SQL – Nested Queries
SQL Examples – Nested Query
• A query inside another query
– A inside query (sub-query) is evaluated first.
– It is common to enclose sub-query in parentheses for
readability!!
– SQL allows a subquery expression to be used in the from
clause
Example 1
• Display Employee name who is having
maximum salary.
SELECT Emp_name
FROM employee WHERE Salary = (SELECT
Max(Salary) FROM employee);
Emp_id Emp_name Dept_name Salary
101 John HR 10000
102 Alex IT 50000
103 Bob CSE 20000
104 Nitin CSE 40000
105 Monika HR 30000
Example 2
• Display second highest salary.
SELECT Salary
FROM employee WHERE Salary <> (SELECT
Max(Salary) FROM employee);
SELECT MAX(Salary)
FROM employee WHERE Salary <> (SELECT
Max(Salary) FROM employee);
Example 3
• Display employee name who is having second
highest salary.
SELECT MAX(Salary)
FROM employee WHERE Salary <> (SELECT
Max(Salary) FROM employee);
SELECT emp_name FROM employee where
Salary = (SELECT MAX(Salary)
FROM employee WHERE Salary <> (SELECT
Max(Salary) FROM employee));
GROUP BY clause
• Use GROUP BY clause
– ONLY grouping to group records, NOT sorting
(usually associated with ORDER BY clause)
• Group rows that have the same values into
summary rows.
• It is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to
group the result-set by one or more columns.
Syntax
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s);
•Example:
SELECT Payment_mode, SUM(amount) AS total
FROM payment
GROUP BY payment_mode;
GROUP BY Clause cont.
• Attributes in select clause outside of aggregate
functions must appear in group by list
– /* erroneous query */
select dept_name, ID , avg (salary)
from instructor
group by dept_name;
Example 1
• Display all the department names along with
number of employees working in each
department.
SELECT Dept_name, Count(*)
FROM employee
GROUP BY Dept_name;
Another Example
SELECT RepNum,
Count(*) AS NumOfCustomer,
Avg(Balance) AS AvgBalance
FROM Customer
GROUP BY RepNum
Aggregate Functions – Group By
• Find the average salary of instructors in each department
select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name;
HAVING Clause
• The HAVING clause is used to apply a filter on the
results of GROUP BY based on the specified
condition.
• The WHERE clause places conditions on the selected
columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY
clause. Example
• Syntax:
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s)
HAVING condition(s);
SQL Examples – Grouping (con’t)
– Use of “Having” command to Restrict Groups.
• Display all the department name where number of
employees are less than 2.
SELECT Dept_name FROM employee
GROUP BY Dept_name
HAVING Count(*)<2;
Example
Display department wise highest salary and name
of employee who is having it.
SELECT emp_name FROM employee
WHERE Salary In (SELECT Max(Salary)
FROM employee
GROUP BY Dept_name);