SQL NOTES
SQL NOTES
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|Page
SQL - NOTES
3|Page
SQL - NOTES
B. Approximate Numeric Datatype: The subtypes of this datatype are given in the table
with the range.
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:
5|Page
SQL - NOTES
2. SQL Comparison Operators: Assume 'variable a' holds 10 and 'variable b' holds 20, then
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
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.
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.
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;
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);
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.
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;
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;
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;
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;
13 | P a g e
SQL - NOTES
14 | P a g e
SQL - NOTES
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 | P a g e
SQL - NOTES
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 | 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
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
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
Examples:
21 | P a g e
SQL - NOTES
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.
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);
25 | P a g e
SQL - NOTES
26 | P a g e
SQL - NOTES
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;
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
28 | P a g e
SQL - NOTES
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
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;
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.
32 | P a g e
SQL - NOTES
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
34 | P a g e
SQL - NOTES
35 | P a g e
SQL - NOTES
36 | P a g e
SQL - NOTES
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:
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.
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
42 | P a g e
SQL - NOTES
43 | P a g e
SQL - NOTES
44 | P a g e
SQL - NOTES
45 | P a g e
SQL - NOTES
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
49 | P a g e