0% found this document useful (0 votes)
0 views

SQL NOTES

This document provides an overview of SQL (Structured Query Language) and its components, including its history, usage, and various commands for managing relational databases. It covers key concepts such as RDBMS, data types, SQL commands (DDL, DML, DCL), and operators, as well as practical examples for creating and managing databases and tables. Additionally, it discusses constraints that ensure data integrity within SQL tables.

Uploaded by

cute girl
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

SQL NOTES

This document provides an overview of SQL (Structured Query Language) and its components, including its history, usage, and various commands for managing relational databases. It covers key concepts such as RDBMS, data types, SQL commands (DDL, DML, DCL), and operators, as well as practical examples for creating and managing databases and tables. Additionally, it discusses constraints that ensure data integrity within SQL tables.

Uploaded by

cute girl
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

SQL - NOTES

SQL – Structured Query


Language
1 Introduction
1.1 PhpMyAdmin
PhpMyAdmin is an open-source software tool introduced on September 9, 1998, which is
written in PHP. Basically, it is a third-party tool to manage the tables and data inside the
database. PhpMyAdmin supports various type of operations on MariaDB and MySQL. The
main purpose of phpMyAdmin is to handle the administration of MySQL over the web .

2 What is SQL?
SQL was developed by IBM Computer Scientists in the 1970s. SQL is Structured Query
Language, which is a computer language for storing, manipulating, and retrieving data
stored in a relational database. SQL is the standard language for Relational Database
System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access,
Oracle, Sybase, Informix, PostgreSQL, and SQL Server use SQL as their standard database
language. SQL is widely popular because it offers the following advantages –
 Allows users to access data in the relational database management systems.
 Allows users to describe the data.
 Allows users to define the data in a database and manipulate that data.
 Allows users to create and drop databases and tables.
 Allows users to set permissions on tables, procedures, and views.

1|Page
SQL - NOTES

2.1 SQL - RDBMS Concepts


RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL,
and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access. A Relational database management system (RDBMS) is a database
management system (DBMS) that is based on the relational model as introduced by E. F.
Codd.
What is a Database? Data is the new fuel of this world but only data is unorganized
information, so to organize that data we make a database. A database is the organized
collection of structured data which is usually controlled by a database management system
(DBMS). Databases help us with easily storing, accessing, and manipulating data held on a
computer.
What is a table? The data in an RDBMS is stored in database objects which are called
as tables. This table is basically a collection of related data entries and it consists of
numerous columns and rows. A table is the most common and simplest form of data storage
in a relational database.
What is a field? Every table is broken up into smaller entities called fields. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY. A field is a column in a
table that is designed to maintain specific information about every record in the table.
What is a Record or a Row? A record is also called as a row of data is each individual entry
that exists in a table.
What is a column? A column is a vertical entity in a table that contains all information
associated with a specific field in a table.

2.2 SQL Commands


The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These commands can be classified into the following
groups based on their nature –
1. DDL - Data Definition Language
 CREATE: Creates a new table, a view of a table, or other object in the database.
 ALTER: Modifies an existing database object, such as a table.
 DROP: Deletes an entire table, a view of a table or other objects in the database.
2. DML - Data Manipulation Language
 SELECT: Retrieves certain records from one or more tables.
 INSERT: Creates a record.
 UPDATE: Modifies records
 DELETE: Deletes records.
3. DCL - Data Control Language
 GRANT: Gives a privilege to user.
 REVOKE: Takes back privileges granted from user.

2|Page
SQL - NOTES

4. Data Query Language


Data retrieval instructions are written in the data query language (DQL), which is used to
access relational databases. The SELECT command is used by software programs to filter
and return particular results from a SQL table.
5. Transaction Control Language
To automatically update databases, the relational engine uses transaction control
language (TCL). For instance, the database can reverse a mistaken transaction using the
ROLLBACK command.

2.3 SQL Data Types


The data type of a column can be defined as basically what type of data format in which
each cell will store the data – it can be any type of integer, character, money, date and time,
binary, etc. An SQL developer must aware of what type of data will be stored inside each
column while creating a table. The data type guideline for SQL is to understand what type of
data is expected inside each column and it also identifies how SQL will interact with the
stored data. For every database, data types are primarily classified into three categories.
 Numeric Datatypes
 Date and Time Datatypes
 String Datatypes
NOTE: Different databases may have different variations of these data types, or they may
have additional data types not listed here. Understanding SQL data types are important for
creating tables and working with data in a database, as it affects how data is stored and
processed.
A. Exact Numeric Datatype: There are nine subtypes which are given below in the table.
The table contains the range of data in a particular type.

3|Page
SQL - NOTES

B. Approximate Numeric Datatype: The subtypes of this datatype are given in the table
with the range.

C. Character String Datatype : The subtypes are given in below table

D. Unicode Character String Datatype: The details are given in below table

4|Page
SQL - NOTES

SQL data types define the type of data that can be stored in a database column or variable.
Here are the most common SQL data types:

2.4 What is an Operator in SQL?


An operator is a reserved word, or a character used primarily in an SQL statement's WHERE
clause to perform operation(s), such as comparisons and arithmetic operations. These
Operators are used to specify conditions in an SQL statement and to serve as conjunctions
for multiple conditions in a statement.
1. SQL Arithmetic Operators: Assume 'variable a' holds 10 and 'variable b' holds 20, then

Operator Description Example

5|Page
SQL - NOTES

Adds values on either side of the operator. a + b will give


+ (Addition)
30

Subtracts right hand operand from left hand a - b will give -


- (Subtraction) operand. 10

* Multiplies values on either side of the operator. a * b will give


(Multiplication) 200

Divides left hand operand by right hand operand. b / a will give


/ (Division)
2

Divides left hand operand by right hand operand b % a will give


% (Modulus) and returns remainder. 0

2. SQL Comparison Operators: Assume 'variable a' holds 10 and 'variable b' holds 20, then

Operato Description Example


r

Checks if the values of two operands are equal or not, if (a = b) is


=
yes then condition becomes true. not true.

Checks if the values of two operands are equal or not, if (a! = b) is


!=
values are not equal then condition becomes true. true.

Checks if the values of two operands are equal or not, if (a <> b) is


<>
values are not equal then condition becomes true. true.

Checks if the value of left operand is greater than the


(a > b) is
> value of right operand, if yes then condition becomes
not true.
true.

Checks if the value of left operand is less than the value of (a < b) is
<
right operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or equal (a >= b) is
to the value of right operand, if yes then condition

6|Page
SQL - NOTES

becomes true. not true.

Checks if the value of left operand is less than or equal to


(a <= b) is
<= the value of right operand, if yes then condition becomes
true.
true.

Checks if the value of left operand is not less than the


(a !< b) is
!< value of right operand, if yes then condition becomes
false.
true.

Checks if the value of left operand is not greater than the


(a !> b) is
!> value of right operand, if yes then condition becomes
true.
true.

3. SQL Logical Operators

Sr.N Operator & Description


o

ALL : The ALL operator is used to compare a value to all values in another value
1
set.

AND : The AND operator allows the existence of multiple conditions in an SQL
2
statement's WHERE clause.

ANY : The ANY operator is used to compare a value to any applicable value in
3
the list as per the condition.

BETWEEN : The BETWEEN operator is used to search for values that are within a
4
set of values, given the minimum value and the maximum value.

EXISTS : The EXISTS operator is used to search for the presence of a row in a
5
specified table that meets a certain criterion.

IN : The IN operator is used to compare a value to a list of literal values that


6
have been specified.

LIKE : The LIKE operator is used to compare a value to similar values using
7
wildcard operators.

8 NOT : The NOT operator reverses the meaning of the logical operator with
which it is used. E.g.: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate

7|Page
SQL - NOTES

operator.

OR : The OR operator is used to combine multiple conditions in an SQL


9
statement's WHERE clause.

10 IS NULL : The NULL operator is used to compare a value with a NULL value.

3 SQL - DATABASE
3.1 CREATE DATABASE
The SQL CREATE DATABASE statement is used to create a new SQL database. Always the
database name should be unique within the RDBMS.
Syntax: CREATE DATABASE DatabaseName;
Example: CREATE DATABASE demo;

3.2 DROP or DELETE Database


The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.
Syntax: DROP DATABASE DatabaseName;
Example: DROP DATABASE demo;

3.3 SELECT Database, USE Statement


When you have multiple databases in your SQL Schema, then before starting your
operation, you would need to select a database where all the operations would be
performed. The SQL USE statement is used to select any existing database in the SQL
schema.
Syntax: The basic syntax of the USE statement is as shown: USE DatabaseName;
Example: SHOW DATABASES;

4 SQL - Table
4.1 CREATE TABLE
Creating a basic table involves naming the table and defining its columns and each column's
data type. The SQL CREATE TABLE statement is used to create a new table. CREATE TABLE is
the keyword telling the database system what you want to do. In this case, you want to
create a new table. The unique name or identifier for the table follows the CREATE TABLE
statement. Then in brackets comes the list defining each column in the table and what sort
of data type it is.

8|Page
SQL - NOTES

Syntax: The basic syntax of the CREATE TABLE statement is as follows: CREATE TABLE
table_name (column1 datatype, column2 datatype, column3 datatype, ..., columnN
datatype, PRIMARY KEY (one or more columns));
Example: CREATE TABLE customers (customer_id int, customer_name varchar (50), city
varchar (50), grade int, salesman_id int, credit int);

4.2 Creating a Table from an Existing Table


A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement. The new table has the same column definitions. All
columns or specific columns can be selected. When you will create a new table using the
existing table, the new table would be populated using the existing values in the old table.
Syntax: Here, column1, column2... are the fields of the existing table and the same would be
used to create fields of the new table. The basic syntax for creating a table from another
table is as follows: CREATE TABLE NEW_TABLE_NAME AS SELECT [ column1,
column2...columnN] FROM EXISTING_TABLE_NAME [WHERE]
Example: CREATE TABLE CUSTOMERS_TEMP AS SELECT ID, SALARY FROM CUSTOMERS;

4.3 Drop or Delete Table


The SQL DROP TABLE statement is used to remove a table definition and all the data,
indexes, triggers, constraints, and permission specifications for that table. You should be
very careful while using this command because once a table is deleted then all the
information available in that table will also be lost forever.
Syntax: DROP TABLE table_name;
Example: DROP TABLE CUSTOMERS;

5 SQL - Constraints
Constraints are the rules enforced on the data columns of a table. These are used to limit
the type of data that can go into a table. This ensures the accuracy and reliability of the data
in the database. Constraints could be either on a column level or a table level. The column
level constraints are applied only to one column, whereas the table level constraints are
applied to the whole table. Following is some of the most commonly used constraints
available in SQL.

5.1 NOT NULL Constraint


Ensures that a column cannot have NULL value. By default, a column can hold NULL values.
If you do not want a column to have a NULL value, then you need to define such a constraint
on this column specifying that NULL is now not allowed for that column. A NULL is not the
same as no data, rather, it represents unknown data.
Examples:

9|Page
SQL - NOTES

 The following SQL query creates a new table called CUSTOMERS and adds 6 columns,
out of which are customer_id, customer_name in this we specify not to accept NULLs:
CREATE TABLE CUSTOMERS (customer_id INT NOT NULL, customer_name VARCHAR (20)
NOT NULL, city VARCHAR (25), grade int, salesman_id int, credit int, PRIMARY KEY
(customer_id));
 If CUSTOMERS table has already been created, then to add a NOT NULL constraint to the
credit column in MySQL, you would write a query like the one that is shown in the
following: ALTER TABLE CUSTOMERS MODIFY credit int NOT NULL;

5.2 DEFAULT Constraint


The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
Example:
 For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, the SALARY column is set to 5000.00 by default, so in case the INSERT
INTO statement does not provide a value for this column, then by default this column
would be set to 5000.00 - CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME
VARCHAR (50) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR (25), SALARY DECIMAL
(18,2) DEFAULT 5000.00, PRIMARY KEY (ID));
 If the CUSTOMERS table has already been created, then to add a DEFAULT constraint to
the SALARY column, you would write a query like the one which is shown in the code
block below - ALTER TABLE CUSTOMERS MODIFY SALARY DECIMAL (18,2) DEFAULT
5000.00;
Drop Default Constraint: ALTER TABLE CUSTOMERS ALTER COLUMN SALARY DROP
DEFAULT;

5.3 UNIQUE Constraint


The UNIQUE Constraint prevents two records from having identical values in a column. In
the CUSTOMERS table, for example, you might want to prevent two or more people from
having an identical age.
Example:
 For example, the following SQL query creates a new table called CUSTOMERS and adds
five columns. Here, the AGE column is set to UNIQUE, so that you cannot have two
records with the same age: CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME
VARCHAR (20) NOT NULL, AGE INT NOT NULL UNIQUE, ADDRESS CHAR (25), SALARY
DECIMAL (18,2), PRIMARY KEY (ID));
 If the CUSTOMERS table has already been created, then to add a UNIQUE constraint to
the AGE column. You would write a statement like the query that is given in the code
block below: ALTER TABLE CUSTOMER MODIFY AGE INT NOT NULL UNIQUE;

10 | P a g e
SQL - NOTES

 You can also use the following syntax, which supports naming the constraint in multiple
columns as well: ALTER TABLE CUSTOMERS ADD CONSTRAINT myUniqueConstraint
UNIQUE (AGE, SALARY);
 If you are using MySQL, then you can use the following syntax: ALTER TABLE
CUSTOMERS DROP INDEX myUniqueConstraint;

5.4 PRIMARY Key Constraint


A primary key is a field in a table which uniquely identifies each row/record in a database
table. Primary keys must contain unique values. A primary key column cannot have NULL
values. A table can have only one primary key, which may consist of single or multiple fields.
When multiple fields are used as a primary key, they are called a composite key. If a table
has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
Example:
 Here is the syntax to define the ID attribute as a primary key in a CUSTOMERS table:
CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT
NOT NULL, ADDRESS VARCHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID));
 To create a PRIMARY KEY constraint on the "ID" column when the CUSTOMERS table
already exists, use the following SQL syntax: ALTER TABLE CUSTOMER ADD PRIMARY KEY
(ID);
Delete Primary Key: You can clear the primary key constraints from the table with the
syntax given below: ALTER TABLE CUSTOMERS DROP PRIMARY KEY;

5.5 FOREIGN Key Constraint


A foreign key is a key used to link two tables together. This is sometimes also called as a
referencing key. A Foreign Key is a column or a combination of columns whose values match
a Primary Key in a different table. The relationship between 2 tables matches the Primary
Key in one of the tables with a Foreign Key in the second table. If a table has a primary key
defined on any field(s), then you cannot have two records having the same value of that
field(s).
Example: Consider the structure of the following two tables.
CUSTOMERS table: CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR (20)
NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR (25), SALARY DECIMAL (18,2), PRIMARY
KEY (ID));
ORDERS table: CREATE TABLE ORDERS (ID INT NOT NULL, DATE DATETIME, CUSTOMER_ID
INT references CUSTOMERS(ID), AMOUNT double, PRIMARY KEY (ID));
If the ORDERS table has already been created and the foreign key has not yet been set, the
use the syntax for specifying a foreign key by altering a table: ALTER TABLE ORDERS: ADD
FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);

11 | P a g e
SQL - NOTES

DROP a FOREIGN KEY Constraint: To drop a FOREIGN KEY constraint, use the following SQL
syntax: ALTER TABLE ORDERS DROP FOREIGN KEY;

5.6 CHECK Key Constraint


The CHECK constraint ensures that all the values in a column satisfies certain conditions. The
CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and is not entered the table.
Example:
 For example, the following program creates a new table called CUSTOMERS and adds
five columns. Here, we add a CHECK with AGE column, so that you cannot have any
CUSTOMER who is below 18 years: CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME
VARCHAR (20) NOT NULL, AGE INT NOT NULL CHECK (AGE >=18), ADDRESS CHAR (25),
SALARY DECIMAL (18,2), PRIMARY KEY (ID));
 If the CUSTOMERS table has already been created, then to add a CHECK constraint to
AGE column, you would write a statement like the one given below: ALTER TABLE
CUSTOMERS MODIFY AGE INT NOT NULL CHECK (AGE >=18);
 You can also use the following syntax, which supports naming the constraint in multiple
columns as well: ALTER TABLE CUSTOMERS ADD CONSTRAINT myCheckConstraint CHECK
(AGE >=18);
To drop a CHECK constraint, use the following SQL syntax. This syntax does not work with
MySQL: ALTER TABLE CUSTOMERS DROP CONSTRAINT myCheckConstraint;

6 SQL - Insert Query


The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax: INSERT INTO TABLE_NAME(column1, column2, column3...columnN) VALUES
(value1, value2, value3...valueN);
Here, column1, column2, column3, columnN are the names of the columns in the table into
which you want to insert the data. You may not need to specify the column(s) name in the
SQL query if you are adding values for all the columns of the table. But make sure the order
of the values is in the same order as the columns in the table.
Example: INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (1,
'Ramesh',32,'Ahmedabad', 2000.00);

7 SQL - Select Query


The SQL SELECT statement is used to fetch the data from a database table which returns this
data in the form of a result table. These result tables are called result-sets.

12 | P a g e
SQL - NOTES

Syntax: The basic syntax of the SELECT statement is as follows: SELECT column1, column2,
columnN FROM table_name.
Here, column1, column2... are the fields of a table whose values you want to fetch.
Example: Select id, name, age, address from customers;
Syntax: If you want to fetch all the fields available in the field, then you can use the
following syntax: SELECT * FROM table_name;
Example: Select * from customers;

8 SQL - Distinct Keyword


The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all
the duplicate records and fetching only unique records. There may be a situation when you
have multiple duplicate records in a table. While fetching such records, it makes more sense
to fetch only those unique records instead of fetching duplicate records.
Syntax: SELECT DISTINCT column1, column2, columnN FROM table_name WERE [condition]
[condition]
Example: SELECT DISTINCT SALARY FROM CUSTOMERS;

9 SQL - WHERE Clause


The SQL WHERE clause is used to specify a condition while fetching the data from a single
table or by joining with multiple tables. If the given condition is satisfied, then only it returns
a specific value from the table. You should use the WHERE clause to filter the records and
fetching only the necessary records. The WHERE clause is not only used in the SELECT
statement, but it is also used in the UPDATE, DELETE statement, etc.
Syntax: SELECT column1, column2, columnN FROM table_name WHERE [condition]
Here, it is important to note that all the strings should be given inside single quotes ('').
Whereas numeric values should be given without any quote.
Example: SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE NAME ='Hardik';

10 SQL - Update Query


The SQL UPDATE Query is used to modify the existing records in a table. You can use the
WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows
would be affected.
Syntax: UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example:

13 | P a g e
SQL - NOTES

 UPDATE CUSTOMERS SET ADDRESS ='Pune' WHERE ID =6;


 UPDATE CUSTOMERS SET ADDRESS ='Pune', SALARY =1000.00;

11 SQL - Delete Query


The SQL DELETE Query is used to delete the existing records from a table. You can use the
WHERE clause with a DELETE query to delete the selected rows, otherwise all the records
would be deleted. You can combine N number of conditions using AND or OR operators.
Syntax: DELETE FROM table_name WHERE [condition];
Example: DELETE FROM CUSTOMERS WHERE ID = 6;

12 SQL - AND/OR Conjunctive Operators


The SQL AND & OR operators are used to combine multiple conditions to narrow data in an
SQL statement. These two operators are called as the conjunctive operators. These
operators provide a means to make multiple comparisons with different operators in the
same SQL statement.

12.1 The AND Operator


The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.
Syntax: SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND
[condition2] ...AND [condition];
You can combine N number of conditions using the AND operator. For an action to be taken
by the SQL statement, whether it be a transaction or a query, all conditions separated by the
AND must be TRUE.
Example: SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >2000 AND age
<25;

12.2 The OR Operator


The OR operator is used to combine multiple conditions in an SQL statement's WHERE
clause.
Syntax: SELECT column1, column2, columnN FROM table_name WHERE [condition1] OR
[condition2] ...OR [condition]
You can combine N number of conditions using the OR operator. For an action to be taken
by the SQL statement, whether it be a transaction or query, the only any ONE of the
conditions separated by the OR must be TRUE.
Example: SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >2000 OR age <25;

14 | P a g e
SQL - NOTES

13 SQL - BETWEEN OPERATORS


The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates. The BETWEEN operator is inclusive: begin and end values are included.
Syntax: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1
AND value2;
Example: SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;

14 SQL - IN Operator
The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is
a shorthand for multiple OR conditions.
Syntax: SELECT column_name(s) FROM table_name WHERE column_name IN (value1,
value2,…);
Example:
 The following SQL statement selects all customers that are in "Germany", "France" or
"UK": SELECT * FROM Customers WHERE Country IN (‘Germany', 'France', 'UK');
 The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK": SELECT * FROM Customers WHERE Country NOT IN ('Germany',
'France', 'UK');

15 SQL - LIKE Clause


The SQL LIKE clause is used to compare a value to similar values using wildcard operators.
There are two wildcards used in conjunction with the LIKE operator. The percent sign (%)
and the underscore (_).The percent sign represents zero, one or multiple characters. The
underscore represents a single number or character. These symbols can be used in
combinations.
Syntax: The basic syntax of % and _ is as follows:
 SELECT FROM table_name WHERE column LIKE 'XXXX%'
 SELECT FROM table_name WHERE column LIKE '%XXXX%'
 SELECT FROM table_name WHERE column LIKE 'XXXX_'
 SELECT FROM table_name WHERE column LIKE '_XXXX'
 SELECT FROM table_name WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here, XXXX could be
any numeric or string value.
Example: The following table has a few examples showing the WHERE part having different
LIKE clause with '%' and '_' operators −

15 | P a g e
SQL - NOTES

Sr.No. Statement & Description

1 WHERE SALARY LIKE '200%'. Finds any values that start with 200.

2 WHERE SALARY LIKE '%200%'. Finds any values that have 200 in any position.

WHERE SALARY LIKE '_00%'. Finds any values that have 00 in the second and
3
third positions.

WHERE SALARY LIKE '2_%_%'. Finds any values that start with 2 and are at
4
least 3 characters in length.

5 WHERE SALARY LIKE '%2'. Finds any values that end with 2.

WHERE SALARY LIKE '_2%3'. Finds any values that have a 2 in the second
6
position and end with a 3.

WHERE SALARY LIKE '2___3'. Finds any values in a five-digit number that start
7
with 2 and end with 3.

16 SQL - ORDER BY Clause


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one column. Some databases sort the query results in an ascending order by default.
Syntax: The basic syntax of the ORDER BY clause is as follows - SELECT column-list FROM
table_name [WHERE condition] [ORDER BY column1, column2...columnN] [ASC | DESC];
Example: SELECT * FROM customer ORDER BY customer_id;

17 SQL – GroupBy Clause


The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT
statement and precedes the ORDER BY clause.
Syntax: The basic syntax of a GROUP BY clause is shown in the following code block. The
GROUP BY clause must follow the conditions in the WHERE clause and must precede the
ORDER BY clause if one is used : SELECT column1, column2 FROM table_name WHERE
[conditions] GROUP BY column1, column2 ORDER BY column1, column2
Example: If you want to know the total amount of the salary on each customer, then the
GROUP BY query would be as follows : SELECT NAME,SUM (SALARY) FROM CUSTOMERS
GROUP BY NAME;

16 | P a g e
SQL - NOTES

18 SQL - Functions
18.1 SQL Server Aggregate Functions
An aggregate function performs a calculation one or more values and returns a single value.
The aggregate function is often used with the GROUP BY clause and HAVING clause of
the SELECT statement.
1. AVG() function: AVG () function retrieves the average value of a given expression. If the
function does not find a matching row, it returns NULL.
Syntax: AVG ([DISTINCT] expr)
Where expr is a given expression. The DISTINCT option can be used to return the
average of the distinct values of expr.
Examples:
 AVG() function: SELECT AVG(credit) FROM customer;
 AVG() function with group by: SELECT grade, AVG(customer_id) FROM customer
GROUP BY salesman_id;
 AVG() function with distinct : SELECT AVG(DISTINCT (grade)) FROM purchase;
 AVG() function with COUNT () function: SELECT pub_id, COUNT(customer_id),
AVG(credit) FROM customer GROUP BY salesman_id;
 AVG() function with having : SELECT customer_id, AVG(credit) FROM customer
GROUP BY salesman_id HAVING salesman_id = 5001;
2. COUNT() function: COUNT() function returns a count of a number of non-NULL values of
a given expression.
Examples:
 COUNT() function: SELECT COUNT(credit) FROM customer;
 COUNT() function with Logical Operator: SELECT city, COUNT(*) FROM customer
WHERE city='New York' OR city='London' GROUP BY city;
3. MIN() function: MIN() function returns the minimum value of an expression. MIN()
function returns NULL when the return set has no rows.
Examples:
 MIN() function: SELECT MIN(credit) FROM customer;
 MIN() function with group by: SELECT order_no, MIN(purchase_amt) FROM orders
GROUP BY customer_id;
 MIN() function with group by and order by: SELECT order_no, MIN(purchase_amt)
FROM orders GROUP BY customer_id ORDER BY order_no;
 MIN() function with having: SELECT order_no, MIN(purchase_amt) FROM orders
GROUP BY customer_id HAVING purchase_amt > 2000 ORDER BY order_no;
 MIN() function with distinct: SELECT MIN(DISTINCT purchase_amt) FROM orders
GROUP BY customer_id;
4. MAX() function: MAX () function returns the maximum value of an expression.
Examples:

17 | P a g e
SQL - NOTES

 MAX() function with group by : SELECT order_no, MAX(purchase_amt) FROM orders


GROUP BY customer_id;
 MAX() with group by and order by: SELECT order_no, MAX(purchase_amt) FROM
orders GROUP BY customer_id ORDER BY order_no;
 MAX() function with having: SELECT city, MAX(credit) FROM customer GROUP BY
salesman_id HAVING MAX(credit)>=20000;
5. SUM() function: MySQL SUM () function returns the sum of an expression. SUM ()
function returns NULL when the return set has no rows.

18.2 SQL String Functions


1. CONCAT() Function: The CONCAT() function takes one or more string arguments and
concatenates them into a single string. The CONCAT function requires a minimum of one
parameter otherwise it raises an error.
Syntax: CONCAT (string1, string2, ...);
Example: SELECT concat(Cust_name,' ',city) as “Name and City” FROM customer;
2. LOWER() Function: The LOWER() function accepts a string argument and returns the
lowercase version of that string.
Syntax: LOWER (str) or LCASE (str)
Example: SELECT LOWER (Cust_name), LCASE (City) FROM `customer`;
3. UPPER Function: The UPPER () function returns the uppercase of a specified string
argument.
Syntax: UPPER (str) or UCASE (str)

18.3 Date Functions


1. CURDATE Function: The CURDATE() function returns the current date as a value in
the 'YYYY-MM-DD' format if it is used in a string context or YYYYMMDD format if it is
used in a numeric context. The following example shows how the CURDATE () function is
used in the string context.
Example:
 CURDATE () function is used in the string context: SELECT CURDATE();
 CURDATE() function is used in a numeric context: SELECT CURDATE() + 0;
 The CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE(): SELECT
CURRENT_DATE(), CURRENT_DATE, CURDATE();
CURDATE vs. NOW: The CURDATE () function returns the current date with date part
only while the NOW() function returns both date and time parts of the current time. The
result of the CURDATE() function is equivalent to the following expression: SELECT DATE
(NOW ());
2. DATEDIFF Function: The DATEDIFF() function calculates the number of days between
two DATE, DATETIME, or TIMESTAMP values.
Syntax: DATEDIFF (date_expression_1, date_expression_2);

18 | P a g e
SQL - NOTES

The DATEDIFF function accepts two arguments that can be any valid date or date-time
values. If you pass DATETIME or TIMESTAMP values, the DATEDIFF function only takes
the date parts for calculation and ignores the time parts. The DATEDIFF function is useful
in many cases e.g., you can calculate an interval in days.
Example: SELECT DATEDIFF ('2011-08-17','2011-08-17');
3. DAY Function: The DAY() function returns the day of the month of a given date.
The following shows the syntax of the DAY function: DAY (date);
The DAY () function accepts one argument that is a date value for which you want to get
the day of the month. If the date argument is zero e.g., '0000-00-00', the DAY () function
returns 0. In case the date is NULL, the DAY () function returns NULL. Note that DAY
() function is the synonym of the DAYOFMONTH () function.
Example:
 DAY() function: SELECT DAY('2010-01-15');
 Using DAY() function to get the number of days in a month of a date: SELECT
DAY(LAST_DAY('2016-02-03'));
4. DATE_ADD Function: The DATE_ADD function adds an interval to a DATE or DATE TIME
value.
Syntax: DATE_ADD(start_date, INTERVAL expr unit);
The DATE_ADD function takes two arguments:
 start_date is a starting DATE or DATETIME value
 INTERVAL expr unit is an interval value to be added to the starting date value.

Examples:
 Add 1 second to 1999-12-31 23:59:59: SELECT DATE_ADD('1999-12-31 23:59:59',
INTERVAL 1 SECOND) result;
 Add 1 day to 1999-12-31 00:00:01: SELECT DATE_ADD('1999-12-31 00:00:01',
INTERVAL 1 DAY) result;
 Add 1 minute and 1 second to 1999-12-31 23:59:59: SELECT DATE_ADD ('1999-12-31
23:59:59', INTERVAL '1:1' MINUTE_SECOND) result;
 Add -1 day and 5 hours to 2000-01-01 00:00:00: SELECT DATE_ADD('2000-01-01
00:00:00', INTERVAL '-1 5' DAY_HOUR) result;
 Add 1 second and 999999 microseconds to 1999-12-31 23:59:59.000002: SELECT
DATE_ADD('1999-12-31 23:59:59.000002’, INTERVAL '1.999999' SECOND
_MICROSECOND) result;
5. DATE_FORMAT Function: To format a date value to a specific format, you use
the DATE_FORMAT function.
Syntax: DATE_FORMAT (date, format)
The DATE_FORMAT function accepts two arguments:
 date: is a valid date value that you want to format

19 | P a g e
SQL - NOTES

 Format: is a format string that consists of predefined specifiers. Each specifier is


preceded by a percentage character (%). See the table below for a list of predefined
specifiers.
The DATE_FORMAT function returns a string whose character set and collation depend
on the settings of the client’s connection. The following table illustrates the specifiers
and their meanings that you can use to construct a date format string:

Specifier Meaning
%a Three-characters abbreviated weekday name e.g., Mon, Tue, Wed, etc.
%b Three-characters abbreviated month name e.g., Jan, Feb, Mar, etc.
%c Month in numeric e.g., 1, 2, 3…12
%D Day of the month with English suffix e.g., 0th, 1st, 2nd, etc.
%d Day of the month with leading zero if it is 1 number e.g., 00, 01,02, …31
%e Day of the month without leading zero e.g., 1, 2…31
%f Microseconds in the range of 000000.999999
%H Hour in 24-hour format with leading zero e.g., 00...23
%h Hour in 12-hour format with leading zero e.g., 01, 02…12
%I Same as %h
%i Minutes with leading zero e.g., 00, 01…59
%j Day of year with leading zero e.g., 001,002…366
%k Hour in 24-hour format without leading zero e.g., 0,1,2…23
%l Hour in 12-hour format without leading zero e.g., 1,2…12
%M Full month name e.g., January, February…December
%m Month name with leading zero e.g., 00,01, 02…12
%p AM or PM, depending on other time specifiers
%r Time in 12-hour format hh:mm:ss AM or PM
%S Seconds with leading zero 00,01…59
%s Same as %S
%T Time in 24-hour format hh:mm:ss
%U Week number with leading zero when the first day of week is Sunday e.g.,
00,01,02…53
%u Week number with leading zero when the first day of week is Monday e.g.,
00,01,02…53
%V Same as %U; it is used with %X
%v Same as %u; it is used with %x
%W Full name of weekday e.g., Sunday, Monday…, Saturday
%w Weekday in number (0=Sunday, 1= Monday, etc.)
%X Year for the week in four digits where the first day of the week is Sunday; often

20 | P a g e
SQL - NOTES

Specifier Meaning
used with %V
%x Year for the week, where the first day of the week is Monday, four digits; used
with %v
%Y Four digits year e.g., 2000 and 2001.
%y Two digits year e.g., 10, 11, and 12.
%% Add percentage (%) character to the output

The following are some commonly used dates format strings:

DATE_FORMAT string Formatted date


%Y-%m-%d 2013-07-04
%e/%c/%Y 4/7/2013
%c/%e/%Y 7/4/2013
%d/%m/%Y 4/7/2013
%m/%d/%Y 7/4/2013
%e/%c/%Y %H:%i 4/7/2013 11:20
%c/%e/%Y %H:%i 7/4/2013 11:20
%d/%m/%Y %H:%i 4/7/2013 11:20
%m/%d/%Y %H:%i 7/4/2013 11:20
%e/%c/%Y %T 4/7/2013 11:20
%c/%e/%Y %T 7/4/2013 11:20
%d/%m/%Y %T 4/7/2013 11:20
%m/%d/%Y %T 7/4/2013 11:20
%a %D %b %Y Thu 4th Jul 2013
%a %D %b %Y %H:%i Thu 4th Jul 2013 11:20
%a %D %b %Y %T Thu 4th Jul 2013 11:20:05
%a %b %e %Y Thu Jul 4 2013
%a %b %e %Y %H:%i Thu Jul 4 2013 11:20
%a %b %e %Y %T Thu Jul 4 2013 11:20:05
%W %D %M %Y Thursday 4th July 2013
%W %D %M %Y %H:%i Thursday 4th July 2013 11:20
%W %D %M %Y %T Thursday 4th July 2013 11:20:05
%l:%i %p %b %e, %Y 7/4/2013 11:20
%M %e, %Y 4-Jul-13
%a, %d %b %Y %T Thu, 04 Jul 2013 11:20:05

Examples:

21 | P a g e
SQL - NOTES

 SELECT orderNumber, DATE_FORMAT(orderdate, '%Y-%m-%d') orderDate, DATE


_FORMAT(requireddate, '%a %D %b %Y') requireddate, DATE_FORMAT(shippedDate,
'%W %D %M %Y') shippedDate FROM orders;
 MySQL DATE_FORMAT with ORDER BY : SELECT orderNumber, DATE_FORMAT
(shippeddate, '%W %D %M %Y') shippeddate FROM orders WHERE shippeddate IS NOT
NULL ORDER BY shippeddate;
6. DAYNAME Function: MySQL DAYNAME function returns the name of a weekday for a
specified date.
Syntax of the DAYNAME function: DAYNAME (date);
The DAYNAME function accepts 1 argument which is a date that you want to get the
name of its weekday. If the date is NULL or invalid e.g., 2017-02-30, the DAYNAME
function returns NULL.
Examples:
 SELECT DAYNAME ('2000-01-01') dayname;
 SELECT DAYNAME(orderDate) weekday, COUNT (*) total_orders FROM orders
WHERE YEAR(orderDate) = 2004 GROUP BY weekday ORDER BY total_orders DESC;
7. DAYOFWEEK Function: The DAYOFWEEK function returns the weekday index for
a date i.e., 1 for Sunday, 2 for Monday, and 7 for Saturday.
Syntax DAYOFWEEK function: DAYOFWEEK(date)
The DAYOFWEEK function accepts 1 argument which is a DATE or DATETIME value. It
returns an integer which ranges from 1 to 7 that represents Sunday to Saturday.
The DAYOFWEEK function returns NULL if the date is NULL, zero (0000-00-00), or invalid.
Example: The following example returns weekday index of December 1st, 2010:
SELECT DAYNAME('2012-12-01'), DAYOFWEEK('2012-12-01');
8. EXTRACT Function: The EXTRACT () function extracts part of a date.
Syntax of the EXTRACT () function: EXTRACT (unit FROM date).
The EXTRACT() function requires two arguments unit and date. The unit is the interval
that you want to extract from the date. The following are the valid intervals for the unit
argument: DAY, DAY_HOUR, DAY_MICROSECOND, DAY_MINUTE, DAY_SECOND, HOUR,
HOUR_MICROSECOND, HOUR_MINUTE, HOUR_SECOND,MICROSECOND, MINUTE,
MINUTE_MICROSECOND, MINUTE_SECOND, MONTH, QUARTER, SECOND,
SECOND_MICROSECOND, WEEK, YEAR, YEAR_MONTH.
The date is a DATE or DATETIME value from which you extract an interval.
Examples:
 Extract day from a date time: SELECT EXTRACT(DAY FROM '2017-07-14 09:04:44')
DAY;
 Extract day_hour from a date time: SELECT EXTRACT(DAY_HOUR FROM '2017-07-14
09:04:44') DAYHOUR;
 Extract day_microsecond from a date time: SELECT EXTRACT(DAY_MICROSECOND
FROM '2017-07-14 09:04:44') DAY_MS;

22 | P a g e
SQL - NOTES

 Extract hour from a date time: SELECT EXTRACT(HOUR FROM '2017-07-14 09:04:44')
HOUR;
 Extract month from a date time: SELECT EXTRACT(MONTH FROM '2017-07-14
09:04:44') MONTH;
 Extract year from a date time: SELECT EXTRACT(YEAR FROM '2017-07-14 09:04:44')
YEAR;
 Extract year_month from a date time: SELECT EXTRACT(YEAR_MONTH FROM '2017-
07-14 09:04:44') YEARMONTH;
9. LAST_DAY Function: The LAST_DAY () function takes a DATE or DATETIME value and
returns the last day of the month for the input date.

19 SQL - Having Clause


The HAVING Clause enables you to specify conditions that filter which group results appear
in the results. The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by the GROUP BY clause.
Syntax: The following code block shows the position of the HAVING Clause in a query:
SELECT FROM WHERE GROUP BY HAVING ORDER BY
The HAVING clause must follow the GROUP BY clause in a query and must also precede the
ORDER BY clause if used. The following code block has the syntax of the SELECT statement
including the HAVING clause - SELECT column1, column2 FROM table1, table2 WHERE
[conditions] GROUP BY column1, column2 HAVING [conditions] ORDER BY column1;
Example:
 SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS GROUP BY age HAVING
COUNT (age)>=2;
 SELECT customer_id, sum (Purchase_amt) as "Total Amount", min(Purchase_amt) as
"Minimum Amount", MAX(Purchase_amt) as “ Maximum amount", AVG(Purchase_amt)
as "Average Amount", COUNT(Purchase_amt) as "Number of orders" FROM `orders`
GROUP by Customer_ID having count (Customer_ID)>=2 ORDER by Customer_ID desc
 SELECT City, COUNT(Cust_Id) as 'No of customers' from customer GROUP BY City HAVING
count(Cust_Id)>1;

20 SQL - Sub Queries


A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause. A subquery is used to return data that will be used in
the main query as a condition to further restrict the data to be retrieved. Subqueries can be
used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators
like =, <, >, >=, <=, IN, BETWEEN, etc. There are a few rules that subqueries must follow –
 Subqueries must be enclosed within parentheses.

23 | P a g e
SQL - NOTES

 A subquery can have only one column in the SELECT clause unless multiple columns are
in the main query for the subquery to compare its selected columns.
 An ORDER BY command cannot be used in a subquery, although the main query can use
an ORDER BY. The GROUP BY command can be used to perform the same function as
the ORDER BY in a subquery.
 The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
a) Subqueries with the SELECT Statement: Subqueries are most frequently used with the
SELECT statement.
The basic syntax is as follows: SELECT column_name [, column_name] FROM table1 [,
table2] WHERE column_name OPERATOR (SELECT column_name [, column_name]
FROM table1 [, table2] [WHERE])
Example:
SELECT * FROM CUSTOMER WHERE customer_id IN (SELECT customer_id FROM CUSTO
MER WHERE credit >10000);
b) Subqueries with the INSERT Statement: Subqueries also can be used with INSERT
statements. The INSERT statement uses the data returned from the subquery to insert
into another table. The selected data in the subquery can be modified with any of the
character, date or number functions.
The basic syntax is as follows: INSERT INTO table_name [(column1 [, column2]) SELECT
[*|column1 [, column2] FROM table1 [, table2][WHERE VALUE OPERATOR]
Example: Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table.
Now to copy the complete CUSTOMERS table into the CUSTOMERS_copy table, you can
use the following syntax: INSERT INTO CUSTOMER_copy SELECT * FROM CUSTOMER
WHERE customer_id IN (SELECT customer_id FROM CUSTOMER);
c) Subqueries with the UPDATE Statement: The subquery can be used in conjunction with
the UPDATE statement. Either single or multiple columns in a table can be updated
when using a subquery with the UPDATE statement.
The basic syntax is as follows: UPDATE table SET column_name = new_value[WHERE
OPERATOR [VALUE] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
Example: Assuming, we have CUSTOMERS_BKP table available which is backup of
CUSTOMERS table. The following example updates SALARY by 10 times in the
CUSTOMERS table for all the customers whose city is Moscow: UPDATE CUSTOMER SET
credit = credit * 10 WHERE city IN (SELECT city FROM CUSTOMER_copy WHERE city
='Moscow' );
d) Subqueries with the DELETE Statement: The subquery can be used in conjunction with
the DELETE statement like with any other statements mentioned above.
The basic syntax is as follows: DELETE FROM TABLE_NAME [WHERE OPERATOR [VALUE]
(SELECT COLUMN_NAME FROM TABLE_NAME) [WHERE)]
Example: Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the CUSTOMERS

24 | P a g e
SQL - NOTES

table for all the customers whose AGE is greater than or equal to 27: DELETE FROM
CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27);

21 SQL - USING Clause


USING Clause is used to match only one column when more than one column matches. It
should not have a qualifier (table name or Alias) in the referenced columns. NATURAL JOIN
uses all the columns with matching names and datatypes to join the tables. The USING
Clause can be used to specify only those columns that should be used for an EQUIJOIN.
Example: Write SQL query to find the working location of the employees. Also give their
respective employee_id and last_name.
The example shown joins the DEPARTMENT_ID column in the EMPLOYEES and
DEPARTMENTS tables, and thus shows the location where an employee works: SELECT
e.EMP_ID, e.emp_name, d.dep_location FROM Employees e JOIN Department d USING
(dep_id);
Example: Write SQL query to find the employee_id, employee_name, department_name
and department_location: SELECT e.emp_id, e.emp_name, d.dep_name, d.dep_location
FROM employees e JOIN department d USING (dep_id);

22 SQL – ALL and ANY


ALL & ANY are logical operators in SQL. They return Boolean value as a result.
1. ALL
ALL operator is used to select all tuples of SELECT STATEMENT. It is also used to compare a
value to every value in another value set or result from a subquery.
The ALL operator returns TRUE if all of the subquery’s values meet the condition. The ALL
must be preceded by comparison operators and evaluates true if all of the subquery’s values
meet the condition. ALL is used with SELECT, WHERE, HAVING statement.

Syntax: SELECT ALL field names FROM table_name WHERE condition(s);


ALL with WHERE or HAVING Statement Syntax: SELECT column_name(s) FROM table_name
WHERE column_name comparison operator ALL (SELECT column_name FROM table_name
WHERE condition(s));
2. ANY
ANY compares a value to each value in a list or results from a query and evaluates to true if
the result of an inner query contains at least one row. ANY return true if any of the
subquery’s values meet the condition. ANY must be preceded by comparison operators.

25 | P a g e
SQL - NOTES

Syntax: SELECT column_name(s) FROM table_name WHERE column_name comparison


operator ANY(SELECT column_name FROM table_ name WHERE condition(s));
EXAMPLE:
Select * from customer WHERE salesman_id = ANY(SELECT salesman_id from salesman WHE
RE salesman_city="Paris");

23 SQL – EXISTS Operator


The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns TRUE if the subquery returns one or more records.
Syntax: SELECT column_name(s)FROM table_name WHERE EXISTS (SELECT column_name
FROM table_name WHERE condition);
Example: SELECT SupplierName FROM Suppliers WHERE EXISTS (SELECT ProductName FROM
Products WHERE Products.SupplierID = Suppliers. supplierID AND Price < 20);

24 SQL – LIMIT Clause


The LIMIT clause is used in the SELECT statement to constrain the number of rows to return.
The LIMIT clause accepts one or two arguments. The values of both arguments must be zero
or positive integers.
LIMIT clause syntax with two arguments: SELECT select_list FROM table_name LIMIT
[offset,] row_count;
In this syntax:
 The offset specifies the offset of the first row to return. The offset of the first row is 0,
not 1.
 The row_count specifies the maximum number of rows to return.
 When you use the LIMIT clause with one argument, MySQL will use this argument to
determine the maximum number of rows to return from the first row of the result set.
Therefore, these two clauses are equivalent:
LIMIT row_count;
LIMIT 0, row_count;
 MySQL provides the following alternative LIMIT clause syntax: LIMIT row_count OFFSET
offset
The following picture illustrates the LIMIT clause:

26 | P a g e
SQL - NOTES

24.1 The LIMIT and ORDER BY clauses


By default, the SELECT statement returns rows in an unspecified order. When you add
the LIMIT clause to the SELECT statement, the returned rows are unpredictable. Therefore,
to ensure the LIMIT clause returns an expected output, you should always use it with
an ORDER BY clause like this: SELECT select_list FROM table_name ORDER BY
sort_expression LIMIT offset, row_count;
The following picture illustrates the evaluation order of the LIMIT clause in
the SELECT statement:

EXAMPLE: This statement uses the LIMIT clause to get the top three customers who have
the highest credit: SELECT customer_id, customer_ name, credit FROM customer ORDER BY
credit DESC LIMIT 3;

24.2 LIMIT & DISTINCT clauses


If you use the LIMIT clause with the DISTINCT clause, MySQL immediately stops searching
when it finds the number of unique rows specified in the LIMIT clause.
The example uses the LIMIT clause with the DISTINCT clause to return the first 3 unique
cities in the customer’s table: SELECT DISTINCT city FROM customer WHERE city IS NOT NULL
LIMIT 3;

25 SQL - JOINS
The SQL Joins clause is used to combine records from two or more tables in a database. In a
relational database, the data stored are all related but scattered throughout the database as
multiple tables. So, if there arises a need to retrieve cohesive data from multiple tables, a
simple Join clause can be used. With a Join clause, fields from two tables can be combined
by using values common to each. The join keyword merges two or more tables and creates a
temporary image of the merged table.

27 | P a g e
SQL - NOTES

A Join Clause works with respect to a join-predicate. This join-predicate is specified in a


WHERE clause; so, it is nothing but a condition that must be satisfied by database tables in
order to combine them. For example, comparing the equality (=) of values in similar columns
of two different tables can be considered as a join-predicate. In addition, several operators
can be used to join tables, such as <, >, <>, <=, >=, ! =, BETWEEN, LIKE, and NOT etc.

25.1 Join vs. Subquery.


 JOINs are faster than a subquery and it is very rare that the opposite.
 In JOINs the RDBMS calculates an execution plan, that can predict, what data should be
loaded and how much it will take to processed and as a result this process save
sometimes, unlike the subquery there is no pre-process calculation and run all the
queries and load all their data to do the processing.
 A JOIN is checked conditions first and then put it into table and displays, where as a
subquery take separate temp table internally and checking condition.
 When joins are using, there should be connection between two or more than two tables
and each table has a relation with other while subquery means query inside another
query, has no need to relation, it works on columns and conditions.

25.2 INNER JOIN


The INNER JOIN - returns rows when there is a match in both tables. The most important
and frequently used of the joins is the INNER JOIN. They are also referred to as
an EQUIJOIN. The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied. This keyword will create the result-set by combining all rows from
both the tables where the condition satisfies i.e. value of the common field will be the
same.

Syntax: SELECT table1.column1, table1.column2, table2.column1 FROM table1 INNER JOIN


table2 ON table1.matching_column = table2. matching_column;
Example: SELECT c.customer_id as "Customer_Customer_id", o.customer_id as
"Orders_customer_id", c.customer_name, o.purchase_amt FROM CUSTOMER c INNER JOIN
orders o on c.customer_id = o.CUSTOMER_ID;
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.

28 | P a g e
SQL - NOTES

25.3 LEFT JOIN


The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that if the ON clause matches 0 (zero) records in the right table; the
join will still return a row in the result, but with NULL in each column from the right table.
This means that a left join returns all the values from the left table, plus matched values
from the right table or NULL in case of no matching join predicate.

Syntax: SELECT table1.column1, table2.column2 FROM table1 LEFT JOIN table2 ON


table1.common_field = table2.common_field;
Example: SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON
CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.

25.4 RIGHT JOIN

SQL RIGHT JOIN is similar to LEFT JOIN, except that the treatment of the joined tables is
reversed. Here’s the syntax of the RIGHT JOIN of two tables t1 and t2:
Syntax: SELECT select_list FROM t1 RIGHT JOIN t2 ON join_condition;
In this syntax:
 The t1 is the left table and t2 is the right table.
 The join_condition specifies the rule for matching rows from both tables.
 If the join_condition uses the equal operator (=) and the joined columns of both tables
have the same name, and you can use the USING syntax like this: SELECT select_list
FROM t1 RIGHT JOIN t2 USING (column_name);

29 | P a g e
SQL - NOTES

 Therefore, the following join conditions are equivalent: ON t1.column_name =


t2.column_name and USING (column_name);
How the RIGHT JOIN works ?
The RIGHT JOIN starts selecting data from the right table (t2). It matches each row from the
right table with every row from the left table. If both rows cause the join condition to
evaluate to TRUE, the RIGHT JOIN combines columns of these rows into a new row and
includes this new row in the result set.
If a row from the right table does not have a matching row from the left table, the RIGHT
JOIN combines columns of rows from the right table with NULL values for all columns of the
right table into a new row and include this row in the result set.
In other words, the RIGHT JOIN returns all rows from the right table regardless of having
matching rows from the left table or not. Notice that the RIGHT OUTER JOIN is a synonym
for RIGHT JOIN. Therefore, you can use them interchangeably.

25.5 SELF JOIN


A self-join is a regular join that is used to join a table with itself. It basically allows us to
combine the rows from the same table based on some specific conditions. It is very useful
and easy to work with, and it allows us to retrieve data or information which involves
comparing records within the same table.
Syntax: The basic syntax of SELF JOIN is as follows:
 SELECT a. column_name, column_name...FROM table1 a, table1 b WHERE a.
common_field = b.common_field;
 SELECT columns FROM table alias1 JOIN table alias2 ON alias1.column = alias2.column;
Example: SELECT a.ID, b.NAME, a. SALARY FROM CUSTOMERS a, CUSTOMERS b WHERE a.
SALARY<b. SALARY;
Example:
Let’s use an illustration to further understand how the self-join functions. Assume that we
have a table called “Sample_Employees” with the column’s employee_id, employee_name,
and manager_id. Each employee in the company is assigned a manager, and using the
manager-ids, we can identify each employee. We need to extract the list of employees along
with the names of their managers because the manager_id column contains the manager ID
for each employee.
Step 1: First, we need to create the “Sample_Employees” table with following query:
CREATE TABLE Sample_Employees (employee_id int, employee_name varchar (50),
manager_id int);
Step 2: Now we will add data into the ‘Sample_Employees’ table using INSERT INTO
statement: INSERT INTO Sample_Employees (employee_id, employee_name, manager_id)
VALUES (1, 'Zaid', 3), (2, 'Rahul', 3), (3, 'Raman', 4), (4, 'Kamran', NULL), (5, 'Farhan', 4);

30 | P a g e
SQL - NOTES

Step 3: Explanation and implementation of Self Join: Now, we need to perform self-join
on the table we created i.e. Sample_Employees in order to retrieve the list of employees
and their corresponding managers name and for that we need to write a query, where we
will create two different aliases for the “Sample_Employees” table as “e” which will
represent the Sample_Employees information and “m” will represent the manager’s
information. This way by joining the table with itself using the manager_id and employee_id
columns, we can generate relationship between employees and their managers.
Step 4: Query for Self-join: SELECT e.employee_name AS employee, m.employee_name AS
manager FROM Sample_Employees e JOIN Sample_Employees m ON e.manager_id =
m.employee_id;

26 SQL - Stored Procedures


A stored procedure is a set of Structured Query Language (SQL) statements with an assigned
name, which are stored in a relational database management system as a group, so it can be
reused and shared by multiple programs. Stored procedures in SQL can accept input
parameters and return multiple values of output parameters; in SQL Server, stored
procedures program statements to perform operations in the database and return a status
value to a calling procedure. If you want to save this query on the database server for
execution later, one way to do it is to use a stored procedure. By definition, a stored
procedure is a segment of declarative SQL statements stored inside the MySQL
What are the Benefits of using a Stored Procedure in SQL?
Stored procedures provide some crucial benefits, which are:
 Reusable: As mentioned, multiple users and applications can easily use and reuse stored
procedures by merely calling it.
 Easy to modify: You can quickly change the statements in a stored procedure as and
when you want to, with the help of the ALTER TABLE command.
 Security: Stored procedures allow you to enhance the security of an application or a
database by restricting the users from direct access to the table.
 Low network traffic: The server only passes the procedure name instead of the whole
query, reducing network traffic.
 Increases performance: Upon the first use, a plan for the stored procedure is created
and stored in the buffer pool for quick execution for the next time.

26.1 Create Procedure


To create a new stored procedure, you use the CREATE PROCEDURE statement. Here is the
basic syntax of the CREATE PROCEDURE statement:
CREATE PROCEDURE procedure_name (parameter_list)
BEGIN

31 | P a g e
SQL - NOTES

Statements;
END //
In this syntax
 Specify the name of the stored procedure that you want to create after the CREATE
PROCEDURE keywords.
 Specify a list of comma-separated parameters for the stored procedure in parentheses
after the procedure name.
 Write the code between the BEGIN END block. The above example just has a
simple SELECT statement.
 After the END keyword, you place the delimiter character to end the procedure
statement.

26.2 DROP PROCEDURE Statement


The DROPPROCEDURE deletes a stored procedure from the database. The following shows
the syntax of the DROP PROCEDURE statement:
DROP PROCEDURE[IF EXISTS] stored_procedure_name;
In this syntax:
 Specify the name of the stored procedure that you want to remove after the DROP
PROCEDURE keywords.
 Use IF EXISTS option to conditionally drop the stored procedure if it exists only.

26.3 Stored Procedure Parameters


Almost stored procedures that you develop require parameters. The parameters make the
stored procedure more flexible and useful. In MySQL, a parameter has one of three
modes: IN, OUT, or INOUT.
26.3.1 IN parameters
IN is the default mode. When you define an IN parameter in a stored procedure, the calling
program must pass an argument to the stored procedure. In addition, the value of
an IN parameter is protected. It means that even the value of the IN parameter is changed
inside the stored procedure, its original value is retained after the stored procedure ends. In
other words, the stored procedure only works on the copy of the IN parameter.
The IN - Parameter Example: The following example creates a stored procedure that finds
the city of the customer specified by the input parameter cityName:

32 | P a g e
SQL - NOTES

26.3.2 OUT parameters


The value of an OUT parameter can be changed inside the stored procedure and its new
value is passed back to the calling program. Notice that the stored procedure cannot access
the initial value of the OUT parameter when it starts.
The OUT - Parameter Example: The following stored procedure returns the number of
orders by order status.

The stored procedure GetOrderCountBySalesmanId() has two parameters:


 sid: is the IN parameter specifies the status of orders to return.
 TotalOrders: is the OUT parameter that stores the number of orders in a specific
salesmanid.
To find the number of orders that already shipped, you call GetOrderCountBySalesmanId(),
and also pass a session variable (@totalOrders) to receive the return value.
26.3.3 INOUT parameters
An INOUT parameter is a combination of IN and OUT parameters. It means that the calling
program may pass the argument, and the stored procedure can modify
the INOUT parameter, and pass the new value back to the calling program.

26.4 IF Statement
The IF statement has three forms: simple IF-THEN statement, IF-THEN-ELSE statement,
and IF-THEN-ELSEIF- ELSE statement.

33 | P a g e
SQL - NOTES

26.4.1 Simple IF-THEN Statement


The IF-THEN statement allows you to execute a set of SQL statements based on a specified
condition. The following illustrates the syntax of the IF-THEN statement:
IF condition THEN
Statements;
END IF;
In this syntax: First, specify a condition to execute the code between the IF-THEN and END
IF. If the condition evaluates to TRUE, the statements between IF-THEN and END IF will
execute. Otherwise, the control is passed to the next statement following the END IF.
Second, specify the code that will execute if the condition evaluates to TRUE.
Example to see the following GetCustomerLevel () stored procedure.

 The stored procedure GetCustomerLevel() accepts two parameters: pCustomerId and


pCustomerLevel.
 First, select credit of the customer specified by the pCustomerId from the customer
table and store it in the local variable creditLimit.
 Then, set value for the OUT parameter pCustomerLevel to PLATINUM if the credit limit
of the customer is greater than 5000.
26.4.2 IF-THEN-ELSE statement
In case you want to execute other statements when the condition in the IF branch does not
evaluate to TRUE, you can use the IF-THEN-ELSE statement as follows. In this syntax, if the
condition evaluates to TRUE, the statements between IF-THEN and ELSE execute. Otherwise,
the else statements between the ELSE and END IF execute.
IF condition THEN
Statements;
ELSE
Else-statements;
END IF;
Example to see the following GetCustomerLevel () stored procedure.

34 | P a g e
SQL - NOTES

26.4.3 IF-THEN-ELSEIF-ELSE statement


If you want to execute statements conditionally based on multiple conditions, you use the
following IF-THEN-ELSEIF-ELSE statement:
Syntax
IF condition THEN
Statements;
ELSEIF elseif-condition THEN
Elseif-statements;

ELSE
Else-statements;
END IF;
Example: to see the following GetCustomerLevelThree () stored procedure.

26.5 CASE Statement


Besides the IF statement, MySQL provides an alternative conditional statement called the
CASE statement for constructing conditional statements in stored procedures. The CASE
statements make the code more readable and efficient. The CASE statement has two forms:
simple CASE and searched CASE statements.

35 | P a g e
SQL - NOTES

The following is the basic syntax of the simple CASE statement:


CASE caseValue
WHEN when_value1 THEN statements
WHEN when_value2 THEN statements
...
[ELSE else-statements]
ENDCASE;
In this syntax, the simple CASE statement sequentially compares the case_value is with
the when_value1, when_value2, until it finds one is equal. When the CASE finds
a case_value equal to a when value, it executes statements in the corresponding THEN
clause. If CASE cannot find any when value equal to the case_value, it executes the else
statements in the ELSE clause if the ELSE clause is available. When the ELSE clause does not
exist and the CASE cannot find any when value equal to the case_value, it issues an error:
Simple CASE statement example: The following stored procedure illustrates how to use the
simple CASE statement

The GetCustomerShipping() stored procedure accepts two parameters:


pCustomerNumber as an IN parameter and pShipping as an OUT parameter.
In the stored procedure: First, select the city of the customer from the customers table by
the input customer number. Second, use the simple CASE statement to determine the
shipping time based on the country of the customer. If the customer locates in California,
the shipping time is 2-day shipping. If the customer locates in London, the shipping time is 3-
day shipping. The customers from other countries have 5-day shipping.
26.5.1 Searched CASE statement
The simple CASE statement only allows you to compare a value with a set of distinct values.
To perform more complex matches such as ranges, you use the searched CASE statement.
The searched CASE statement is equivalent to the IF statement, however, it’s much more
readable than the IF statement.
Here is the basic syntax of the searched CASE statement:
CASE

36 | P a g e
SQL - NOTES

WHEN search_condition1 THEN statements


WHEN search_condition1 THEN statements

[ELSE else-statements]
ENDCASE;
In this syntax, searched CASE evaluates each search condition in the WHEN clause until it
finds a condition that evaluates to TRUE , then it executes the
corresponding THEN clause statements. If no search condition evaluates to TRUE,
the CASE will execute else-statements in the ELSE clause if an ELSE clause is available. Like
the simple CASE statement, if you don’t specify an ELSE clause and no condition is TRUE,
MySQL raises the same error: Case not found for CASE statement
MySQL also does not allow you to have empty statements in the THEN or ELSE clause. If you
don’t want to handle the logic in the ELSE clause while preventing MySQL from raising an
error in case no search condition is true, you can use an empty BEGIN END block in
the ELSE clause.
Searched CASE statement example:

26.6 MySQL LOOP


The LOOP statement allows you to execute one or more statements repeatedly. Here is the
basic syntax of the LOOP statement:
[begin_label:] LOOP
statement_list
END LOOP [end_label]
The LOOP can have optional labels at the beginning and end of the block. The LOOP
executes the statement_list repeatedly. The statement_list may have one or more
statements, each terminated by a semicolon (;) statement delimiter. Typically, you

37 | P a g e
SQL - NOTES

terminate the loop when a condition is satisfied by using the LEAVE statement. This is the
typical syntax of the LOOP statement used with LEAVE statement:
[label]: LOOP
...
-- terminate the loop
IF condition THEN
LEAVE [label];
END IF;
...
END LOOP;
The LEAVE statement immediately exits the loop. It works like the break statement in other
programming languages like PHP, C/C++, and Java. In addition to the LEAVE statement, you
can use the ITERATE statement to skip the current loop iteration and start a new iteration.
The ITERATE is like the continue statement in PHP, C/C++, and Java.
MySQL LOOP statement example: The following statement creates a stored procedure that
uses a LOOP loop statement:

In this example:
 The stored procedure constructs a string from the even numbers e.g., 2, 4, and 6.
 The loop_label before the LOOP statement for using with
the ITERATE and LEAVE statements.
 If the value of x is greater than 10, the loop is terminated because of the LEAVE
statement.

38 | P a g e
SQL - NOTES

 If the value of the x is an odd number, the ITERATE ignores everything below it and
starts a new loop iteration.
 If the value of the x is an even number, the block in the ELSE statement will build the
result string from even numbers.
26.6.1 MySQL WHILE Loop
The WHILE loop is a loop statement that executes a block of code repeatedly as long as a
condition is true. Here is the basic syntax of the WHILE statement:
[begin_label:] WHILE search_condition DO
statement_list
END WHILE [end_label]
In this syntax:
 First, specify a search condition after the WHILE keyword.
 The WHILE checks the search_condition at the beginning of each iteration.
 If the search_condition evaluates to TRUE, the WHILE executes the statement_list as
long as the search_condition is TRUE.
 The WHILE loop is called a pretest loop because it checks the search_condition before
the statement_list executes.
 Second, specify one or more statements that will execute between the DO and END
WHILE keywords.
 Third, specify optional labels for the WHILE statement at the beginning and end of the
loop construct.
The following flowchart illustrates the MySQL WHILE loop statement:

MySQL WHILE loop statement example:


 First, create a table named calendars which stores dates and derived date information
such as day, month, quarter, and year: CREATE TABLE calendars(id INT

39 | P a g e
SQL - NOTES

AUTO_INCREMENT, fulldate DATE UNIQUE, day TINYINT NOT NULL, month TINYINT NOT
NULL, quarter TINYINT NOT NULL, year INT NOT NULL,PRIMARY KEY(id));
 Second, create a new stored procedure to insert a date into the calendars table:
DELIMITER $$
CREATE PROCEDURE InsertCalendar(dt DATE)
BEGIN
INSERT INTO calendars (fulldate, day, month, quarter, year) VALUES (dt, EXTRACT(DAY
FROM dt), EXTRACT(MONTH FROM dt), EXTRACT(QUARTER FROM dt), EXTRACT(YEAR
FROM dt));
END$$
DELIMITER ;
 Third, create a new stored procedure LoadCalendars() that loads a number of days
starting from a start date into the calendars table.
DELIMITER $$
CREATE PROCEDURE LoadCalendars(startDate DATE, day INT)
BEGIN
DECLARE counter INT DEFAULT 1;
DECLARE dt DATE DEFAULT startDate;
WHILE counter <= day DO
CALL InsertCalendar(dt);
SET counter = counter + 1;
SET dt = DATE_ADD(dt, INTERVAL 1 day);
END WHILE;
END$$
DELIMITER ;
 The stored procedure LoadCalendars() accepts two arguments: startDate is the start
date inserted into the calendars table. day is the number of days that will be loaded
starting from the startDate.
 In the LoadCalendars() stored procedure: First, declare a counter and dt variables for
keeping immediate values. The default values of counter
and dt are 1 and startDate respectively. Then, check if the counter is less than or
equal day, if yes: Call the stored procedure InsertCalendar() to insert a row into
the calendars table. Increase the counter by one. Also, increase the dt by one day using

40 | P a g e
SQL - NOTES

the DATE_ADD () function. The WHILE loop repeatedly inserts dates into
the calendars table until the counter is equal to day.

26.7 MySQL REPEAT Loop

The REPEAT statement executes one or more statements until a search condition is true.
Here is the basic syntax of the REPEAT loop statement:
[begin_label:] REPEAT
statement
UNTIL search_condition
END REPEAT [end_label]
 The REPEAT executes the statement until the search_condition evaluates to true.
 The REPEAT checks the search_condition after the execution of statement, therefore,
the statement always executes at least once. Therefore, the REPEAT is also known as a
post-test loop.
 The REPEAT statement can have labels at the beginning and at the end. These labels are
optional.
This statement creates a stored procedure called RepeatLoopExample() that uses
the REPEAT statement to concatenate numbers from 1 to 9:

41 | P a g e
SQL - NOTES

26.8 MySQL LEAVE


The LEAVE statement exits the flow control that has a given label. The following shows the
basic syntax of the LEAVE statement: LEAVE Label; In this syntax, you specify the label of the
block that you want to exit after the LEAVE keyword.
26.8.1 Using the LEAVE statement to exit a stored procedure
If the label is the outermost of the stored procedure or function block, LEAVE terminates
the stored procedure or function. The following statement shows how to use
the LEAVE statement to exit a stored procedure:
CREATE PROCEDURE sp_name ()
sp: BEGIN
IF condition THEN
LEAVE sp;
END IF;
-- Other statement
END$$
EXAMPLE of MySQL leave statement is as follows:

42 | P a g e
SQL - NOTES

26.9 Error Handling in Stored Procedures


When an error occurs inside a stored procedure, it is important to handle it appropriately,
such as continuing or exiting the current code block’s execution, and issuing a meaningful
error message. MySQL provides an easy way to define handlers that handle from general
conditions such as warnings or exceptions to specific conditions e.g., specific error codes.
26.9.1 Declaring a handler
To declare a handler, you use the DECLARE HANDLER statement as follows: DECLARE action
HANDLER FOR condition_value statement;
If a condition whose value matches the condition_value, MySQL will execute
the statement and continue or exit the current code block based on the action.
The action accepts one of the following values:
 CONTINUE: the execution of the enclosing code block (BEGIN … END) continues.
 EXIT: the execution of the enclosing code block, where the handler is declared,
terminates.
The condition_value specifies a particular condition or a class of conditions that activate the
handler. The condition_value accepts one of the following values:
 A MySQL error code.
 A standard SQLSTATE value. Or it can be
an SQLWARNING, NOTFOUND or SQLEXCEPTION condition, which is shorthand for the
class of SQLSTATE values. The NOTFOUND condition is used for a cursor or SELECT INTO
variable_list statement.
 A named condition associated with either a MySQL error code or SQLSTATE value.

43 | P a g e
SQL - NOTES

The statement could be a simple statement or a compound statement enclosing by


the BEGIN and END keywords.

27 SQL Exercises, Practice, Solution


27.1 Boolean, Relational, Wildcard and Special operators
1. Write a query to display all customers with a grade above 100.
SELECT * FROM customer WHERE grade >100;
2. Write a query statement to display all customers in New York who have a grade value
above 100.
SELECT * FROM customer WHERE city ='New York' AND grade>100;
3. Write a SQL statement to display all customers, who are either belongs to the city New
York or had a grade above 100.
SELECT * FROM customer WHERE city ='New York' OR grade>100;
4. Write a SQL statement to display all the customers, who are either belongs to the city
New York or not had a grade above 100.
SELECT * FROM customer WHERE city ='New York' OR NOT grade>100;
5. Write a SQL query to display those customers who are neither belongs to the city New
York nor grade value is more than 100.
SELECT * FROM customer WHERE NOT(city ='New York' OR grade>100);
6. Write a SQL statement to display either those orders which are not issued on date 2012-
09-10 and issued by the salesman whose ID is 5005 and below or those orders which
purchase amount is 1000.00 and below.
SELECT * FROM orders WHERE NOT ((order_date='2012-09-10' AND salesman_id<=5005)
OR purchase_amt<=1000.00);
7. Write a SQL statement to display salesman_id, name, city and commission who gets the
commission within the range more than 0.10% and less than 0.12%.
SELECT salesman_id, name, city, commission FROM salesman WHERE (commission>0.10
AND commission<0.12);
8. Write a SQL query to display all orders where purchase amount less than 200 or exclude
those orders which order date is on or greater than 10th Feb, 2012 and customer id is
below 3009.
SELECT * FROM orders WHERE (purch_amt<200 OR NOT (ord_date>='2012-02-10'AND
customer_id<3009));
9. Write a SQL statement to exclude the rows which satisfy 1) order dates are 2012-08-17
and purchase amount is below 1000 2) customer id is greater than 3005 and purchase
amount is below 1000.
SELECT * FROM orders WHERE NOT ((ord_date ='2012-08-17' OR customer_id>3005)
AND purch_amt<1000);
10. Write a SQL statement to find those salesmen with all information who come from the
city either Paris or Rome.

44 | P a g e
SQL - NOTES

SELECT * FROM salesman WHERE city ='Paris' OR city ='Rome';


11. Write a query to filter those salesmen with all information who comes from any of the
cities Paris and Rome.
SELECT * FROM salesman WHERE city IN ('Paris’, ‘Rome');
12. Write a query to produce a list of salesman_id, name, city and commission of each
salesman who live in cities other than Paris and Rome.
SELECT * FROM salesman WHERE city NOT IN('Paris’, ‘Rome');
13. Write a query to sort out those customers with all information whose ID value is within
any of 3007, 3008 and 3009.
SELECT * FROM customer WHERE customer_id IN(3007, 3008, 3009);
14. Write a SQL statement to find those salesmen with all information who get the
commission within a range of 0.12 and 0.14.
SELECT * FROM salesman WHERE commission BETWEEN 0.12 AND 0.14;
15. Write a query to filter all those orders with all information which purchase amount value
is within the range 500 and 4000 except those orders of purchase amount value 948.50
and 1983.43.
SELECT * FROM orders WHERE(purch_amt BETWEEN 500 AND 4000) AND NOT
purch_amt IN (948.50, 1983.43);
16. Write a SQL statement to find those salesmen with all other information and name
started with any letter within 'A' and 'K'.
SELECT * FROM salesman WHERE name BETWEEN 'A' and 'L';
17. Write a SQL statement to find those salesmen with all other information and name
started with other than any letter within 'A' and 'L'.
SELECT * FROM salesman WHERE name NOT BETWEEN 'A' and 'L';
18. Write a SQL statement to find that customers whose name begin with the letter 'B'.
SELECT * FROM customer WHERE cust_name LIKE 'B%';
19. Write a SQL statement to find those salesmen with all information whose name
containing the 1st character is 'N' and the 4th character is 'l' and rests may be any
character.
SELECT * FROM salesman WHERE name LIKE 'N__l%';
20. Write a query to display the orders according to the order number arranged by
ascending order.
SELECT * FROM orders ORDER BY ord_no;

27.2 Aggregate Functions


1. Write a SQL statement to find the total purchase amount and average purchase amount
of all orders.
SELECT SUM(purch_amt), AVG(purch_amt) FROM orders;
2. Write a SQL statement to know how many customers have listed their names.
SELECT COUNT(*) FROM customer;
3. Write a SQL statement to find the number of salesmen currently listing for all of their
customers.

45 | P a g e
SQL - NOTES

SELECT COUNT(DISTINCT salesman_id) FROM orders;


4. Write a SQL statement to get the maximum purchase amount and minimum purchase
amount of all the orders.
SELECT MAX(purch_amt), MIN(purch_amt) FROM orders;
5. Write a SQL statement which selects the highest grade for each of the cities of the
customers.
SELECT city, MAX(grade) FROM customer GROUP BY city;
6. Write a SQL statement to find the highest purchase amount ordered by each customer
with their ID and highest purchase amount.
SELECT customer_id, MAX(purch_amt) FROM orders GROUP BY customer_id;
7. Write a SQL statement to find the highest purchase amount ordered by each customer
on a particular date with their ID, order date and highest purchase amount.
SELECT customer_id, ord_date, MAX(purch_amt) FROM orders GROUP BY customer_id;
8. Write a SQL statement to find the highest purchase amount on a date '2012-08-17' for
each salesman with their ID.
SELECT salesman_id, MAX(purch_amt) FROM orders WHERE ord_date ='2012-08-17'
GROUP BY salesman_id;
9. Write a SQL statement to find the highest purchase amount with their ID and order date,
for only those customers who have highest purchase amount in a day is more than 2000.
SELECT customer_id, ord_date, MAX(purch_amt) FROM orders GROUP BY customer_id
HAVING MAX(purch_amt)>2000.00;
10. Write a SQL statement to find the highest purchase amount with their ID and order date,
for those customers who have a higher purchase amount in a day is within the range
2000 and 6000.
SELECT customer_id, ord_date, MAX(purch_amt) FROM orders GROUP BY customer_id
HAVING MAX(purch_amt) BETWEEN 2000 AND 6000;
11. Write a SQL statement to find the highest purchase amount with their ID and order date,
for only those customers who have a higher purchase amount in a day is within the list
2000, 3000, 5760 and 6000.
SELECT customer_id, ord_date, MAX(purch_amt) FROM orders GROUP BY customer_id
HAVING MAX(purch_amt) IN(2000, 3000, 5760, 6000);
12. Write a SQL statement to find the highest purchase amount with their ID, for only those
customers whose ID is within the range 3002 and 3007.
SELECT customer_id, MAX(purch_amt) FROM orders WHERE customer_id BETWEEN
3002 and 3007 order BY customer_id desc;
13. Write a SQL statement to display customer details (ID and only highest purchase
amount) who’s IDs are within the range 3002 and 3007 and highest purchase amount is
more than 1000.
SELECT customer_id, MAX(purch_amt) FROM orders WHERE customer_id BETWEEN
3002 and 3007 GROUP BY customer_id HAVING MAX(purch_amt)>1000;

46 | P a g e
SQL - NOTES

14. Write a SQL statement to find the highest purchase amount with their ID, for only those
salesmen whose ID is within the range 5003 and 5008.
SELECT salesman_id, MAX(purch_amt) FROM orders where salesman_id BETWEEN 5003
AND 5008 GROUP BY salesman_id;
15. Write a SQL statement that counts all orders for a date August 17th, 2012.
SELECT COUNT(*) FROM orders where ord_date='2012-08-17';
16. Write a query that counts the number of salesmen with their order date and ID
registering orders for each day.
SELECT ord_date, salesman_id, COUNT(*) FROM orders GROUP BY ord_date,
salesman_id;

27.3 Subqueries
1. Write a query to display all the orders for the salesman who belongs to the city London.
SELECT * FROM orders WHERE salesman_id = (SELECT salesman_id FROM salesman
WHERE city='London');
2. Write a query to find all the orders issued against the salesman who may works for
customer whose id is 3007.
SELECT * FROM orders WHERE salesman_id = (SELECT DISTINCT salesman_id FROM
orders WHERE customer_id =3007);
3. Write a query to display all the orders which values are greater than the average order
value for 10th October 2012.
SELECT * FROM orders WHERE purchase_amt > (SELECT AVG(purchase_amt) FROM
orders WHERE order_date ='2012-10-10');
4. Write a query to find all orders attributed to a salesman in New York.
SELECT * FROM orders WHERE salesman_id IN (SELECT salesman_id FROM salesman
WHERE city ='New York');
5. Write a query to display the commission of all the salesmen servicing customers in Paris.
SELECT commission FROM salesman WHERE salesman_id IN (SELECT salesman_id FROM
customer WHERE city ='Paris');
6. Write a query to display all the customers whose id is 2001 below the salesman ID of Mc
Lyon.
SELECT * FROM customer WHERE customer_id = (SELECT salesman_id - 2001 FROM
salesman WHERE name ='Mc Lyon');
7. Write a query to count the customers with grades above New York's average.
SELECT grade, COUNT(grade) FROM customer GROUP BY grade HAVING grade>(SELECT
AVG(grade) FROM customer WHERE city = 'New York');
8. Write a query to extract the data from the orders table for those salesmen who earned
the maximum commission.
SELECT order_no, purchase_amt, order_date, salesman_id FROM orders WHERE
salesman_id IN (SELECT salesman_id FROM salesman WHERE commission = (SELECT
MAX (commission)FROM salesman));

47 | P a g e
SQL - NOTES

9. Write a query to find all orders with order amounts which are above-average amounts
for their customers.
Select * from orders where purchase_amt> (select AVG(purchase_amt) from orders);
10. Write a query to extract all data from the customer table if and only if one or more of
the customers in the customer table are located in London.
SELECT customer_id, customer_name, city FROM customer WHERE EXISTS(SELECT *
FROM customer WHERE city='London');
11. Write a query to find the salesmen who have multiple customers.
select * from salesman where salesman_id in (SELECT salesman_id FROM customer
GROUP BY salesman_id HAVING COUNT(salesman_id) >= 2)
12. Write a query to find all the salesmen for whom there are customers that follow them.
SELECT * FROM salesman WHERE city IN (SELECT city FROM customer);
13. Write a query to display all orders with an amount smaller than the maximum amount
for a customer in London.
SELECT * FROM orders WHERE purchase_amt < (SELECT MAX(purchase_amt) FROM
orders a, customer b WHERE a.customer_id= b.customer_id AND b.city = 'London');
14. Write a query to find all those customers whose grade are not as the grade who belongs
to the city Paris.
- SELECT * FROM customer WHERE grade NOT IN (SELECT grade FROM customer
WHERE city='Paris');

27.4 JOINS
1. Write a SQL statement to prepare a list with salesman name, customer name and their
cities for the salesmen and customer who belongs to the same city.
SELECT salesman.name AS "Salesman", customer.cust_name, customer.city FROM
salesman inner join customer WHERE salesman. City = customer.city;
2. Write a SQL statement to make a list with order no, purchase amount, customer name
and their cities for those orders which order amount between 500 and 2000.
SELECT a.ord_no, a.purch_amt, b.cust_name, b.city FROM orders a, customer b WHERE
a.customer_id = b.customer_id AND a.purch_amt BETWEEN 500 AND 2000;
3. Write a SQL statement to know which salesman are working for which customer.
SELECT a.cust_name AS "CustomerName", a.city, b.name AS "Salesman", b.commission
FROM customer a INNER JOIN salesman b ON a.salesman_id = b.salesman_id;
4. Write a SQL statement to find the list of customers who appointed a salesman for their
jobs who gets a commission from the company is more than 12%.
SELECT a.cust_name AS "Customer Name", a.city, b.name AS "Salesman", b.commission
FROM customer a INNER JOIN salesman b ON a. salesman_id = b. salesman_id WHERE
b.commission>.12;
5. Write a SQL statement to find the list of customers who appointed a salesman for their
jobs who does not live in the same city where their customer lives, and gets a
commission is above 12%.

48 | P a g e
SQL - NOTES

SELECT a.cust_name AS "Customer Name", a.city, b.name AS "Salesman", b.city,


b.commission FROM customer a INNER JOIN salesman b ON a.salesman_id =
b.salesman_id WHERE b.commission>.12AND a.city<>b.city;
6. Write a SQL statement to find the details of an order i.e. order number, order date,
amount of order, which customer gives the order and which salesman works for that
customer and commission rate he gets for an order.
SELECT a.ord_no, a.ord_date, a.purch_amt, b.cust_name AS "Customer Name", b.grade,
c.name AS "Salesman", c.commission FROM orders a INNER JOIN customer b ON
a.customer_id=b.customer_id INNER JOIN salesman c ON a.salesman_id =
c.salesman_id;
7. Write a SQL statement to make a list in ascending order for the customer who works
either through a salesman or by own.
SELECT a.cust_name, a.city, a.grade, b.name AS "Salesman", b.city FROM customer a
LEFT JOIN salesman b ON a.salesman_id = b.salesman_id order by a.customer_id;
8. Write a SQL statement to make a list in ascending order for the customer who holds a
grade less than 300 and works either through a salesman or by own.
SELECT a.cust_name, a.city, a.grade, b.name AS "Salesman", b.city FROM customer a
LEFT OUTER JOIN salesman b ON a.salesman_id = b.salesman_id WHERE a.grade<300
ORDER BY a.customer_id;

49 | P a g e

You might also like