Mastering SQL
Mastering SQL
Mastering SQL helps the readers gain a firm understanding of the Structured
Query Language.
Structured Query Language, more often known as SQL, is the de facto
standard language for working with databases. It is a specialised language
for handling data-related tasks like creating a database, putting information
into tables, modifying and extracting that information, and much more.
MySQL, PostgreSQL, Oracle, SQL light, etc. are only a few examples of SQL
implementations.
SQL is a fast and efficient database system. SQL allows for the rapid and
efficient retrieval of huge numbers of data entries from a database. It’s a rela-
tional database. Thus, the data is described in a more orderly fashion than
in an unstructured database like MongoDB. Insertions, d eletions, inquiries,
manipulations, and computations of data through analytical queries in a
relational database may all be performed in a matter of seconds.
With Mastering SQL, learning SQL becomes straightforward; using this
book and resource will undoubtedly help readers advance their careers.
About the Series
The Mastering Computer Science series of books start from the core con-
cepts and then quickly move on to industry-standard coding practices, to
help learners gain efficient and crucial skills in as little time as possible. The
books assume no prior knowledge of coding, so even the absolute newbie
coders can benefit from this series.
The Mastering Computer Science series is edited by Sufyan bin Uzayr, a
writer and educator with over a decade of experience in the computing field.
Edited by
Sufyan bin Uzayr
First Edition published 2024
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742
Reasonable efforts have been made to publish reliable data and information, but the author and
publisher cannot assume responsibility for the validity of all materials or the consequences of
their use. The authors and publishers have attempted to trace the copyright holders of all material
reproduced in this publication and apologize to copyright holders if permission to publish in this
form has not been obtained. If any copyright material has not been acknowledged please write and
let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced,
transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or
hereafter invented, including photocopying, microfilming, and recording, or in any information
storage or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.
com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA
01923, 978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@
tandf.co.uk
Trademark notice: Product or corporate names may be trademarks or registered trademarks and are
used only for identification and explanation without intent to infringe.
DOI: 10.1201/9781003358435
vii
viii ◾ Contents
Characteristics of Transactional 23
Commands for Controlling Transactions 24
Commands for Transactional Control 24
Set Transaction 28
VIEWS IN SQL 29
Views Are Being Removed 31
Views Are Being Updated 32
Delete a Row from a View 34
With Check Option 34
VIEWS AND THEIR APPLICATIONS 35
SQL COMMENTS 36
CONSTRAINTS IN SQL 38
SQL CREATING ROLE 42
Making a Role and Assigning It 42
SQL INDEXES 43
Unique Indexes 44
Clustered Index 45
Non-Clustered Indexes 45
When Should You Construct Indexes? 45
When Indexes Should Be Avoided 45
DROP INDEX 46
ALTERING INDEX 46
CONFIRMING INDEXES 46
RENAMING AN INDEX 46
SEQUENCES IN SQL 47
Query Processing in SQL 49
COMMON TABLE EXPRESSIONS (CTE) IN SQL 50
Defining CTEs 50
Creating a Common Table Expression (Recursive) 50
Types of Common Table Expressions 51
TRIGGERS IN SQL 52
x ◾ Contents
Chapter 2 ◾ Clauses/Operators 63
IN THIS CHAPTER 63
WITH CLAUSE IN SQL 63
WITH TIES CLAUSE IN SQL 66
ARITHMETIC OPERATORS IN SQL 66
Addition Operator (+) 67
Contents ◾ xi
BIBLIOGRAPHY, 235
INDEX, 239
About the Editor
Sufyan bin Uzayr is a writer, coder, and entrepreneur with over a
decade of experience in the industry. He has authored several books in
the past, pertaining to a diverse range of topics, ranging from History to
Computers/IT.
Sufyan is the Director of Parakozm, a multinational IT company spe-
cialising in EdTech solutions. He also runs Zeba Academy, an online
learning and teaching vertical with a focus on STEM fields.
Sufyan specialises in a wide variety of technologies, such as JavaScript,
Dart, WordPress, Drupal, Linux, and Python. He holds multiple degrees,
including ones in management, IT, literature, and political science.
Sufyan is a digital nomad, dividing his time between four countries. He
has lived and taught in universities and educational institutions around
the globe. He takes a keen interest in technology, politics, literature, his-
tory, and sports, and in his spare time, he enjoys teaching coding and
English to young students.
Learn more at sufyanism.com
xix
Acknowledgements
There are many people who deserve to be on this page, and this book
would not have come into existence without their support. That said, some
names deserve a special mention, and I am genuinely grateful to
xxi
Zeba Academy –
Mastering Computer
Science
• Divya Sachdeva.
• Jaskiran Kaur.
• Simran Rao.
• Aruqqa Khateib.
• Suleymen Fez.
• Ibbi Yasmin.
• Alexander Izbassar.
Zeba Academy is an EdTech venture that develops courses and content for
learners primarily in STEM fields, and offers educational consulting and
mentorship to learners and educators worldwide.
Additionally, Zeba Academy is actively engaged in running IT schools
in the CIS countries and is currently working in partnership with numer-
ous universities and institutions.
For more info, please visit https://zeba.academy
xxiii
Chapter 1
IN THIS CHAPTER
➣➣ Basics about SQL
➣➣ Purpose of SQL
➣➣ Features of SQL
➣➣ SQL and its components
➣➣ Introduction to NoSQL
➣➣ Advantages and disadvantages
DOI: 10.1201/9781003358435-1 1
2 ◾ Mastering SQL
KEYS IN SQL
Keys are a fundamental part of the relational database paradigm. They
are used to define and identify relationships between tables, as well as to
identify any record or row of data in a table.
SQL has been around for more than four decades. Nonetheless, it really
has changed massively. Throughout our academics, we all encountered
SQL at a certain point. We are all here to make things better by moving
away from outdated tools and methods. When we learn a system utilising
old methods and procedures, we must internalise it and reconsider its use
in modern industry after you become a member of it. SQL is an abbre-
viation for Structured Query Language. It is a computer language that is
commonly used for Relational Database Management Systems (RDBMS)
and data manipulation.
Understand that SQL is not going away anytime soon. It has only become
stronger as a consequence of corporate objectives such as Microsoft, which
has recently made SQL available for Linux as well. The numerous cloud
products, such as Microsoft Azure and Amazon Web Services – the two
biggest participants in the market – take a much focused approach to the
relational database model, and SQL in particular. And, this is only the
start of a new epoch. When you enter this period, it’s critical that you
understand how things function so that you can take the company you
own or support to new heights.
• For data professionals and SQL users, the most fundamental uses of
SQL are for inserting, updating, and removing data from a relational
database.
• SQL can be used to get data from relational database management
systems for users and data professionals.
• Additionally, it helps with structured data description.
• Databases and tables can be created, deleted, and managed by SQL
users.
• It also facilitates the creation of relational database views, stored pro-
cedures, and functions.
• It enables users to define and update the information maintained in
a relational database.
• SQL clients can also define access and conditions for table columns,
views, and stored procedures.
Basics about SQL ◾ 5
INSTALLATIONS OF SQL
MySQL is an open-source relational database management system that
may be downloaded from the official website at https://dev.mysql.com/
downloads. Start MySQL service after it has been installed (Figure 1.2).
• Optimisation Engines.
• SQL Query Engine.
• Classic Query Engine.
• Query Dispatcher.
Data professionals and users can use a classic query engine to maintain
non-SQL queries. Figure 1.3 illustrates the SQL architectural style.
6 ◾ Mastering SQL
• Aggregated Functions.
• Scalar Functions.
Aggregated Functions
In SQL, an aggregate function adds up a set of values and returns a single
result. A handful of the most regularly used Aggregate Functions are listed
below:
Function Description
Scalar Functions
Scalar functions in SQL return a single value based on the input value.
Some of the most widely used Aggregate Functions are listed below:
Function Description
CHARACTERISTICS OF STRUCTURED
QUERY LANGUAGE (SQL)
In today’s technological environment, regardless of how it appears on
the surface, every programme or development tool ends up translating
queries and other commands into SQL. The characteristics of SQL are
numerous and may be described in greater depth, but we’ve focused on
the most popular and crucial elements that have helped SQL maintain its
prominence to this day. Because of these significant capabilities, no other
database system has been able to attain the same level of success as SQL.
Foundational Relationships
SQL is a relational database language. The tabular layout of a relational
database provides an intuitive user interface, making SQL simple to learn
and use. Furthermore, relational models have a strong theoretical founda-
tion that has influenced relational database development and deployment.
SQL has become the database language for relational databases as a result
of the popularity of the relational paradigm.
High Performance
A significant volume of data is swiftly and efficiently retrieved. Furthermore,
simple data manipulation tasks such as inserting, deleting, and modifying
data can be completed in a short amount of time. SQL is so fast because
a database product must deliver sets of data quickly when requested in
order to be successful. Many of the company’s brightest individuals labour
8 ◾ Mastering SQL
around the clock on the query engine to ensure that it generates ‘optimal’
query strategies that operate quickly.
Scalability
The SQL database is vertically scalable, which means that by adding more
RAM, SSDs, or CPUs, you may increase the load on a single server. Because
of the way data is stored (connected tables vs unrelated collections), SQL
databases can only scale vertically – horizontal scalability is only possible
with NoSQL databases.
Independent Vendors
No new DBMS product has been very successful over the last decade,
despite SQL support being available from all major DBMS manufacturers.
With minimal conversion work, SQL-based databases and programmes
can be moved from one DBMS to another vendor’s DBMS. As a result, ven-
dor independence is one of SQL’s most fundamental characteristics and a
key reason for its early appeal.
Basics about SQL ◾ 9
Dynamic
One of the most significant advantages of SQL over other static databases
is the ability to update and expand a database’s structure dynamically,
even while users are accessing database material. As a result, SQL offers
the most flexibility, allowing online applications to run uninterrupted as a
database adapts to changing needs.
Architecture of Client/Server
A client–server relationship is one in which a client (or a group of clients) is
connected to a server (one). SQL implementation is a natural fit for appli-
cations with distributed client/server systems. A SQL database connects
‘front-end’ computer systems that focus on user interface with ‘back-end’
computer systems that focus on database management, allowing each sys-
tem to perform what it does best. SQL also enables personal computers to
act as a front end to network servers or mainframe databases, allowing
access to corporate data via a desktop application.
Connectivity JDBC (a standard API that allows Java programs to use SQL
for database access). It ensured that SQL would continue to be relevant in
the emerging Java-based programming environment.
DISADVANTAGES OF STRUCTURED
QUERY LANGUAGE (SQL)
Despite all of SQL’s advantages, it also has certain disadvantages, includ-
ing the following:
as binary strings, dates and times, characters, money, dates, and integers,
as specified by the data type attribute of the object. SQL Server comes with
a collection of system data types that describe all of the data types that can
be used with it.
For each database, data types are divided into three categories (Figure 1.4):
of database schemas and is used to build and alter the structure of data-
base objects in the database. In contrast to data, DDL refers to a set of SQL
instructions for adding, removing, and altering database structures. These
steps should not be carried out by a regular user who should be using an
application to access the database.
The DDL commands are listed below:
• Create: The database and its objects are created by this command
(like table, index, function, views, store procedure, and triggers).
In SQL, you can use one of two CREATE statements:
• CREATE A TABLE.
• CREATE A DATABASE.
Make a Database
A database is a planned gathering of data. To store data in a well-struc-
tured manner, the first step with SQL is to establish a database. To build a
new database in SQL, use the CREATE DATABASE statement.
Syntax:
Example:
It creates a new database in SQL and name the database as m database.
Make a Table
We have already learned how to create databases. To save the information,
we’ll need a table. In SQL, the CREATE TABLE statement is used to make
a table. A table is made of rows and columns, as we all know. As a result,
when building tables, we must give SQL with all relevant information,
such as the names of the columns, the type of data to be kept in the col-
umns, the data size, and so on. Let us look at how to utilise the Construct
TABLE statement to create tables in SQL in more detail.
18 ◾ Mastering SQL
Syntax:
where t_name: name of the table; col1, col2, col3: names of the first, sec-
ond and third columns of the table, and data_type: stores the type of data
types we want to store in the particular column.
For example, the data type declared is int for integer data; size: defines
the size we can store in a particular column like we specify the data_type
as int and size as 15 then this column can store an integer with a maxi-
mum capacity limit of 15 digits.
This query will construct a table called Stud_Info, which will have three
columns: R_NO, NAME, and SUBJECT.
A table called Stud_Info will be created as a result of this query. The R_NO
field is of type int and can hold a five-digit integer value. The following two
columns, NAME and SUBJECT, are of type varchar and can store charac-
ters, with the size 35 indicating that these two fields can hold a maximum
of 35 characters.
Examples:
Add to Table
To add columns to an existing table, use ADD. We may occasionally need
to add extra information; in this instance, we do not need to recreate the
entire database; instead, ADD comes to our rescue.
Syntax:
Drop a Table
The DROP COLUMN command is used to remove a column from a table.
The table’s unnecessary columns are removed.
Syntax:
Example:
--(notes, examples)
Example:
UPDATE Stud_Info
SET Date of joining = ‘2014-09-12’
WHERE year of Birth = 1995;
UPDATE customers
SET last_name = ‘Astitiva’
WHERE customer_id = 2;
The task is not yet complete, though, as the other users of the data-
base system won’t be able to detect if we have made any modifica-
tions. To complete the operation, add a COMMIT statement at the
end of the UPDATE block:
UPDATE customers
SET last_name = ‘Astitiva’
WHERE customer_id = 2
COMMIT;
Basics about SQL ◾ 23
UPDATE customers
SET last_name = ‘Astitiva’
WHERE customer_id = 2
COMMIT;
ROLLBACK;
SAVEPOINT savepoint_name;
TRANSACTIONS IN SQL
It is a logical unit of work performed on a database. Transactions are logi-
cally ordered units or sequences of work that can be completed manually
by a human or automatically by a database application. A transaction is
the transmission of one or more changes to the database. An example of
a table transaction would be the creation, update, or deletion of a record
from that table. It is essential to maintain track of these transactions in
order to protect data integrity and handle database concerns.
In practise, you’ll group several SQL queries together and run them all
at the same time as part of a transaction.
Characteristics of Transactional
Transactions contain the four standard qualities listed below, which are
frequently abbreviated as ACID.
24 ◾ Mastering SQL
Commit (Command)
The transactional command COMMIT is used to save changes made by
a transaction to the database. To save changes done by a transaction to
the database, use the transactional verb COMMIT. The COMMIT com-
mand saves all transactions to the database that have occurred since the
last COMMIT or ROLLBACK command.
The COMMIT command has the following syntax:
COMMIT;
Basics about SQL ◾ 25
Example:
Consider the following records in the CUSTOMERS table:
The example below will delete all records in the table with an age of 30 and
then COMMIT the changes to the database.
As a result, one row from the table will be removed, and the SELECT com-
mand yields the following result:
Rollback (Command)
It is a command that allows you to go back in time. The transactional com-
mand is used to undo transactions that have not yet been recorded in the
database. This command can only be used to reverse transactions that
have occurred the last COMMIT or ROLLBACK command.
The ROLLBACK command has the following syntax:
ROLLBACK;
26 ◾ Mastering SQL
Example:
Consider the following records in the CUSTOMERS table:
The following is an example that would delete all records in the table with
the age of 30 and then ROLLBACK the database modifications.
As a result, the delete action has no effect on the table, and the SELECT
command yields the following result.
Savepoint (Command)
It allows you to save a point in time and let us revert to a previous state
without reverting the entire transaction.
The SAVEPOINT command has the following syntax.
SAVEPOINT SAVEPOINT_NAME;
Basics about SQL ◾ 27
ROLLBACK TO SAVEPOINT_NAME;
The example below shows how to delete three separate records from
the CUSTOMERS database. Before each delete, you should create a
SAVEPOINT so that you can ROLLBACK to any SAVEPOINT at any
moment to restore the required data to its previous state.
Example:
Consider the following records in the CUSTOMERS table.
Now that the three deletions have occurred, let us pretend that you
have changed your mind and have decided to ROLLBACK to the SP3
SAVEPOINT. The last two deletions are undone because SP2 was estab-
lished after the initial deletion.
Since you rolled back to SP3, only the first deletion has occurred.
Release Savepoint
It is a command that allows you to release a saved state.
The RELEASE SAVEPOINT command is used to delete a previously
established SAVEPOINT.
The RELEASE SAVEPOINT command has the following syntax.
Set Transaction
It is a command that allows you to set up a transaction. A database trans-
action can be started with the SET TRANSACTION command. This com-
mand is used to define the properties of the next transaction. You can, for
example, make a transaction read-only or read-write.
Basics about SQL ◾ 29
VIEWS IN SQL
Views in SQL are comparable to virtual tables. A view’s rows and columns
are identical to those in a database table. By selecting fields from one or
more database tables, a view can be made. Based on a criteria, a view may
include all of a table’s rows or only a subset of them.
In this article, we will discover how to build, remove, and update views.
To create a View, use the Build VIEW statement. A View can be built using
a single table or several tables.
Syntax:
Examples:
Using a single table to create a View:
In this example, we’ll use the table StudentDetails to create a View
called DetailsView.
30 ◾ Mastering SQL
Query:
To see the data in a view, we can query it similarly to how we query a table.
Output:
Name Address
Alex New York
Joshua Vegas
Nick Maryland
Johnny Boston
Query:
If we now query the view as, we’ll get the following results.
Output:
Sn_ID Name
LRB123 Alex
LRB124 Joshua
LRB125 Nick
LRB126 Johnny
Basics about SQL ◾ 31
Query:
Output:
Syntax:
Syntax:
For illustrate, if you wanted to modify the MarksView view and include
the AGE field from the StudentMarks Table, we could accomplish it as
follows:
Output:
Example: In the example below, we will add a new row to the View
DetailsView that we constructed before in the “building views from
a single table” section.
Output:
Name Address
Alex New York
Joshua Vegas
Nick Maryland
Johnny Boston
Jaques Texas
34 ◾ Mastering SQL
Syntax:
Example:
In this case, we’ll delete the last row from the DetailsView view, which we
just put in the previous row-inserting example.
Output:
Name Address
Alex New York
Joshua Vegas
Nick Maryland
Johnny Boston
VIEW statement, and the UPDATE or INSERT clause does not meet the
conditions, an error will be returned.
Example: Using the WITH CHECK OPTION clause, we create a View
SampleView from the StudentDetails Table.
This view was constructed with the NOT NULL condition for the NAME
column, so if we attempt to insert a new row with a null value in the Name
column, we would see an error.
For example, despite the fact that the view is updatable, the following
query for this View is invalid:
SQL COMMENTS
Comments can help you read and manage your application more easily.
For example, you can add a comment to a statement that explains what the
statement’s purpose is in your application. Comments in SQL statements,
with the exception of hints, have no effect on the statement’s execution.
In a statement, a comment can exist between any keywords, param-
eters, or punctuation marks. There are two ways to include a comment in
a statement:
Use a slash and an asterisk (/*) to start your comment. Continue with
the comment’s text. This text may be split across numerous lines. An aster-
isk and a slash (*/) should be used to close the comment. A space or a line
break is not required to separate the opening and closing characters from
the text. Begin your comment with the word – (two hyphens). Continue
with the comment’s text. This text isn’t long enough to fill a new line. A
line break should be used to end the comment. Additional limits apply to
certain of the tools used to enter SQL. Multiple comments of both forms
can be found in a SQL statement. The text of a remark may contain any
printable characters from your database’s character set.
The following three formats are available for making comments:
are regarded to be the start of a comment and are deleted when ‘*/’
appears.
Syntax:
/* multi-line comment
another comment */
SELECT * FROM Customers;
Example:
There are numerous comments in these statements:
CONSTRAINTS IN SQL
Constraints are the guidelines that the data columns in a table must adhere
to. These are used to restrict what kinds of data can be added to tables. This
guarantees the database’s data’s dependability and accuracy. At the level of
the column or table, constraints can be used. The column level constraints
only apply to one column, while the table level constraints are applied to
the entire table.
In SQL, the following constraints are available:
The following restrictions are possible in SQL:
• Unique: Each table row can be uniquely identified with the help of
this constraint. In other words, all rows should have the same value
for a given column. We can have a lot of unique columns in a table.
40 ◾ Mastering SQL
Orders
ID O_NO C_ID
1 22 2
2 33 4
3 44 3
4 55 1
Basics about SQL ◾ 41
Customers
ID NAME ADDRESS
1 NAME NOIDA
2 MAHESH GURGAON
3 SURESH DELHI
The field C_ID in the Orders table is clearly the main key in the Customers
table, i.e., it uniquely identifies each row in the Customers dataset. As a
result, the Orders table has a Foreign Key.
Syntax:
For instance, the following query will create a table called Student
and set the column AGE’s default value to 18.
Syntax:
The syntax for the role that has to be formed is called ‘manager’.
• Now that the role has been formed, the DBA can assign users to it
and assign privileges to it using the GRANT statement.
Basics about SQL ◾ 43
Drop a Role:
SQL INDEXES
A SQL index is a type of index that allows you to quickly access data from
a database. Without a question, one of the best methods to improve query
and application performance is to index a database or view. A SQL index
is a rapid lookup table used to find frequently sought records. An index
is a data structure that is tiny, fast, and optimised for speedy lookups.
44 ◾ Mastering SQL
It’s great for linking relational tables and searching huge databases. In
SQL Server, indexes are utilised to speed up the query process, resulting
in excellent performance. They’re a lot like textbook indexes. If you need
to get to a certain chapter in a textbook, you go to the index, identify the
chapter’s page number, and go straight to that page. Finding your selected
chapter would have been extremely time consuming without indexes.
The same can be said for database indexes. Without indexes, a data-
base management system (DBMS) must go through all of the records in a
table to extract the needed results. This is known as table-scanning, and
it is a very slow procedure. When you create indexes, on the other hand,
the database looks for the index first and then obtains the table records
directly.
Syntax for creating Index
where the index is given a name, TABLE is the name of the table on which
the index is constructed, and column is the name of the column to which
it is applied.
Unique Indexes
Unique indexes are used to maintain the integrity of the data in the table
as well as to improve performance by preventing multiple entries from
being entered into the table.
Syntax:
Clustered Index
A clustered index specifies the physical order in which data is stored in a
table. Each table can only include one clustered index since there is only
one manner in which table data can be sorted. The primary key constraint
in SQL Server automatically constructs a clustered index on that column.
Non-Clustered Indexes
The physical data inside the table is not sorted by a non-clustered index. In
reality, a non-clustered index is kept in one location while table data is kept
in another. This is similar to how a textbook is organised, with the infor-
mation in one location and the index in another. This allows each table to
have multiple non-clustered indexes.
It’s worth noting that the data inside the table will be sorted using a
clustered index. However, data is saved in the desired order within the
non-clustered index. The index contains the index’s column values as well
as the address of the record to which the column value belongs.
DROP INDEX
This command, you can delete an index from the data dictionary.
Syntax:
You must be the index owner or have the DROP ANY INDEX privilege to
drop an index.
ALTERING INDEX
Altering an Index entails rebuilding or restructuring the index of an exist-
ing table.
CONFIRMING INDEXES
You can verify the uniqueness of the different indexes present in a table
given by the user or the server.
Syntax:
It will display all of the server’s indexes, where you may also find your own
tables.
RENAMING AN INDEX
You can rename any index in the database using the system stored func-
tion sp rename.
Syntax:
EXEC sp_rename
index_name,
new_index_name,
N’INDEX’;
Basics about SQL ◾ 47
SEQUENCES IN SQL
A sequence is a collection of integers, such as 1, 2, 3, and so on, that some
database systems construct and support in order to instantly produce
unique values. A sequence is a schema-bound user-defined object that gen-
erates a list of numeric values. Many databases employ sequences because
many applications need that each row in a table include a unique value,
and sequences give an easy way to do so. The sequence of numeric num-
bers is generated at defined intervals in ascending or descending order,
and it can be adjusted to resume when the max value is exceeded.
Syntax:
Example:
The sequence query that creates the sequence in ascending order is shown
below.
48 ◾ Mastering SQL
Example 1:
The query above will result in the creation of a sequence named sequence
1. The sequence will begin at 1 and will be incremented by 1 until it reaches
a maximum value of 100. After exceeding 100, the sequence will repeat
itself from the beginning.
Example 2:
Create a series in descending order using the sequence query.
The sequence 2 will be created as a result of the query above. The sequence
will begin at 100 and will be incremented by −1 with a minimum value of
1 and should be less than or equal to the maximum value.
Create a table called students with the columns id and name as an
example of how to utilise sequence.
where sequence 1. Nextval will add ids to the id column in the sequence
defined in sequence 1.
ID Name
LB 1 Johnny
LB 2 Simon
into equivalent expressions that are more efficient to execute. The third
step is Query evaluation which will execute the above query execution
plan and returns the result.
Defining CTEs
CTEs can be defined by including a WITH clause before any SELECT,
INSERT, UPDATE, DELETE, or MERGE statement. One or more CTEs
can be separated by commas in the WITH clause. You can use the follow-
ing syntax:
[WITH [, ...]]
::=
cte_name [(column_name [, ...])]
AS (cte_query)
You can then refer to the CTEs as you would any other table after you’ve
defined your Using clause with the CTEs. You can only refer to a CTE
within the execution scope of the statement that comes after the WITH
clause. The result set is not available to other statements once you’ve run
your statement.
used to show the hierarchy of employee data. A CTE might become stuck
in an infinite loop if it is built incorrectly. The MAXRECURSION hint
can be appended to the OPTION clause of the primary SELECT, INSERT,
UPDATE, DELETE, or MERGE statement to prevent this.
• Non-Recursive CTEs
Non-Recursive CTEs are simple CTEs that do not employ
recursion or repeat processing in a subroutine. We’ll make a sim-
ple non-recursive CTE to show the number of rows from 1 to 10.
Each and every CTE query will begin with a “With,“ followed by
the CTE Expression name and column list, according to the CTE
Syntax.
Example: Create a table
WITH
cteReports (Emp_ID, F_Name, L_Name, M_ID, EmpLevel)
AS
(
SELECT Emp_ID, F_Name, L_Name, M_ID, 1
FROM Empl_Info
WHERE M_ID IS NULL
UNION ALL
SELECT e.Emp_ID, e.F_Name, e.L_Name, e.M_ID,
r.EmpLevel + 1
FROM Empl_Info e
INNER JOIN cteReports r
ON e.M_ID = r.Emp_ID
)
SELECT
F_Name + ‘ ‘ + L_Name AS Full Name,
EmpLevel,
(SELECT F_Name + ‘ ‘ + L_Name FROM Empl_Info
WHERE Emp_ID = cteReports.M_ID) AS Manager
FROM cteReports
ORDER BY EmpLevel, M_ID
When you need to build temporary result sets that can be retrieved in a
SELECT, INSERT, UPDATE, DELETE, or MERGE statement, CTEs can
be a handy tool.
TRIGGERS IN SQL
A trigger is a database stored procedure that is automatically invoked
whenever a specific event happens in the database. A trigger can be trig-
gered when a row is entered into a table or when particular table columns
are modified, for example.
Syntax Explanation:
The above SQL line will build a trigger in the student database so that any-
time subjects marks are entered, the trigger will compute those two values
and insert them with the entered values before entering the data into the
database. i.e.
• 1998: Carlo Strozzi used the name ‘NoSQL’ to describe his light-
weight, open-source relational database Neo4j is released in 2000.
• Google BigTable was launched in 2004.
• CouchDB was launched in 2005.
• The research paper on Amazon Dynamo is published in 2007.
• Facebook releases the Cassandra project to the public in 2008.
• The phrase NoSQL was resurrected in 2009.
• Key-value
• Column-oriented based on pairs
• Graphs-based
• Document-oriented Graphs
KEY-VALUE
They are used to store data, and they are made to withstand tremendous
loads and big amounts of data. Key-value pair storage databases employ
hash tables to store data; each key must be unique, and the value may be in
text, JSON, BLOBs (Binary Large Objects), or another format.
COLUMN-BASED
These are based on Google’s BigTable paper and function with columns.
Each column is dealt with independently. The values of single-column
databases are kept together.
58 ◾ Mastering SQL
DOCUMENT-ORIENTED
The value part of a NoSQL DB’s data is kept as a document, while the key-
value pair is stored as a key-value pair. JSON or XML formats are used to
store the document. The database recognises the value and can be queried.
CMS systems, blogging platforms, real-time analytics, and e-commerce
apps all use this document type. It should not be used for complex trans-
actions involving several operations or queries against different aggregate
models.
Popular Document DBMS systems include Amazon SimpleDB,
CouchDB, MongoDB, Riak, Lotus Notes, and MongoDB.
GRAPH-BASED
This maintains both entities and the relationships between them. The
entity is represented as a node, while the relationships are represented as
edges. An edge establishes a connection between nodes. A unique iden-
tifier is assigned to each node and edge. It is multi-relational in nature,
as opposed to a relational database, which has loosely connected tables.
Traversing relationships is quick because they are already stored in the
database and don’t need to be calculated. Graph databases are commonly
used for social networks, logistics, and geographic data.
Popular graph-based databases include Neo4J, Infinite Graph,
OrientDB, and FlockDB.
FEATURES OF NoSQL
The following are the feature:
Schema-Free
Distributed
• Consistency
• Availability
• Tolerance for Partitions
Consistency
Even after an operation has been completed, the data should stay consis-
tent. This indicates that once data is written, it should be included in any
subsequent read requests. After altering the order status, for example, all
clients should be able to see the same information.
Availability
The database should be accessible and responsive at all times. There should
be no downtime.
inconsistent at first, but with time, they become consistent. As a result, the
term ‘ultimate consistency’ was coined.
BASE stands for Basic Availability, Soft State, and Eventual Consistency.
According to the CAP theorem, availability indicates that the database
is available at all times.
The term ‘soft state’ refers to a system’s ability to alter even when no
input is provided.
The term ‘eventual consistency’ refers to the system’s ability to become
consistent over time.
ADVANTAGES
Working with NoSQL databases such as MongoDB and Cassandra has
numerous advantages like high scalability and availability:
DISADVANTAGES
NoSQL has the following drawbacks:
SUMMARY
In this chapter, we have covered all the fundamentals of SQL, including
commands, statements, data types, views, comments that create roles,
indexes, query processing, CTE, database management, and a quick intro-
duction to NoSQL.
NOTE
1 Codd, E.F., 1983. A relational model of data for shared data banks.
Communications of the ACM, 26(1), pp. 64–69.
Chapter 2
Clauses/Operators
IN THIS CHAPTER
• Operators in arithmetic
• Operators for comparison
• Operators logical
• Negative operators were employed to negate conditions
DOI: 10.1201/9781003358435-2 63
64 ◾ Mastering SQL
• The clause is used to define a temp relation so that the output of this
temporary relation is available and can be used by the query con-
nected with it.
• Queries with a linked WITH clause can be created with nested sub-
queries, which improves the readability and debug ability of the SQL
query.
• All database systems don’t support the WITH clause.
• The name given to the sub query is treated as if it were a table or
inline view.
• Oracle introduced the WITH clause in the Oracle release 2 database.
Syntax:
WITH temporaryTable (averageValue) as
(SELECT avg(Attr1)
FROM Table)
SELECT Attr1
FROM Table, temporary Table
WHERE Table.Attr1 > temporary Table.average value;
The WITH clause is used to create a temp table with only one attribute,
average Value. The average value of column Attr_1 in relation Table
is stored in average Value. Following the WITH clause, the SELECT
statement will return those tuples in which the value of Attr1 in rela-
tion Table is greater than the avg value acquired from the that clause
statement.
When a query with a WITH clause is run, the clause query is evalu-
ated first, and the result of that evaluation is saved in a temporary rela-
tion. The primary query linked with the WITH clause is then eventually
executed, that uses the temporary relation created.
Queries:
Example 1: Here, we identify all employees whose salaries are higher than
the average of all employees.
Clauses/Operators ◾ 65
Query in SQL:
WITH temporary Table(averageValue) as
(SELECT avg(Salary)
from Employee)
SELECT EmployeeID,Name, Salary
FROM Employee, temporaryTable
WHERE Employee.Salary > temporaryTable.
averageValue;
Output:
Example 2: Locate those airlines in which the whole salary of all pilots in
that airline exceeds the database’s average total salary of all pilots. Pilot is
the name of the relationship.
Explanation: The overall income of all Air India pilots is 66,016.6, while
the total salary of all Jet Airways pilots is 37,500. In the table Pilot, the
average income of all pilots is 58,971.6. Because only the total income of all
Air India pilots is more than the average salary, Air India is in the output
relationship.
Output:
Airline
Air India
When dealing with sophisticated SQL statements rather than basic ones,
the SQL WITH clause comes in handy. It also allows you to split down
large SQL queries into smaller chunks, making debugging and processing
the queries much easier. The WITH clause in SQL is essentially a drop-in
replacement for the subquery.
Syntax:
Output:
Addition
430
The table lists numerous employees and their contact information. Let’s
combine the two columns together in the SALARY column. The SALARY
column is increased by 10,000 in the query below.
Output:
N_Salary
40,000
55,000
60,000
45,000
Let’s add two columns together using the addition operator, as indicated
in the query below.
SELECT SALARY+ID as add_salary FROM EMPLOYEES;
The above query has following results, along with the salary and ID
columns.
Output:
Add_Salary
40,100
55,150
60,185
452,000
Subtract
260
Take, for example, the table ‘EMPLOYEES’ that was previously men-
tioned. We can see that 500 is deducted from the SALARY column in the
query below.
Output:
S_Sal
29,500
44,500
49,500
34,500
The ID column is deducted from the SALARY columns in the above query,
and the result is as follows:
N_Sal
29,400
44,350
49,315
34,300
Output:
Multiplication
800
Using the EMPLOYEES table as a starting point, multiply the column
SALARY by 15 as indicated below:
The above query has following results, and we can see that the SALARY
column is multiplied by 10.
70 ◾ Mastering SQL
Multi_Salary
300,000
450,000
500,000
350,000
The following query shows the multiplication of two columns from the
table EMPLOYEES, namely, SALARY and ID.
Output:
A_Salary
300,000
6,750,000
9,250,000
7,000,000
Output:
Division
4
Consider the table ‘EMPLOYEES’, which we previously discussed. The
query below shows how the column SALARY is divided by 5 in the divi-
sion operation.
Sal_Div
6,000
9,000
10,000
7,000
Modulus Operator(%)
The residual of the division of the left-hand side operand by the right-hand
side operand is obtained using this arithmetic operator.
Result:
0
The SALARY column of the EMPLOYEES table below is used to per-
form the modulus operation.
The above query conducts the modulus operation, and when the employ-
ees’ salaries are divided by 100, the result shows the division’s remaining
values, is mentioned as output.
Salary
300
450
500
350
BB% allows us to search for strings that start with BB and end with another
single character or multiple characters.
Clauses/Operators ◾ 73
Or
We can use %BB% percent to find strings that start with any number of
characters but contain the string BB in the middle and end with any num-
ber of characters between 0 and infinity.
Or
SELECT FROM table_name
WHERE column LIKE ‘_BB’
_BB allows us to search for strings that start with a single distinct charac-
ter and end with the character BB.
Or
We can use BB_ to find any strings that start with the BB pattern and ter-
minate with a single different character.
Or
_BB_ allows us to search for strings that start with a unique charac-
ter, contain the pattern BB in the middle, and end with a single unique
character.
Regular Expressions and wildcard characters both perform the same
thing. To improve search outcomes and results, we can mix numerous
wildcards in a single string. A distinct SQL wildcard could be used for a
similar function in a few databases, such as MS Access.
Syntax:
SELECT column-1, column-2 ……
FROM table 1
WHERE…..
INTERSECT
SELECT column-1, column-2 ……
FROM table 2
WHERE…..
Syntax:
SELECT ID, Name, Bonus
FROM
table1
LEFT JOIN
table2
ON table1.ID = table2.Employee_ID
INTERSECT
SELECT ID, Name, Bonus
FROM
table1
RIGHT JOIN
table2
ON table1.ID = table2.Employee_ID;
EXCEPT CLAUSE
ID Name Bonas(Dollar)
1 William 45,000
2 Kevin 72,000
3 Nick 30,000
Clauses/Operators ◾ 75
The inverse of the INTERSECT clause is the EXCEPT clause. In this case,
all rows outside of the shared rows between the two SELECT statements
are included in the result.
The syntax is as follows:
Query:
SELECT ID, Name, Bonus
FROM
table1
LEFT JOIN
table2
ON table1.ID = table2.Employee_ID
EXCEPT
SELECT ID, Name, Bonus
FROM
table1
RIGHT JOIN
table2
ON table1.ID = table2.Employee_ID;
USING CLAUSE
3 Nick Null
If numerous columns have the same names but different datatypes, the
NATURAL JOIN clause can be changed with the USING clause to desig-
nate which columns should be used for an EQUIJOIN. When more than
one column matches, the USING Clause is used to match only one of them.
76 ◾ Mastering SQL
Syntax:
SELECT <table_name>.<column_name> AS <column_name>
FROM <table_name> JOIN <table_name> USING
(<column_name>)
Table: Owner
Owner ID Nick
123 Tiru
134 Tarous
156 Surfit
Output:
Product List:
Updated List:
The goal is to update the PRODUCT LIST’s product data to match the
UPDATED LIST.
Solution
Let’s break down this example into steps to make it easier to understand.
PRODUCT_LIST
12 Bakery 30.00
UPDATED_LIST
12 Bakery 39.00
80 ◾ Mastering SQL
PRODUCT_LIST
14 tea 45.00
UPDATED_LIST
17 Juices 75.00
2. Operation DELETE
14 TEA 45.00
Output: PRODUCT_LIST
So, with the help of the MERGE statement, we can conduct all three pri-
mary statements in SQL at the same time.
set of values). The user who creates a domain becomes the owner of that
domain. The domain is formed in the supplied schema if a schema name is
specified (for example, CREATE DOMAIN myschema.mydomain...).
If not, it will be created in the current schema. The domain name must
be distinct from the other kinds and domains in the schema. Domains are
useful for storing and maintaining common field constraints in a single
location. For example, numerous tables may contain email address col-
umns, all of which require the same CHECK constraint to ensure that
the address syntax is correct. Rather of setting up each table’s constraint
individually, define a domain.
Parameters: There are various parameters in create domain:
üüName
üüData type
The domain’s underlying data type. Array specifiers are an example of this.
üüCollation
A collation for the domain that is optional. If no collation is supplied, the
default collation of the underlying data type is utilised. If COLLATE is
given, the underlying type must be collatable.
üüEXPRESSION BY Default
The default value is provided via the DEFAULT clause for columns with
the domain data type. Any variable-free expression can be used as the
value (but subqueries are not allowed). The default expression’s data type
must match the domain’s data type. If no default value is supplied, the null
value is used as the default.
Any insert operation that does not specify a value for the column will
use the default expression. Any default connected with the domain is
overridden if a default value is provided for a specific column. As a result,
any default value associated with the underlying data type is overridden
by the domain default.
üüNOT NULL
Clauses/Operators ◾ 83
üüNULL
This domain’s values are allowed to be null. This is the default behaviour.
This clause is only for compatibility with SQL databases that aren’t stan-
dard. Its use in new applications is discouraged.
üüCHECK (expression)
The CHECK clauses define the integrity restrictions or tests that the domain’s
data must pass. Each constraint must be a Boolean result-producing expres-
sion. The key term VALUE should be used to refer to the value being exam-
ined. TRUE or UNKNOWN evaluating expressions succeed. If the result of
the expression is FALSE, an error is reported, and the value cannot be changed
to the domain type. CHECK expressions can’t have subqueries or refer to
variables other than VALUE right now. When there are several CHECK con-
straints in a domain, they are tested in alphabetical order by name.
After you’ve specified these domains, you may use them in the same way
that you’d use the built-in data types. These definitions, for example, can
be used to create the following tables.
The variable @col is used in this check constraint. You can rewrite the
above-mentioned definition of the customer table using this definition.
CREATE TABLE customer (
id identifier PRIMARY KEY
name persons_name
address street_address
)
Syntax:
CREATE DOMAIN name [ AS ] data_type
[ COLLATE collation ]
[ DEFAULT expression ]
[ constraint [ ... ] ]
where constraint is:
[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | CHECK (expression) }
Clauses/Operators ◾ 85
Examples:
The Indian postal code data type is created in this example, and it is then
used in a table definition. To ensure that the value appears like a genuine
Indian postal code, a regular expression test is used:
DESCRIBE STATEMENT
The SQL DESCRIBE TABLE command is responsible for providing infor-
mation about a certain table in the database. To display the structure
of a database table or tables on the server, we’ll use the SQL command
DESCRIBE or another term DESC, which is equal to DESCRIBE. We’ll
use either DESCRIBE or DESC to retrieve information about the table in
the database and locate the properties associated with it. Both are Case
Insensitive and yield comparable results. We use the DESCRIBE TABLE
query to acquire information on the name of the column, its data type, its
NULL or NOT NULL properties, and the table’s database size accuracy, as
well as the If NUMERIC type scale.
Syntax:
DESCRIBE one;
OR
DESC one;
Note that we can use DESCRIBE or DESC (both are Case Insensitive).
Assume our table, named one, has three columns: F_NAME, L_NAME,
and SALARY, each of which can have null values.
86 ◾ Mastering SQL
Output:
We may see the structure of a table using DESC or DESCRIBE, but not on
the console tab; the structure of a table is visible in the describe tab of the
Database System Software. So, the desc or describe command displays the
table’s structure, which includes the column name, data type, and nullabil-
ity, which indicates whether the column may store null values or not. All
of these characteristics of the table are described at the time of its creation.
Consider the following scenario:
We built a table with the name one and the columns S_ID, S_NAME,
and S_ID is of the non-null type, which means we can’t put null values in
the S_ID column but can in the S_NAME field.
To explain DESC, consider the following example:
DESC one
OR
DESCRIBE one
Clauses/Operators ◾ 87
Output:
The ID field is not null; however, the other two columns can have null val-
ues. We must use the DESC command solely on your system software; it
will not work in any editor. Make sure you’re only running this command
on your own database.
CASE
WHEN condition1 THEN stuff
WHEN condition2 THEN other stuff
...
ELSE default stuff
END
88 ◾ Mastering SQL
ID Name Score
1 Simon 60
2 Iris 80
3 Maliki 52
4 Chrissy 98
5 Lemma 84
6 Alex 82
7 Uranus 69
8 Raza 78
9 Calvin 87
10 Alvin 57
11 Gabriela 89
12 Marcel 99
13 Christopher 55
14 Nick 81
15 Elvin 71
16 Leo 90
17 Johnny 90
18 Anais 90
19 Ryan 97
20 Simpson 61
21 Elena 63
22 Kathrin 51
We may use the CASE statement to assign a grade to each student, which
will be stored in a new column called grade. Let’s start by writing the
CASE statement, which will include the grade breakdown. If the score is 94
or higher, the row will be given the value of A. If the score is 90 or greater,
it will be assigned the letter A-, and so on.
Clauses/Operators ◾ 89
CASE
WHEN score >= 94 THEN “A++”
WHEN score >= 90 THEN “A+”
WHEN score >= 87 THEN “B++”
WHEN score >= 83 THEN “B+”
WHEN score >= 80 THEN “B-”
WHEN score >= 77 THEN “C++”
WHEN score >= 73 THEN “C+”
WHEN score >= 70 THEN “C-”
WHEN score >= 67 THEN “D++”
WHEN score >= 60 THEN “D+”
ELSE “F”
END
We’ll use the CASE statement in a query after we’ve written it. Then, using
the AS keyword, we’ll give the column the name grade:
SELECT *,
CASE
WHEN score >= 94 THEN “A++”
WHEN score >= 90 THEN “A+”
WHEN score >= 87 THEN “B++”
WHEN score >= 83 THEN “B+”
WHEN score >= 80 THEN “B-”
WHEN score >= 77 THEN “C++”
WHEN score >= 73 THEN “C+”
WHEN score >= 70 THEN “C-”
WHEN score >= 67 THEN “D++”
WHEN score >= 60 THEN “D+”
ELSE “F”
END AS grade
FROM students_grades;
The table returned by this query looks like this – each student now has a
grade based on their performance.
Name Grade
Simon D+
Iris B-
Maliki F
Chrissy A++
Lemma B++
Alex B+
Uranus D++
Raza B-
Calvin B++
Alvin F
Gabriela B++
Marcel A++
Christopher F
Nick B-
Elvin C-
Leo A+
Johnny A+
Anais A+
Ryan A++
Simpson D+
Elena D+
Kathrin F
SELECT
CASE
WHEN score >= 94 THEN “A++”
WHEN score >= 90 THEN “A+”
WHEN score >= 87 THEN “B++”
WHEN score >= 83 THEN “B+”
WHEN score >= 80 THEN “B-”
WHEN score >= 77 THEN “C++”
92 ◾ Mastering SQL
Because score is a number, we use Sort BY to order the grades from highest
to lowest (because ordering by the grade column would employ an alpha-
betical order, which is different from the order of the grades by value).
Grade Number_of_Students
A++ 3
A- 3
B++ 2
B+ 1
B- 3
C+ 1
C- 1
D+ 1
D 3
F 4
The case statement is a helpful tool when you need values based on specific
conditions.
To ensure that the information stored in the columns that are a part of the
UNIQUE constraint is unique, SQL Server creates a UNIQUE index in the
background. As a result, attempting to insert a duplicate record will result
in SQL Server rejecting the modification and returning an error message
stating that the UNIQUE constraint has been violated.
The sentence below creates a new row in the Hr_persons table:
If you don’t give the UNIQUE constraint a unique name, SQL Server will
come up with one for you. The constraint name in this case is UQ people
LR7E617240E, which is not very readable.
The CONSTRAINT keyword is used to assign a specific name to a
UNIQUE constraint, as shown below:
If you try to insert another NULL into the email column now, you’ll get
the following error:
The unique phone constraint in the Hr_persons table is removed using the
following statement:
Change the Limitations that are Unique. Because there is no direct query
in SQL Server to modify a UNIQUE constraint, you must drop the con-
straint first and then recreate it if you wish to update it.
Clauses/Operators ◾ 97
Syntax:
CREATE TABLE newTable LIKE pets;
Example:
CREATE TABLE newTable as
(SELECT *FROM pets
WHERE pets.BREED = ‘shitzu’)
Queries:
Pets Table:
Query 1:
CREATE TABLE newTable LIKE pets;
SELECT *
FROM newTable
where newTable.GENDER = ‘Female’;
Result:
Query 2:
CREATE TABLE newTable as
(SELECT *
FROM pets
WHERE pets.BREED = ‘German Shepherd’);
SELECT * from newTable;
Output:
Primary, the inner query is executed, then the results are saved in a new
temporary relation. The outer query is then evaluated, which creates
newTable and adds the output of the inner query to it.
RENAME IN SQL
Database administrators and users may want to change the name of a
table in a SQL database in order to give it a more relevant name in some
cases. By using the RENAME TABLE and ALTER TABLE statements in
Structured Query Language, any database user can quickly modify the
name. The RENAME TABLE and ALTER TABLE syntax can be used to
change the table’s name.
In SQL, the RENAME query has the following syntax.
RENAME old_table _name to new_table_name;
Table: Automobiles
• Let’s say you wish to rename the above table ‘Car 2022 Details’. You
must type the following RENAME query in SQL to accomplish this.
• Following this statement, the table ‘Cars’ will be renamed ‘Car 2021
Details’.
Let’s say you wish to use an ALTER TABLE statement to rename the afore-
mentioned table to ‘Coding Employees’. The SQL query to enter for this is
as follows:
Syntax:
ALTER TABLE table_name
ADD (Columnname_1 datatype,
Columnname_2 datatype,
…
Columnname_n datatype);
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
Syntax:
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
Roll_No. Name
1 Ram
2 Abhi
3 Tanu
4 Rahul
Query:
Output:
After running the preceding query, the maximum size of the Course
Column is reduced from 40 to 20.
Output:
LIMIT CLAUSE
One of the most crucial clauses in SQL is LIMIT. Developers must filter
their scripts when working with enormous databases in order to get to the
precise number. This is the function of LIMIT, which aids in providing you
with the necessary outcomes in the manner you desire, in a well filtered
manner.
shown at once even if the question requirements are met for many of them.
The LIMIT clause limits the number of tuples that SQL can return.
The SQL LIMIT operator can be used when you need to pick the top three
students in a class without using any conditional statements.
The value of OFFSET must be larger than zero or equal to it. Negative feed-
back is not an option since errors would then recur.
Give an Example to Clarify: The LIMIT clause in MySQL controls how
many logs are returned.
If you decide to choose any record between 1 and 30 from the ‘Orders’
table, the SQL query will look like this:
When the aforementioned SQL query was run, they returned the first 30
records.
What if you wish to choose 16 to 25 records (including)?
Using OFFSET in MySQL is another option.
The SQL statement “return only 10 records, launch record 16 (OFFSET
15)” reads as follows: $sql = “SELECT * FROM Orders LIMIT 10
OFFSET 15”;
SELECT
select list
FROM
table name
Queries:
SELECT *
FROM Student
LIMIT 5;
Output:
1201 Adi 9
1202 Suhail 6
1203 Himani 8
1204 Rob 9
1205 Sita 7
104 ◾ Mastering SQL
SELECT *
FROM Student
ORDER BY Grade DESC
LIMIT 3;
Output:
12006 Anne 10
12001 Aditya 9
12004 Robin 9
When we need to identify the top three students in a class but do not want
to use any conditional statements, we can utilise the LIMIT operator in
cases like the one described above.
Parameters or Arguments
• Expressions: The computations or columns that you want to get back.
• Tables: The tables from which you want to get records. The FROM
clause must list one table at a minimum.
• Where Conditions: the prerequisites that must be satisfied in order
to choose the records.
• Order by Expression: It is used in the SELECT LIMIT statement to
help you target the records you want to return and order the results.
Ascending order is ASC, and descending order is DESC.
• Limit Number_Rows: It determines the maximum number of result
set rows depending on number rows that will be returned. With
LIMIT 10, for instance, the first 10 entries that satisfy the SELECT
criteria would be returned. Sort order is important in this situation,
therefore employ an ORDER BY clause wisely.
• Offset_Value: LIMIT will use offset value to select which row to
return first.
• The LIMIT number can be any number between 0 and 255. If the
LIMIT is set to zero (0), no rows are returned from the set result.
Clauses/Operators ◾ 105
• You can choose which line to start the data recovery on using the
OFFSET value.
• The Syntax of LIMIT works well with the Choose Update or DELETE
order.
Mysql will issue a warning and insert all the proper records while leaving
out and excluding the rows that were the cause of the mistake if we use
INSERT IGNORE instead of simply a simple insert command.
Syntax:
The INSERT IGNORE statement’s syntax is as follows:
Drawback
Since certain errors could go unreported, most users do not favour
INSERT IGNORE over INSERT. This might lead to discrepancies in the
table, which would prevent some tuples from being inserted without giv-
ing the user an opportunity to fix them. Thus, INSERT IGNORE must
only be used in very particular circumstances.
Example: Say we have a relation, Employee.
Employee Table:
As we can notice, the entries are not sorted on the basis of their primary
key, i.e., Emp_ID.
Sample Query:
Output:
No entry inserted.
Output:
The first and last entries are added; the intermediate entry is merely disre-
garded. No error message flashes.
As Mysql attempts to change the values to arrange them in the cor-
rect manner and inserts the correct records except the one that can create
an issue, using the INSERT IGNORE statement rather than just inserting
statements is always a recommended practise.
LIKE OPERATOR
To determine whether a particular character string matches a given pat-
tern, the logical operator SQL Like is employed. It is typically utilised in a
Where clause to search for a specific pattern in a column. When pattern
matching is required rather than equal or not equal, this operator can be
helpful. When we wish to return a row if a given character string matches
a predetermined pattern, we utilise the SQL Like function. Regular char-
acters and wildcard characters may both be used in the pattern. Regular
characters must exactly match the characters supplied in the character
string in order to return a row. Any portion of the character string can be
matched using the wildcard characters.
Syntax:
The following wildcard characters can be used with the LIKE operator to
specify a pattern:
108 ◾ Mastering SQL
Pattern Description
The percentage matches 0–1, multiple capital or small-capital characters, or
numbers.
%
E.g., ‘B%’ will match all string starting with ‘B’ further followed by any number of
characters or numbers.
Any single letter or number can be represented by the underscore (_) symbol.
_ E.g., ‘B_’ will match all strings with two chars where the first character must be ‘B’
and second character can be anything.
The [] searches any single character within the specified range in the [].
[]
E.g., ‘B[e,l,p]’ will match ‘Ball’, ‘Bat’, ‘Bird’ etc.
The [^] seaches any single character except the specified range in the [^].
[^] E.g., ‘B [^e,l,p]’ will match anything that starts with ‘B’, but not ‘Bpple’, ‘Belp’,
‘Blep’, ‘Bple’, etc.
When using the LIKE operator, these wildcard characters can be used sin-
gly or in combination.
For example: Let us use Employee info table in all the examples:
Query 1:
SELECT *
FROM Employee
WHERE FirstName LIKE ‘john’;
The query WHERE FirstName LIKE ‘john’ above searches all the records
in the MS SQL Server, SQLite, and MySQL databases where the value of
the FirstName column is ‘john’ or ‘John’. But with Oracle and PostgreSQL
databases, the LIKE operator is case-sensitive, so it only retrieves entries
where the value is ‘john,’ not ‘John. The outcome in the MS SQL Server,
SQLite, and MySQL databases is as follows.
SELECT *
FROM Employees
WHERE FirstName LIKE ‘j%’;
The aforementioned query retrieves all records from the MS SQL Server,
SQLite, and MySQL databases where the value of the First Name col-
umn begins with either “j” or “J” followed by any number of characters.
It will retrieve records in Oracle or PostgreSQL that begin with “j,” but
not “J.” The outcome in the MS SQL Server, SQLite, and MySQL data-
bases is as follows:
SELECT *
FROM Employee
WHERE FirstName LIKE ‘%a%’;
Records with a FirstName value of three letters and ‘e’ in the second posi-
tion will be returned by the query below. Any one character is indicated
by the ‘_’.
SELECT *
FROM Employee
WHERE FirstName LIKE ‘_e_’;
110 ◾ Mastering SQL
SELECT *
FROM Employee
WHERE FirstName LIKE ‘B [i,m,t,y,s]’;
SELECT *
FROM Employee
WHERE FirstName LIKE ‘B [^i,m,t,y,s]’;
LIKE NOT
Filter records that do not match the provided string by combining the
NOT operator with the LIKE operator.
SELECT *
FROM Employee
WHERE FirstName NOT LIKE ‘j%’;
FirstName NOT LIKE ‘j%’ in the above sentence retrieves entries where
the FirstName values do not begin with ‘j’.
come before SOME in order for it to match at least one entry in the sub-
query. Consider that when SOME is used, greater than (>) signifies greater
than at least one value.
Syntax:
Parameters:
Name Description
Col_name Name of the column of the table.
Express1 Expressions can be parts of a SQL query that do computations or value
comparisons against other values and are composed of a single constant,
variable, scalar function, or column name.
Table name The table’s name.
Where Until the SOME operator finds a match, compares a scalar expression.
expression2 For the SOME operator to return a Boolean TRUE value, one or more
rows must match the expression.
Comparison Compares the subquery and the expression. A standard comparison
operator operator (=, >,!=, >, >=,, or =) must be used in the comparison.
Instructor Table:
select name
from instructor
where Salary > some(select Salary
from instructor
where dept=’Computer Science’);
Output:
Visweswaran
Samantha
Debarka
Explanation:
The teachers whose salaries exceed one or more instructors’ salaries in
the “Computer Science” department are asked to leave. The “Computer
Science” department pays 1.3, 2, and 2 in wages. This implies that any
instructor earning more than 1.3 can be counted in the outcome.
Syntax:
The syntax used to demonstrate how to utilise OFFSET and FETCH clause
is as follows:
We have specified the table name from which the data will be obtained in
this syntax. For records shown in ascending or descending order, we then
specified the ORDER BY clause. The amount of records was then skipped
using the OFFSET specification, and the set of records was then returned
using FETCH.
Let’s look at how the OFFSET and FETCH clauses are used practically.
Let’s say we have “my table” with the information below:
a b
1 100
2 99
3 98
4 97
5 96
6 95
7 94
Result:
a b
4 97
5 96
114 ◾ Mastering SQL
Offset Only
Query: SELECT * from “my table” order by a offset 3
rows;
Results:
a b
4 97
5 96
6 95
7 94
Fetch Only
Query:
SELECT * from “my table” order by a fetch next 2 rows
only;
Results:
a b
1 100
2 99
• The tables used to execute the SELECT operations should have the
same number of columns and order.
Clauses/Operators ◾ 115
• The related SELECT queries should use data types that are compat-
ible or the same for the corresponding columns in both tables.
Students Table:
TA Table:
Syntax:
SELECT Name
FROM Students
EXCEPT
SELECT NAME
FROM TA;
Output:
Rohan
Mansi
Megha
We must specifically use EXCEPTALL rather than EXCEPT in order to
keep duplication.
116 ◾ Mastering SQL
SELECT Name
FROM Students
EXCEPTALL
SELECT Name
FROM TA;
Output:
Rohan
Mansi
Mansi
Megha
• Display the name, sal, and job of the emp, as well as the maximum,
minimum, average, and total sal of all the employees doing the
same job.
• Display the department name and the number of employees in it.
UTILISING JOINS
• Make a subtable that contains the values that have been aggregated.
• Use Join to display the results from the subtable with their raw values.
OVER CLAUSE
• Partition by and over clause are used to break down data into
partitions.
• For each partition, the specified function is active.
SELECT DISTINCT(DNAME),
COUNT(ENAME) OVER (PARTITION BY EMP.DEPTNO) EMP
FROM EMP
RIGHT OUTER JOIN DEPT
ON EMP.DEPTNO=DEPT.DEPTNO
ORDER BY EMP DESC;
Dname Emp
SALES 6
RESEARCH 5
ACCOUNTING 3
OPERATIONS 0
OTHERS 0
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Clauses/Operators ◾ 119
A comparison operator like >, >=, =, >, or = must come before the SQL ALL
operator, and a subquery must come after it. A list of literal values may be
used in place of a subquery in some database systems, such as Oracle. Keep
in mind that the WHERE clause’s condition is always true if the subquery
returns no rows. The following table demonstrates the significance of the
SQL ALL operator, assuming that the subquery produces one or more rows:
Demonstration Database
EXISTS IN SQL
One of the key SQL operators, exists, enables you to specify a subquery to
check whether a specific object exists in the database. It executes the query
using the syntax listed below.
Syntax:
If the subquery returns any rows, the operator returns TRUE; otherwise, it
returns FALSE. The SELECT, UPDATE, INSERT, or DELETE commands
can all be used with the exists operator. The following is an explanation of
the syntax’s parameters.
Parameter Description
Col_name Name of the column
Express 1 This could be any expression composed of a single variable, constant, or
even the name of a column.
t_name The title of the column on which we are working
Where exists It looks for the presence of one or more rows in the subquery. If there is a
row, the Boolean value is TRUE; otherwise, it is FALSE
120 ◾ Mastering SQL
Query:
Value returned
It gives back a True or False Boolean value.
Example:
The Employee table in the code snippet below includes the following col-
umns: Employee id, first name, last name, salary, and department.
PRIMARY KEY(Employee_id));
Output:
Employee_id
1
2
3
Syntax:
The following code block illustrates the fundamental grammar of a
GROUP BY clause. If there is an ORDER BY clause, it must come after the
GROUP BY clause and come before the constraints in the WHERE clause.
Example:
Consider the following records in the CUSTOMERS table:
Result:
Name Salary
Muffin 10,000.00
Kamal 4,500.00
Hardin 8,500.00
Chantal 6,500.00
Ramesh 2,000.00
Khilan 1,500.00
kaushik 2,000.00
Let’s take a look at a table where the CUSTOMERS table has the records
with the following names twice:
UNION CLAUSE
As its name suggests, this operator/clause is used to join the results of two
or more SELECT queries. We can also use this command to access a spe-
cific record from a certain column of the table. The number of columns
in each SELECT statement and the order in which they are used in the
UNION statement must match. In addition, the data type of each column
must be the same in all SELECT statements. The UNION clause returns
only distinct values. For good measure you need to copy the values, then
you need to use the UNION ALL clause.
Syntax:
Duplicate rows in the result table are removed using the UNION clause.
To keep copies, check UNION ALL. Quite a few SELECT statements can
be merged using the UNION statement, both UNION and UNION ALL
can be used to join different tables. If you want to consolidate from differ-
ent SELECT statements are one of a kind, on the off chance that unique-
ness is not a concern, then use UNION ALL for better performance.
124 ◾ Mastering SQL
After the last SELECT statement, add an ORDER BY clause to the result-
ing table to sort the data. A union names the columns it returns as results
based on the initial SELECT statement. Connections are often parsed
from left to right by default. You can use parentheses to define an evalua-
tion sequence. The UNION clause allows you to combine any number of
SELECT statements.
The query generates the New Employee table, which has four fields:
CREATE TABLE New_Employee
(
Emp_Id INT NOT NULL,
Emp_Name Varchar (40),
Clauses/Operators ◾ 125
Emp_Age INT,
Emp_Salary INT
);
The query generates the new Employee table, which has four fields:
The following INSERT query adds a new employee record into the Old
Employee table:
Table: New_Emp
Using the UNION operator, the following query displays all data from
both tables in a single table:
Output:
UNION
SELECT Col_Name1, Col_Name_2 ...., Col_Name_N FROM
T_Name_2 [WHERE condition];
Output:
The query below generates the New Students table, which has four fields:
The INSERT query below adds a record of passed students to the Passed
Students table:
Output:
SQL IN ALIASES
Aliases are temporary names assigned to tables or columns for the sake
of a certain SQL query. It is used when the name of a column or table is
changed from its original name, but the change is just temporary.
Syntax:
As a Column Alias:
Let’s go over how to alias a column. Enter the SQL statement below:
There will be two records chosen. You should see the following outcomes:
Dept_ID Total
50 2
51 2
We’ve aliased the COUNT (*) field as total in this example. As a result,
when the result set is returned, total will appear as the heading for the
second column. Because our alias name does not contain any spaces, we
do not need to wrap it in quotes.
Change our query such that the column alias has a space:
There will be two records chosen. You should see the following outcomes:
As a Table Alias:
Category_ID Category_Name
25 Deli
50 Produce
75 Bakery
100 General Merchandise
125 Technology
Clauses/Operators ◾ 133
Let us now combine these two tables and alias the table names. Enter the
SQL statement as follows:
There will be five records chosen. You should see the following outcomes:
Product_Name Category_Name
Banana Produce
Orange Produce
Apple Produce
Bread Bakery
Sliced Ham Deli
We’ve built an alias for the goods table and an alias for the categories table
in this example. We may now refer to the products table as p and the cat-
egories table as c within this SQL expression.
It is not essential to generate aliases for all of the tables provided in the
FROM clause when establishing table aliases. You have the option of creat-
ing aliases on any or all of the tables.
SELECT col-list
FROM t_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
The ORDER BY clause might include more than one column. Make sure
the column you’re sorting by is in the column list.
134 ◾ Mastering SQL
Example:
Consider the CUSTOMERS table, which contains the following records:
An example is provided in the following code block, which sorts the results
in ascending order by NAME and SALARY.
An example is provided in the following code block, which sorts the result
in descending order by NAME.
Syntax:
SELECT TOP number column name FROM table name WHERE con-
dition; the syntax above retrieves data from all columns depending on
the WHERE clause and is limited by the number provided as part of the
SELECT TOP.
Consider the following Customer Table to learn how to use the SELECT
TOP command to copy all of the columns’ data depending on a
criterion.
Scenario: Retrieve the first row of data from the Customer table where the
gender is male.
Output:
Syntax:
The syntax above retrieves data from all columns based on the WHERE
clause and is limited by the percent provided as part of the SELECT TOP.
Consider the following Customer Table to learn how to use the SELECT
INTO command to copy all of the columns’ data depending on a criterion.
Scenario: Get data from the Customer table for 50% of the entries where
the gender is male.
Query:
Syntax:
Scenario:
Retrieve the first row of data from the Customer table where the gender is
male.
Query:
Output:
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN =
valueN
WHERE [condition];
where the keywords are UPDATE, SET, and WHERE table name is the
name of the table that has to be updated, col1, col2,... are the columns val1,
val2,... considered to be updated? assign new values, and the condition sec-
tion, which is followed by a semicolon, contains the condition.
Example:
Consider the CUSTOMERS table, which contains the following records:
The query below will change the ADDRESS for a customer whose ID num-
ber in the table is 6.
If you wish to change all of the ADDRESS and SALARY column values
in the CUSTOMERS table, you may use the UPDATE query instead, as
illustrated in the following code block.
Syntax:
Example:
Take a look at the ‘Customer’ table.
The number of records we can delete will depend on the criteria we give
in the WHERE clause. If we leave out the WHERE clause, all of the records
are destroyed and the table is empty.
Table: Customer
• Single record deletion: Remove all rows where NAME = ‘Ram.’ This
will only erase the first row.
Query:
Result: The above query deletes only the first row, and the table
Customer now looks like this:
Clauses/Operators ◾ 141
Query:
Results: The query above will eliminate two rows (first and third),
and the table Customer will now look like this:
• Delete Every Single Record: There are two queries that can be used
to accomplish this, as illustrated below.
Query 1: “DELETE FROM Student”;
Query 2: “DELETE * FROM Student”;
Output: The table’s records will all be deleted; no records will be
displayed. Customer’s table will soon be empty.
• Simply Values: The first technique is to specify only the data value to
be added without specifying the column names.
142 ◾ Mastering SQL
Syntax:
Syntax:
Table Customer:
Output: This query will only insert the last row from table Lateral
customer into table customer. Customer’s table will now look like this:
AND Operator
This operator returns only records where both condition1 and condition2
evaluate to True.
Syntax:
OR Operator
This operator returns records where either of the conditions condition1
or condition2 is True. That is, either condition 1 or condition 2 is true.
Syntax:
Assume we wish to retrieve all records from the Student table where the
Salary is ≤3,000 and the ADDRESS is Delhi. The question will then be as
follows:
Query:
Output:
As another model, assume you need to get every one of the records from
the Student table where the NAME is Kamal and the Salary is 2,000.
Query:
Output:
Query:
Output:
Syntax:
Consider retrieving all data from the Student table where the Age is 18 and
the NAME is Ram or RAMESH.
Query:
Output:
CLAUSE WHERE
The SQL WHERE statement is utilised to determine a condition while
recovering information from a solitary table or interfacing numerous tables.
Only if the provided condition is met does it return a specific value from the
table. You should utilise the WHERE clause to filter the records and retrieve
only those that are required. The WHERE clause is utilised not just in the
SELECT statement, but also in the UPDATE and DELETE statements.
148 ◾ Mastering SQL
Syntax:
The following is the basic syntax of the SELECT statement with the
WHERE clause:
Example:
Consider the CUSTOMERS table, which contains the following records:
The code beneath is an illustration of how to recover the ID, Name, and
Salary information from the CUSTOMERS table where the compensation
is bigger than 5000.
Query:
Output:
ID Name Salary
4 Kula 6,500.00
5 Hendrik 8,500.00
6 Kiwi 4,500.00
Clauses/Operators ◾ 149
An example query would retrieve the ID, Name, and Salary fields from the
CUSTOMERS table for a client named kiwi.
It is vital to notice that all strings should be enclosed in single quotes
(‘’). Numeric values, on the other hand, should be presented without any
quotation marks, as seen in the preceding example.
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE NAME = ‘Kiwi’;
The output will be as follows:
ID Name Salary
6 Kiwi 4,500.00
Syntax:
This query will return all of the distinct combinations of rows in the
table with the fields column1, column2.
If the distinct keyword is used with multiple columns, the distinct com-
bination will be shown in the result set.
Example:
Consider the CUSTOMERS table, which contains the following records:
Queries:
Name
Ravi
Kaushik
Kevin
Kula
Hendrik
Kiwi
SELECT DISTINCT *
FROM Student;
Clauses/Operators ◾ 151
Output:
Without the term distinct, six entries would have been fetched instead of
four, because the original table contains six records with duplicate values.
The following INSERT query inserts an employee entry into the Employee
Details table:
The data from the Employee Details table is shown in the following
SELECT query:
The following query returns the list of employees from the preceding table
whose Emp Panelty is 500:
The following INSERT query adds a car entry to the Cars Details table:
The values in the output are displayed by the following SELECT query:
The following query displays the total salary of employees with more than
5,000 in the Employee Having table:
Output:
The following INSERT query installs an employee record into the Employee
Having table:
156 ◾ Mastering SQL
The following SELECT query displays the table values in the output:
The following query sorts the salaries of employees from the above
Employee Order table in descending order:
Output:
TRUNCATE TABLE is the SQL command, and table name is the name of
the existing table that you want to empty.
Example:
Consider the following records in a CUSTOMERS table:
The CUSTOMERS table has now been shortened, and the output of the
SELECT operation is as seen in the code block below.
158 ◾ Mastering SQL
Let’s look at the syntax for removing the table from the database.
We would first verify the STUDENTS table before deleting it from the
database.
This indicates that the STUDENTS table is present in the database, there-
fore we may drop it as follows:
CREATE IN SQL
In SQL, there are two CREATE statements:
• CREATE TABLE
• CREATE DATABASE
Make a Database
A database is a systematic collection of data. To store data in a well-struc-
tured manner, the first step with SQL is to establish a database. In SQL, the
CREATE DATABASE statement is used to create a new database.
Syntax:
Example Query: This query will establish a new SQL database and call it
my database.
Table Creation
We learned about database creation before. To save the data, we will need
a table. In SQL, the Construct TABLE statement is used to create a table.
We all know that a table is made up of rows and columns. So, while con-
structing tables, we must give SQL with information such as the names of
the columns, the type of data to be stored in the columns, the quantity of
the data, and so on. Let us now go through how to utilise the Construct
TABLE statement to create tables in SQL.
Syntax:
This query will generate the table Students. The ROLL NO field is of type int
and can hold a three-digit integer value. The following two columns, NAME
and SUBJECT, are of the type varchar and may store characters, with the size
20 indicating that these two fields can hold a maximum of 20 characters.
Clauses/Operators ◾ 161
JOINS IN SQL
A JOIN clause is used to join rows from two or more tables based on a
common column.
In this article, we will go over the last two JOINS:
Syntax:
Syntax:
Syntax:
Output (Third and Fifth Columns show values concatenated by operator ||)
id salary
Syntax:
OPERATOR MINUS
In SQL, the Minus Operator is used with two SELECT statements. The
MINUS operator is used to deduct the first SELECT query’s result set from
the second SELECT query’s result set. In other words, the MINUS opera-
tor will return only those rows that are unique in only the first SELECT
query and not those that are common to both the first and second SELECT
searches.
Basic Syntax:
Important Point:
DIVISION OPERATOR
In SQL, the division operator is an arithmetic operator. Addition (+), sub-
traction (–), multiplication (*), division (/), and modulus are the arithme-
tic operators (%).
In SQL, the division operator has the following syntax:
Query:
SELECT 4 / 2
You may run this query, and it will return the result, which in this example
is 2. However, you are more likely to be working with numbers stored in
columns in your database tables.
Syntax:
The NOT condition in SQL has the following syntax:
NOT condition
SELECT *
FROM products
WHERE product_name NOT IN (‘Pear’, ‘Banana’, ‘Bread’);
There will be four records chosen. You should see the following outcomes:
This example returns all entries from the products table where the product
name does not match Pear, Banana, or Bread. It is sometimes more eco-
nomical to mention the values that you do not want rather than the ones
that you do want. It corresponds to the following SQL statement:
SELECT *
FROM products
WHERE product_name <> ‘Pear’
AND product_name <> ‘Banana’
AND product_name <> ‘Bread’;
Output:
Between Operator
The SQL Between operator is used to determine whether an expression falls
inside a certain value range. This operator is inclusive, meaning it includes
the range’s start and end values. The values can be textual, numeric, or date
based. This operator is compatible with the SELECT, INSERT, UPDATE,
and DELETE commands. Let’s look at the syntax of this operator to gain a
better understanding of it.
SELECT column_names
FROM table_name
WHERE column_name BETWEEN range_start AND range_end;
In Operator
You can define several values in a WHERE clause by using the IN opera-
tor. The numerous OR conditions are abbreviated as the IN operator.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
Because the data is dispersed over different tables, we use various joins to
combine the tables into a single table to extract the data. SQL join com-
mands allow us to merge the rows, columns, and sections of many tables
and see them as a single entity. We may quickly integrate and present data
into a single table by using joins.
This makes it simple for us to run queries and transactions on the data
we require. Joins are performed based on one or more common fields in
two or more tables. They are commonly utilised when a user attempts to
extract data from tables that have one-to-many or many-to-many relation-
ships. Now that we have understood what joins are, let’s look at the many
forms of joins.
• Right join
• Inner join
• Full join
• Left join
Employee Table:
Project Table:
Client Table:
Inner Joining
This type of join delivers records that have values in both tables that match.
As a result, if you run an INNER join operation between the Employee and
Projects databases, all tuples with matching values in both tables will be
returned as output.
Clauses/Operators ◾ 169
Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.
Column1,....
FROM Table1
INNER JOIN Table2
ON Table1.MatchingColumnName = Table2.
MatchingColumnName;
Example:
Output:
Full Joining
The Full Join, also known as the Full Outer Join, retrieves all entries that
have a match in either the left (Table1) or right (Table2) table.
Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.
Column1,....
FROM Table1
FULL JOIN Table2
ON Table1.MatchingColumnName = Table2.
MatchingColumnName;
170 ◾ Mastering SQL
Example:
Output:
Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.
Column1,....
FROM Table1
LEFT JOIN Table2
ON Table1.MatchingColumnName = Table2.
MatchingColumnName;
Example:
Output:
Right Joining
The RIGHT JOIN or RIGHT OUTER JOIN returns all records from
the right table as well as those that satisfy a condition in the left table.
Furthermore, for records with no matching values in the left table, the
output or result-set will contain NULL values.
Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.
Column1,....
FROM Table1
RIGHT JOIN Table2
ON Table1.MatchingColumnName = Table2.MatchingColumnName;
Example:
SELECT Emp.EmpFname, Emp.EmpLname, Proj.P_ID,
Proj.P_Name
FROM Emp
RIGHT JOIN
ON Emp.EmpID = Proj.EmpID;
Output:
The check constraint in the preceding SQL query limits the GENDER to
only the categories supplied. The associated database update is cancelled
if a new tuple is introduced or an existing tuple in the relation is altered
with a GENDER that does not belong to any of the three categories stated.
Query:
From the table mentioned above, the condition is where Students must be
over the age of >=17 to enrol in a university.
Student database schema at a university permitted to enrol in a
university.
University student database schema is as follows:
PRIMARY KEY(ID),
check(Age >= 17)
);
Student Relation:
SUMMARY
SQL clauses and operators were created to assist programmers who are
newbies with Structured Query Language in learning and applying the
language in their daily job. This chapter gives a brief demonstrates about
use of various SQL clauses, SQL commands, SQL statements, and SQL
operators. This chapter gives an overview about the SQL clauses and
commands like SELECT, INSERT, UPDATE, DELETE, WHERE, JOIN,
DISTINCT, ORDER BY, GROUP BY, HAVING, and UNION. The basic
objective of this chapter is to provide a very brief introduction you to this
powerful language and its clauses and lay the groundwork for you to con-
tinue your SQL learning.
Chapter 3
SQL Injections
IN THIS CHAPTER
➣➣ What is SQLi
➣➣ Goals, types, and its mechanism
➣➣ Detection and prevention of SQL injection attacks
➣➣ Sqlmap and its features
➣➣ Prepared statements
The previous chapter taught us about the various SQL statements, clauses,
and related commands. In this chapter, we will be learning about a fre-
quent attack vector that involves backend database modification with
malicious SQL code to gain access to information that was not intended
to be displayed called as SQL injection (SQLi). So, we are moving on with
the brief introduction about SQLi and then go on to its mode of operation
with examples.
database records. Any website or web application that uses an SQL data-
base such as MySQL, Oracle, SQL Server or others can be vulnerable to
SQL Injection. It could be used by criminals to illegally access your sensi-
tive data such as customer information, personal data, secrets, intellectual
property and more. One of the oldest, most common and deadliest online
application vulnerabilities is SQL Injection.
SQL injection can have a high impact on a company bottom line. A suc-
cessful attack can result in an attacker reading lists of illegal users, deleting
entire tables, and in some situations gaining administrator rights to the
database, all of which are extremely damaging to a company. Consider
the client’s loss of trust in your SQLi cost estimate if personal information
such as phone numbers, addresses, and credit card information is com-
promised. Although any SQL database can be attacked using the vector,
websites are the most popular targets. As evidenced by their ranking in
OWASP’s top 10 online application security risks list, one of the most wide-
spread types of security attacks is SQL injection.1 With the availability of
automated SQL injection tools, the risk of exploiting SQLi has expanded,
as has the damage it can cause. In the past, attackers had to perform these
attacks manually, as the chances of targeting a company using SQL injec-
tion were very limited.
GOALS OF SQLi
Following are the goals attained by SQLi:
username = request.POST[‘u_name’]
password = request.POST[‘p_word’]
database.execute(SQL)
Password’ OR 2=2
No matter what the username or password is, the WHERE clause always
returns the first id from the users table because of the OR 2=2 state-
ment. The administrator is frequently the first user id in a database.
The attacker not only gets administrator rights but also bypasses authenti-
cation. To have additional control over how the query is executed, they can
also comment out the remaining SQL statement:
-- MySQL
‘ OR ‘2’=’2’ #
-- Access (using null characters)
‘ OR ‘2’=’2’ %00
‘ OR ‘2’=’2’ %16
SQLMAP
Sqlmap is a free and open source penetration testing tool for detecting and
leveraging SQL injection vulnerabilities and gaining control of database
systems. It comes with a powerful detection engine, a slew of specialised
features for the ultimate penetration tester, and a slew of switches for data-
base fingerprinting, data extraction from databases, access to the under-
lying file system, and out-of-band command execution on the operating
system.
Features of Sqlmap
The detailed description of all the features can be learned from wiki2
(Figure 3.1).
184 ◾ Mastering SQL
How to Download
You can get the most recent zip ball or tarball here. The best way to get
sqlmap is to clone the Git repository:
Pass -h to sqlmap to display the command’s help menu and verify that
it is installed.
$ sqlmap –h
If you don’t want to install DVWA, you can use this publicly accessible
vulnerable website instead:
http://checkphp.vulnerableweb.com/artists22.php?artist=4*.
Let us get started now that everything is set up.
$ sqlmap -u “http://localhost/vulnerabilities/
sqli/?id=1&Submit=Submit” --cookie “PHPSESSID=u8e7b7vb
kkienkafe68a6pabzf; security=low” –dbs
First, we use the -u parameter to specify our target URL, which in my case
is localhost/, but you should specify where your DVWA is installed,
186 ◾ Mastering SQL
for example, if it’s on another machine in the same network and in the
DVWA folder.
192.168.1.3/DVWA/vulnerabilities/sqli/?id=1&Submit=Submit.
We also pass the —cookie argument, because DVWA requires login to
begin performing SQL injection, so simply passing our cookie will log us
in. You can find your cookie by going to Developer Console > Network,
looking for any request, scrolling down to the Request Headers section,
and looking for Cookie.
We use –DBS to retrieve a list of the website’s available databases; the
following is the result:
$ sqlmap -u “http://localhost/vulnerabilities/
sqli/?id=1&Submit=Submit” --cookie “PHPSESSID=u8e7b7vb
kkienkafe68a6pabzf; security=low” -D dvwadb –tables
Output:
Database: dvwadb
[2 tables]
SQL Injections ◾ 187
Guestbook
Customers
Great, we have two tables in this database; we will dump the Customers
table in the next part.
$ sqlmap -u “http://localhost/vulnerabilities/
sqli/?id=1&Submit=Submit” --cookie “PHPSESSID=u8e7b7vb
kkienkafe68a6pabzf; security=low” -D dvwadb -T
customers –columns
Here’s what happens when we use the -T argument to define the table
name:
Output:
Database: dvwadb
Table: Customer
Column Type
password varchar(32)
user varchar(15)
avatar varchar(70)
failed_login int(3)
first_name varchar(15)
last_login timestamp
last_name varchar(15)
user_id int(6)
$ sqlmap -u “http://localhost/vulnerabilities/
sqli/?id=1&Submit=Submit” --cookie “PHPSESSID=u8e7b7vb
kkienkafe68a6pabzf; security=low” -D dvwadb -T
Customer –dump
188 ◾ Mastering SQL
We just substituted - dump for - columns; this will prompt you with vari-
ous questions, including whether you want to save the hashes to a tempo-
rary file or crack the passwords using a dictionary-based attack; I selected
Y (yes) for both, and the result.4
Prepared Statements
A prepared statement is a parameterised, reusable SQL query that requires
the developer to create the SQL command and user-supplied data separately.
SQL Injection risks are avoided since the SQL command is executed safely.
In PHP, here’s an example of an unsafe approach:
From the above code it is clearly evident that the data that the user has
provided is directly inserted into the SQL query mentioned. If the user
pungin or inputs admin and ‘a’ or ‘2’=’2, the user will be able to access the
login credentials of the admin account without even having knowledge of
user login pin or password because the SQL statement declared above has
been tampered/modified.
Here is an example of a prepared statement approach in PHP:
But given that they are distinct from a regular query, how does a prepared
statement go through this process?
Although the process is the same, there are a few differences:
Semantics Checking is equivalent to parsing. After the database engine
detects the placeholders, binding builds the query with placeholders. Later,
190 ◾ Mastering SQL
the user’s data will be added. The step called ‘Cache’ doesn’t change. The
query is cached so it can be used again.
There is still a phase after caching and before execution: placeholder
replacement. The user’s information is now entered in place of the place-
holders. The final query won’t go through the compilation process again
because the query has already been pre-compiled (Binding). Because of
this, the user-provided data will always be treated as a basic string and
is unable to alter the logic of the original query. The query will therefore
be resistant to SQL Injection flaws for that data. That is a method of tak-
ing advantage of a SQL statement’s inherent weakness by injecting mali-
cious SQL statements into its entry field for final execution, as described
in the chapter about SQLi above. Since 1998, when it initially surfaced,
it has mostly targeted stores and bank accounts. It can produce signifi-
cant effects when combined with other types of attacks like DDOS attacks,
cross-site scripting (XSS), or DNS hijacking.
Terminology
When a user inputs his or her UserID and password in normal circum-
stances, the following statement is generated for execution:
userID = 2’ or ‘2’ = ‘2
password = 2’ or ‘2’ = ‘2
Because the criteria (OR 2 = 2) is always true, the query will return a value.
Without knowing the user’s username or password, the system has suc-
cessfully authenticated the user.
192 ◾ Mastering SQL
If an attacker tries to set a value for the userID column that isn’t a basic
integer, statement.setInt() will throw a SQLException instead of
allowing the query to finish.
if (!hashOf(request.getParameter(“password”)).
equals(rs.getString(“password_Hash”)))
{
SQL Injections ◾ 193
throw BadLoginException();
}
rs = statement.executeQuery(userGroupQuery);
while (rs.next())
{
userGroup.put(rs.getString(“group”), true);
}
}
catch (SQLException e){}
catch (BadLoginException e){}
The following could be injected into the userName field by the attacker.
Anam’;
INSERT INTO groupMmbership (userID, group)
VALUES (SELECT userID FROM users
WHERE userName=’Anam’, ‘Administrator’); --
try
{
PreparedStatement statement =
connection.prepareStatement(userLoginQuery);
statement.setString(1, request.getParameter(“user”));
ResultSet rs = statement.executeQuery();
}
Consider what would happen if the attacker typed the following into the
userName field:
When this query is run, it entirely deletes the users table. Again, a
prepared statement can be used as a workaround.
SUMMARY
In this chapter, we learned about SQL Injection, a type of attack that
makes use of weak SQL statements. Using SQL injection, it is possible to
access, insert, update, and delete data as well as circumvent authentication
processes. Use sound security practices while writing SQL statements to
reduce the risk of SQL injection. We also talked about the SQL injection
tools, including Sqlmap, and we got a quick explanation of prepared state-
ments and input sanitization.
NOTES
1 https://owasp.org/www-project-top-ten/Wasp to ten, Wasp.
2 Feature-Miroslav Stampar, Github.com.
3 How To Setup DVWA Using XAMPP (Windows Tutorial)-Effecthacking.
com
4 How to Scan SQL Injection Vulnerable Sites using Sqlmap-Rimsha Ashraf,
Root Install.
Chapter 4
SQL Functions
IN THIS CHAPTER
➣➣ What are Functions in SQL
➣➣ Different types of function
➣➣ Syntax and Examples
In the previous chapter, we learned about SQLi, how to prevent SQLi attack,
and sqlmap and its functions, and we also discussed a brief introduction
about prepared statements and their function in SQL. A function is a for-
mula that accepts one or more arguments as input, processes them, and
then returns output. It is a programming construct that returns a single
value and accepts parameters. Function parameters can change the result
or return the result. The beauty of a function is that it can be embedded in
an expression because it is self-contained. An expression in Oracle SQL is
a statement of SQL code or even another function by definition.
SQL FUNCTIONS
SQL functions are a very powerful feature that can be used to perform cal-
culations on data, change individual data items, change output for groups
of rows, format data and numbers for display, and convert column data
types. An SQL function always outputs a value and can accept input.
SQL functions are regularly used routines that help with database
processing, modification, and maintenance. SQL functions are simple
subroutines that are often used and reused in SQL database systems to
process and manipulate data. In order to create and manage databases, all
SQL database systems include DDL (Data Definition Language) and DML
(Data Manipulation Language) tools.
There are five general categories of functions in SQL. Object reference
functions that provide access to unique object pointers, aggregation func-
tions that group rows into groups, analytic functions that also group but
allow in-depth data analysis, and user-defined functions that you can
create using a programming language such as PL/SQL, are other types of
functions.
Aggregate Functions
It returns a single value after performing a calculation on a set of
values. They can be used in a SELECT statement’s select list or the
SQL Functions ◾ 199
Function Description
SUM() This returns the sum of a group of values.
COUNT() It returns the number of rows either based on a
condition, or without a condition.
AVG() Returns the average value of a column (numeric).
MIN() Returns the minimum value of a column.
MAX() Returns a maximum value of a column.
FIRST() Return the first value of the column.
LAST() Returns the last value of the column.
Analytic Functions
Analytic functions calculate a total value from a set of rows. Analytic
functions, unlike aggregate functions, can return numerous rows for each
group. Within a group, analytic functions can be used to generate moving
averages, running totals, percentages, or top-N outcomes.
Function Description
LCASE() convert string column values to lowercase
UCASE() It converts a string column values to uppercase.
LEN() It returns the length of the text values in the column.
MID() It extracts substrings from column values having string data type.
ROUND() It rounds off a numeric value to the nearest integer.
NOW() It returns the current system date and time.
FORMAT() Format how a field must be displayed.
200 ◾ Mastering SQL
CONVERSION FUNCTION
The Oracle built-in function library includes type conversion functions
in addition to SQL utility functions. In some cases, the query may expect
input of a certain data type but receives it in a different data type. In some
circumstances, Oracle tries implicitly to transform the unexpected value
to a compatible data type that can be substituted in place without com-
promising application continuity. Oracle can convert types intuitively or
explicitly, depending on the programmer’s preference (Figure 4.1).
From To
VARCHAR2 or CHAR NUMBER
VARCHAR2 or CHAR DATE
DATE VARCHAR2
NUMBER VARCHAR
Example: Take a look at the SELECT queries below. Because Oracle inter-
nally interprets 2000 and ‘2000’ as the same, both queries will return the
same answer.
Query 1:
Query 2:
Output:
Syntax:
Example:
To show a number value as a character, you can use the TO CHAR func-
tion with the following format elements:
Example:
Output:
Salary
$9,000
SQL Functions ◾ 205
Syntax:
TO_NUMBER(char[, ’format_model’])
TO_DATE(char[, ’format_model’])
Example:
Output:
The conversion function lets us to alter date formats for display, convert
column datatypes, perform calculations on data, modify individual data
items, and manipulate output for groups of rows
NVL()
It is a SQL function that converts a null value to a valid value. Date, let-
ter, and integer are examples of data types that can be employed. The data
types must be compatible, i.e., expr1 and expr2 must be of the same data
type.
Syntax:
NVL2 Function
The NVL2 capability assesses the underlying articulation (expr1, expr2,
expr3). The NVL2 capability returns the subsequent articulation on the
off chance that the principal articulation isn’t invalid. In the event that
the primary articulation is invalid, the third articulation is returned, for
example, NVL2 returns expr2, assuming expr1 isn’t invalid. NVL2 returns
expr3 on the off chance that expr1 is invalid. Any information type can be
utilised in the expr1 contention.
SQL Functions ◾ 207
Syntax:
expr1 is the source value or expression, which may or may not contain a
null value.
If expr1 is not null, the value returned is expr2.
If expr1 is null, the value returned is expr3.
DECODE()
It performs the duties of an IF-THEN-ELSE or CASE statement, simplify-
ing conditional searches. With the help of IF-THEN-ELSE logic, which
is ubiquitous in computer languages, the DECODE function decodes an
expression. The DECODE function decodes the expression after compar-
ing each search value to it. If the expression matches the search, the result
is returned.
When a search value does not match any of the result values and the
default value is omitted, a null value is returned.
Syntax:
COALESCE()
It really takes a look at the main articulation, and in the event that the
principal articulation isn’t invalid, it returns that articulation; otherwise,
it does a COALESCE of the excess articulations.
The benefit of the COALESCE() capability over the NVL() capability is
that the COALESCE capability can take different substitute qualities. In
basic words, COALESCE() capability returns the main non-invalid articu-
lation in the rundown.
NULLIF()
The NULLIF capability looks at two articulations. Assuming that they are
equivalent, the capability brings invalid back. In the event that they are
not equivalent, the capability returns the principal articulation. You can’t
indicate the strict NULL for first articulation.
LVL()
LVL assesses a condition when one of the two operands of the condition
might be invalid. The capability can be utilised exclusively in the WHERE
provision of a question. It takes as a contention a condition and returns
TRUE in the event that the condition is FALSE or UNKNOWN and FALSE
assuming the condition is TRUE.
LVL( condition(s) )
• CASE
• IF
The CASE explanation goes through conditions and returns a worth when
the primary condition is met (like an on the off chance that else procla-
mation). In this way, when a condition is valid, it will quit perusing and
return the outcome. Expecting no conditions are substantial, it returns the
value in the ELSE statement. If there is no ELSE condition and no circum-
stances are authentic, it brings NULL back
SQL Functions ◾ 209
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN condition THEN resultN
ELSE result
END;
IF Proclamation in SQL
In the event that assertions can be utilised to restrictively go into some
rationale in view of the situation with a condition being fulfilled. The IF
proclamation is consistently identical to CASE explanations with a looked
case-proclamation when proviso. The IF proclamation upholds the utilisa-
tion of discretionary ELSE IF provisos and a default ELSE condition. An
END IF condition is expected to show the finish of the assertion.
Here is an illustration of procedure that contains an IF statement:
CHARACTER FUNCTIONS
Character capabilities acknowledge character inputs and can return either
characters or number qualities as a result. SQL gives various different
person datatypes which incorporates – CHAR, VARCHAR,VARCHAR2,
LONG, RAW, and LONG RAW. The different data types are arranged into
three distinct data types:
At the point when a person’s capability returns a person’s esteem that worth
is dependably of type VARCHAR2 (variable length), with the accompany-
ing two exemptions: UPPER and LOWER. These capabilities convert to
upper and to bring down case, individually, and return the CHAR values
(fixed length), assuming that the strings they are approached to change
over are fixed-length CHAR contentions.
SQL gives a rich arrangement of character works that permit you to
get data about strings and change the items in those strings in more than
one way.
• Character capabilities are of the accompanying two sorts:
• Case-Manipulative Functions (LOWER, UPPER and INITCAP)
• Character-Manipulative Functions (REPLACE, CONCAT,
LENGTH, SUBSTR, INSTR, LPAD, RPAD, and TRIM)
Case-Manipulative Functions
LOWER(SQL course)
Input1: SELECT LOWER(‘TechFORTech’) FROM DUAL;
Output1: TechFORTech
Input2: SELECT LOWER(‘DATABASE@456’) FROM DUAL;
Output2: database@456
INITCAP(SQL course)
Input1: SELECT INITCAP(‘Tech point is a software
engineering gateway for nerds’) FROM DUAL;
SQL Functions ◾ 213
Character-Manipulative Functions
CONCAT(‘String1’, ‘String2’)
Input1: SELECT CONCAT (‘Data’ ,’Learning’) FROM DUAL;
Output1: DataLearning
Input2: SELECT CONCAT( NULL ,’Operating System’) FROM
DUAL;
Output2: Operating System
Input3: SELECT CONCAT( NULL ,NULL ) FROM DUAL;
Output3: -
Syntax:
LENGTH (Column|Expression)
Input1: SELECT LENGTH (‘Dancing Is Love ‘) FROM DUAL;
Output1: 20
Input2: SELECT LENGTH (‘ Write an Experience ‘) FROM
DUAL;
Output2: 24
214 ◾ Mastering SQL
Syntax:
SUBSTR(‘String’,start-index,length_of_extracted_
string)
Input1: SELECT SUBSTR (‘Data management, 15) FROM
DUAL;
Output1: Data
Input2: SELECT SUBSTR (‘Data Manage System’, 9, 7)
FROM DUAL;
Output2: Manage
Syntax:
Syntax:
LPAD(Column|Expression, n, ‘String’)
Syntax: RPAD(Column|Expression, n, ‘String’)
LPAD Input1: SELECT LPAD (‘105’,5,’*’) FROM DUAL;
LPAD Output1: **105
LPAD Input2: SELECT LPAD(‘hey’, 29, ‘Tech’) FROM DUAL;
LPAD Output2: TechTechTechTechhey
RPAD Input1: SELECT RPAD(‘8000’,7,’*’) FROM DUAL;
RPAD Output1: 8000***
RPAD Input1: SELECT RPAD(‘Lern’, 25, ‘time’) FROM DUAL;
RPAD Output1: Lerntimetimetimetime
• Trim: This capability manages the string input all along or end (or
both). Assuming that no string or burn is indicated to be managed
from the string and there exists some additional room at start or end
of the string, then those additional areas are managed off
Syntax:
Syntax:
Listing Function
The listing capability changes values from a gathering of columns into a
rundown of values that are delimited by a configurable separator. Listing
is regularly used to denormalise columns into a line of comma-isolated
values (CSV) or other similar configurations reasonable for human perus-
ing. Listing doesn’t make a difference any getting away: it isn’t by and large
conceivable to tell whether an event of the separator in the outcome is a
real separator, or simply an aspect of a worth. The protected utilisation
of listing for electronic information connection points is hence restricted
to cases in which an unambiguous separator can be chosen, for example,
while amassing numbers, dates, or strings that are known to not contain
the separator.
Syntax:
Listing is an arranged set capability, which requires the inside bunch
statement to indicate a request. The insignificant language structure is as
follows:
LISTING(, ON OVERFLOW … )
The default is on flood blunder. For this situation, the standard requires an
exemption with SQLSTATE 22001 to be brought – up practically speak-
ing, this necessity isn’t satisfied. The on flood shorten statement forestalls
the flood by just linking; however, many qualities as the outcome type can
oblige. Moreover, the on flood shorten condition permits one to determine
how the outcome is ended:
The discretionary defaults to three periods (...) and will be added as the
last component in the event that truncation occurs. If with count is deter-
mined and truncation occurs, the quantity of overlooked values is placed
in sections and annexed to the outcome. The SQL standard doesn’t need
an admonition to be given on truncation. To know regardless of whether
the outcome is finished, clients can parse the result or look at the genuine
length of the outcome to the determined length for an outcome containing
all qualities.
Distinct
The listing capability acknowledges the discretionary set quantifiers all
and particular:
LISTAGG( [ALL|DISTINCT] , … ) …
purposes min (o) to keep the main event on the off chance that one worth
seems on various occasions.
SELECT g
, LISTAGG(val, ‘,’) WITHIN GROUP (ORDER BY o) list
FROM (SELECT g, min(o) o, Val
FROM dist_listagg
GROUP BY g, Val
) dt
GROUP BY g
The effect of the filter clause is to remove rows before aggregation. Case
can be used for the same effect. The over clause must not contain an order
by clause10 because the mandatory within group clause must contain an
order by clause anyway. It is not possible to narrow the window frame: the
set of aggregated rows is always the full partition.
COMPATIBILITY
Listing was introduced with SQL: 2016 as optional feature T625. Even
though listing is not yet widely supported, most databases offer similar
functionality using a proprietary syntax.
ARRAYS
In the event that the question doesn’t rigorously need the arrival of a delim-
ited string, exhibits can be utilised to return a variety of values. A cluster
can be developed utilising the array_agg total capability or by means of a
subquery.
ARRAY_AGG( ORDER BY … )
ARRAY()
The subsequent structure can contain particular and bring first to elim-
inate copies and breaking point the exhibit length. Neither one nor the
other methodologies play out a verifiable cast: The exhibit components
SQL Functions ◾ 219
have a similar kind as. That implies that the recovering application can get
the qualities in a sort of safe way and apply designing whenever required.
The sort safe nature of exhibits permits them to likewise convey invalid
qualities in an unambiguous manner. Array_agg does subsequently not
eliminate invalid qualities like other total capabilities do (counting list-
ing). The channel provision can be utilised to eliminate invalid qualities
before conglomeration with array_agg. On the off chance that the chan-
nel condition eliminates all columns, array_agg returns invalid – not an
unfilled exhibit. The subquery sentence structure permits eliminating
invalid qualities in the where proviso of the and returns a vacant exhibit
if the subquery returns no lines. On the off chance that the request for
components is superfluous, multisets and gather can likewise be utilised
to pass a sort of safe rundown to an application.
DOCUMENT TYPES
Like array_agg, the SQL standard characterises total capabilities that
return JSON or XML pieces: for example, json_arrayagg and xmlagg. The
principal benefit contrasted with listing is that they apply the separate get-
away rules.
, and ‘,’as
DUE TO RECURSIVE
list_agg(g, val, list)
AS (
SELECT g, min(val), CAST(null AS VARCHAR(255))
FROM listagg_demo
220 ◾ Mastering SQL
GROUP BY g
UNION ALL
SELECT prev.g,
(SELECT min(val)
FROM listagg_demo this
WHERE this.g = prev.g
AND this.Val > prev.val) Val
, COALESCE(list || ‘, ‘, ‘’) || val
FROM list_agg prev
WHERE prev.Val IS NOT NULL
)
SELECT g, list
FROM list_agg
WHERE val IS NULL
ORDER BY g
This specific execution utilises the ‘free record filter’ procedure and the
presentation will stay at a fairly low level even with a file on (g, val). The
particular way of behaving is a symptom of this technique. The right treat-
ment of invalid in Val is a significant exceptional case: albeit invalid is
by and large disregarded in totals, a gathering that comprises of invalid
qualities just should in any case be available in the outcome. This implies
that invalid should not be taken out in the event that there is no not invalid
worth in the gathering. The execution above utilises min(Val) in the
non-recursive articulation to get this social more conventional execution
that upholds all semantics and erratic request by conditions is conceiv-
able utilising with recursive and window capabilities. Aaron Bertrand’s
post ‘Assembled Concatenation in SQL Server’ presents an illustration
of this methodology.1 In the two cases, erratic on flood conduct can be
executed.
Proprietary Extensions
The main helpful expansion that is generally accessible is the help of tie
boundaries and consistent articulations in. The standard neither per-
mits precluding the nor discarding the inside bunch provision. However,
a few information bases treat them as discretionary and apply execution
SQL Functions ◾ 221
Proprietary Alternatives
There are two broadly accessible restrictive options to listagg: group_con-
cat and string_agg. Despite the fact that a few data sets utilise a similar
exclusive capability name, they actually utilise an alternate sentence struc-
ture. Fortunately, the exclusive capabilities have a similar default semantic
as listing: they channel invalid qualities before collection yet don’t elimi-
nate copies.
• Count()
• Sum()
• Avg()
• Min()
• Max()
222 ◾ Mastering SQL
DATE FUNCTIONS
One of the most crucial SQL functions is the date, but it can be challeng-
ing for beginners to understand because there are numerous forms in
which dates can be stored in databases and numerous formats in which
users want to access dates depending on the particular needs. When
storing both the date and time values at once in a single column in SQL,
Date Time (time is also used together with the date) is usually utilised.
Date time is sometimes used in place of dates because dates and times are
related.
SQL Functions ◾ 223
Let’s understand each date function used in SQL one by one in detail:
Name Birthdate
Output:
Patrick 1998-09-16
Name Birthday
Output:
Patrick 16
(Continued)
224 ◾ Mastering SQL
Date is a substantial date and configuration indicates the result design for
the date/time. The configurations that can be utilised are:
Some of the fundamental date functions used in SQL are those that were
just mentioned. Other date functions are utilised in various contexts.
Before utilising any of them, one must be aware of the syntax and argu-
ments supplied into the function to prevent unexpected outcomes.
Is Null Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Syntax:
The basic syntax of NULL while creating a table:
NOT NULL in this case denotes that the column must always accept an
explicit value of the specified data type. We did not apply NOT NULL in
two columns; hence, these columns are open to NULL values. When a field
contains a NULL value, it means that the record creation process left the
field empty.
However, when comparing an unknown number to any other value, the
result is always unknown and not included in the final results, which is
why the NULL value might be problematic when picking data. To check
for a NULL value, you must use the IS NULL or IS NOT NULL operators.
Take a look at the CUSTOMERS table, which contains the following
records:
Output:
Output:
NUMERIC FUNCTIONS
The numerical functions accept a numeric expression as input and output
numeric results. The majority of mathematical functions have NUMBER
as their return type. The following table lists the included numerical
functions:
Function Description
ABS( numeric_exp ) Returns the outright worth of numeric_exp.
ACOS( float_exp ) Returns the arccosine of float_exp as a point, communicated
in radians.
ASIN( float_exp ) Returns the arcsine of float_exp as a point, communicated in
radians.
ATAN( float_exp ) Returns the arctangent of float_exp as a point, communicated
in radians.
ATAN2( float_ Returns the arctangent of the x and, not set in stone by
exp1, float_exp2) float_exp1 and float_exp2, independently, as a point,
imparted in radians.
(Continued)
230 ◾ Mastering SQL
Function Description
CEILING( numeric_ Returns the littlest number more noteworthy than or
exp ) equivalent to numeric_exp. The return esteem is of similar
information type as the info boundary.
COS( float_exp ) gives the cosine of float exp, where float exp is the radian-
based coordinate of the point.
COT( float_exp ) Returns the cotangent of float_exp, where float_exp is a point
communicated in radians.
DEGREES( numeric_ Returns the quantity of degrees changed over from numeric_
exp ) exp radians.
EXP( float_exp ) Returns the exponential value of float_exp.
FLOOR( numeric_exp ) Returns the biggest number not exactly or equivalent to
numeric_exp. The return esteem is of similar information
type as the information parameter.
LOG( float_exp ) returns the float exp’s natural logarithm.
LOG10( float_exp ) gives back the base The float exp 10 logarithm.
MOD( integer_ Returns the amount left over (modulus) after dividing integer
exp1, integer_exp2) exp1 by integer exp2.
PI( ) gives a floating-point value that is equal to the constant value
of pi.
POWER( numeric_ returns the result of scaling numeric exp by integer exp.
exp, integer_exp)
RADIANS( numeric_ gives the number of radians created when numeric exp
exp ) degrees were converted.
RAND([integer_exp]) Returns a random floating-point number using the specified
seed value of integer exp.
ROUND( numeric_ returns the numeric exp rounded to integer exp places to the
exp, integer_exp) right of the decimal. Numeric exp is rounded to |integer exp|
places to the left of the decimal point if integer exp is
negative.
SIGN( numeric_exp ) gives back a numeric exp sign signal. –1 is returned if numeric
exp is less than zero. 0 is returned if numeric exp is equal to
zero. One is returned if numeric exp is larger than 0.
SIN( float_exp ) Returns the sine of float_exp, where float_exp is an angle
expressed in radians.
SQRT( float_exp ) Returns the square root of float_exp.
TAN( float_exp ) Returns the tangent of float_exp, where float_exp is an angle
expressed in radians.
TRUNCATE( numeric_ Returns numeric_exp shortened to integer_exp puts right of
exp, integer_exp) the decimal point. Assuming integer_exp is negative,
numeric_exp is shortened to |integer_exp| spots to one side of
the decimal point.
SQL Functions ◾ 231
STRING FUNCTIONS
A string function always accepts a string value as an input, no matter what
data type is returned. There are numerous built-in string functions in SQL
Server that developers can use. The SQL Server string functions listed
below examine an input string and output a string or a number:
Function Description
ASCII Return the value of the character in terms of ASCII code value
CHAR Convert the value of the character as an ASCII value
CHARINDEX Look for a substring inside a string beginning from a predefined
area and return the place of the substring
CONCAT join at least two strings into one string
CONCAT_WS Connect various strings with a separator into a solitary string
DIFFERENCE Analyse the SOUNDEX() upsides of two strings
FORMAT Return a worth designed with the predefined design and
discretionary culture
LEFT Separate a given various characters from a character string
beginning from the left
LEN Return various characters of a character string
LOWER Lowercase a string by changing it
LEITRIM Remove all leading blanks from the provided string to produce a
new string.
NEAR Return the Unicode character that corresponds to the requested
integer code in accordance with the Unicode standard.
PATINDEX The starting location of a pattern’s first appearance in a string is
returned.
(Continued)
232 ◾ Mastering SQL
Function Description
QUOTE NAME provides a response that is a Unicode string with the delimiters
appended to make the input string a legitimate delimited identifier.
REPLACE Anywhere a substring appears in a string, replace it with a different
substring.
REPLICATE Get a string that has been repeated a certain amount of times.
REVERSE Return a character string’s reverse order.
RIGHT Extract a specified number of characters, starting on the right, from
a character string.
RTRIM Remove any trailing blanks from the provided string to create a new
string.
SOUNDEX If a string is spoken, return a four-character (SOUNDEX) code for it.
SPACE Returns a string of repeated spaces.
STR Returns character data converted from numeric data.
STRING_AGG Concatenate rows of strings with a specified separator into a new
string
STRING_ESCAPE Escapes special characters in a string and returns a new string with
escaped characters
STRING_SPLIT A table-valued function that splits a string into rows of substrings
based on a specified separator.
STUFF Delete a part of a string and then insert another substring into the
string starting at a specified position.
SUBSTRING Extract a substring within a string starting from a specified location
with a specified length
TRANSLATE Replace several single-characters, one-to-one translation in one
operation.
TRIM To make a new string, take off the leading and trailing blanks from
the given string.
UNICODE returns a character’s integer value according to the Unicode standard.
UPPER Make a string all uppercase.
Except for FORMAT, all built-in string functions are deterministic. This
indicates that they always produce the same result when called with a
particular set of input values.
The input type is implicitly changed to a text data type when inputs to
string functions are not strings.
SQL Functions ◾ 233
Function Comments
All aggregate These are deterministic unless they are specified with the OVER and
ORDER BY clauses.
CAST Deterministic unless used with sql_variant, small date time, or
DateTime.
CONVERT Deterministic unless any of the following circumstances apply:
SQL variant is the source type.
The source type is nondeterministic, and the target type is SQL variant.
Datetime or smalldatetime is the source or target type, a character string
is the other source or target type, and a nondeterministic style is given.
The style parameter must be a constant for the system to be
deterministic. Except for styles 20 and 21, all styles with a value of less
than or equal to 100 are nondeterministic.
With the exception of styles 106, 107, 109, and 113, all styles larger than
100 are deterministic.
With the exception of CHECKSUM(*), CHECKSUM is deterministic.
Only when used in conjunction with the CONVERT function, ISDATE is
deterministic for however long style isn’t equivalent to 0, 100, 9, or 109
and the CONVERT style boundary is provided.
Only when a seed parameter is supplied, RAND is deterministic.
SUMMARY
In the chapter, we learned about the functions, which are pre-written pro-
grammes that may take variables and return a value, and Oracle offers
various built-in functions. Function can be used alone or can be used in
combination with several other functions like string, math, date, transla-
tion etc. There may be several uses for a function depending on the kind of
information that is given to carry out code.
NOTE
1 Grouped Concatenation in SQL Server- Aaron Bertrand, SQL Performance.
com
Bibliography
Adrienne Watt & Nelson Eng - SQL Structured query language - https://open-
textbc.ca/dbdesign01/chapter/sql-structured-query-language/. Accessed on
(2022 June 11).
Adrienne Watt & Nelson Eng - SQL Structured query language - https://open-
textbc.ca/dbdesign01/chapter/sql-structured-query-language/. Accessed on
(2022 June 16).
Ahmad Yaseen - Constraints in SQL Server: SQL NOT NULL, UNIQUE and
SQL primary key - https://www.sqlshack.com/commonly-used-sql-server-
constraints-not-null-unique-primary-key/. Accessed on (2022 June 17).
Ajay Sarangam - Important types of indexes in SQL server - https://u-next.com/
blogs/data-science/types-of-indexes-in-sql-server/. Accessed on (2022
June 14).
Andrew Pomponio - MySQL overview: Key features, benefits, and use cases -
https://www.openlogic.com/blog/mysql-overview. Accessed on (2022
June 16).
Chad Brooks - When to use SQL - https://www.businessnewsdaily.com/5804-
what-is-sql.html. Accessed on (2022 June 10).
Data Flow - https://learn.microsoft.com/en-us/sql/integration-services/data-flow/
data-flow?view=sql-server-ver16. Accessed on (2022 June 17).
How SQL works? - https://www.tutorialspoint.com/sql/sql-overview.htm.
Accessed on (2022 June 12).
Index in SQL - https://www.simplilearn.com/tutorials/sql-tutorial/index-in-sql.
Accessed on (2022 June 14).
Installing MySQL on Microsoft Windows - https://dev.mysql.com/doc/ref-
man/8.0/en/windows-installation.html. Accessed on (2022 June 16).
Introduction to SQL - https://www.w3schools.com/sql/sql_intro.asp. Accessed on
(2022 June 10).
Kashyap Vyas - Major Advantages of Using MySQL - https://www.datamation.com/
storage/8-major-advantages-of-using-mysql/. Accessed on (2022 June 15).
Kate Brush - RDBMS (relational database management system). -https://www.
techtarget.com/searchdatamanagement/definition/RDBMS-relational-
database-management-system. Accessed on (2022 June 10).
Katie Terrell Hanna| Sarah Lewis - SQL injection - https://www.techtarget.
com/searchsoftwarequality/definition/SQL-injection. Accessed on (2022
June 15).
235
236 ◾ Bibliography
239
240 ◾ Index
Improved
A streamlined A single point search and
experience for of discovery discovery of
our library for all of our content at both
customers eBook content book and
chapter level