0% found this document useful (0 votes)
19 views28 pages

5 - Advanced Select Queries

Uploaded by

rjmodi942
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views28 pages

5 - Advanced Select Queries

Uploaded by

rjmodi942
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Advanced Select

Queries
Advanced Select Queries(Ordering a
Listing)
- The ORDER BY clause in SQL is used to sort the rows
in the result set based on one or more columns or
expressions.
- Without it, the order of rows returned by a query is
undefined and may vary each time
Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY columnA [ASC|DESC], columnB [ASC|
DESC], ...;
ASC (ascending) order is default, DESC (descending)
Advanced Select Queries(Ordering a
Listing)
SELECT * FROM employees Departm
Emp_id Name Salary
ent
ORDER BY salary ASC;
50,00
Emp_i 1 Alka HR
Name Department Salary 0
d Balra 60,00
1 Eva HR 45,000 2 IT
m 0
2 Aika HR 50,000 Charlo 55,00
Charlo 3 Finance
3 Finance 55,000 Emp_i s Departme 0
s Name Salary
d nt 70,00
Balra 4 Dev IT
4 IT 60,000 1 Charlos Finance 0
55,000
m 2 Alka HR 45,00
50,000
5 Eva HR
5 SELECT
Dev *FROM
IT 70,000
Employees 3 Eva HR 0
45,000
ORDER BY Department 4 Dev IT 70,000
ASC, 5 Balram IT 65,000
Advanced Select Queries(Listing
Unique Values)
- listing unique values in DBMS use the DISTINCT
keyword
- SQL’s DISTINCT clause produces a list of only those values
that are different from one another.
Syntax: SELECT DISTINCT <column_name> FROM
<table_name>;
FNAME
Employee: DNO
Jeny 5
Example: SELECT DISTINCT DNO FROM
May 1 Employee
Alice 5
Ben 3
Sam 1 Result : 1,3,5
Aggregate functions
In DBMS (SQL), aggregate functions are used to perform
calculations on a set of rows and return a single value.
FNAM LNAM SALAR
EMPID DNO
Aggregate functions E E
101 John Smith 5
Y
40000
1) COUNT(): Johnso
102 Mary 5 50000
SELECT COUNT(*) FROM n
Employee; 103 Alice Brown 1 55000
Result : 6 104 Bob Davis 1 70000
105 Carol Miller 3 55000
4) SUM():
106 David Wilson3 30000
2) MIN(): SELECT SUM(SALARY) AS
SELECT MIN(SALARY) AS total_salary FROM Employee;
lowest_salary FROM Employee; Result: 3,00,000
Result: 30000
5)AVG():
3) MAX():
SELECT AVG(SALARY) AS
SELECT MAX(SALARY) AS
avg_salary FROM Employee;
highest_salary FROM Employee;
Result : 50000
Grouping Data (GROUP BY and HAVING
Clause)
GROUP BY:
- Used to group rows based on one or more columns.
- Works together with aggregate functions like SUM(),
AVG(), COUNT(), MAX(), MIN().
SELECT DeptNo, AVG(Salary) AS
DeptN
EmpID Name
o
Salary avg_salary
1 John 10 40000 FROM Employee
2 Mary 10 50000 GROUP BY DeptNo; avg_salary
DeptNo
3 Alice 20 45000 Result: 10 45000
4 Bob 20 60000
20 52500
5 Carol 30 55000
30 40000
6 David 30 30000
40 70000
7 Eve 30 35000
Grouping Data (GROUP BY and HAVING
Clause)
Having:
- Similar to WHERE but applies after grouping.
- Used to filter groups (not individual rows).
EmpI DeptN SELECT DeptNo, AVG(Salary) AS
Name Salary
D o avg_salary
4000 FROM Employee
1 John 10
0 GROUP BY DeptNo
5000 HAVING AVG(Salary) > 45000;
2 Mary 10
0 Result:
4500 DeptNo avg_salary
3 Alice 20 20 52500
0
40 70000
6000
4 Bob 20
Advanced SQL(Relational Set Operators)
- Relational set operators are used to combine the
results of two or more queries.
- “UNION, INTERSECT, and EXCEPT (MINUS) work
only when the tables are union-compatible means
both queries must return the same number of
columns, and the columns in the same position
must have the similar data types.”
UNION :
- Combines results of two queries.
- Removes duplicates by default.
Syntax : query UNION query
Advanced SQL(Relational Set Operators) -
Union
Students1 SELECT Name FROM Students1
ID Name
UNION
1 Riya
2 Arjun SELECT NAME FROM Students2;
3 Meera Result : Riya, Arjun, Meera, Neha

Students2 SELECT Name FROM Students1


ID Name UNION ALL
1 Arjun SELECT NAME FROM Students2;;
2 Neha Result: Riya, Arjun, Meera, Arjun,Neha
Advanced SQL(Relational Set Operators) -
INTERSECT
- Returns only the common rows between two queries.
- It is not supported in MySQL directly, but can be simulated
with INNER JOIN or IN
- INNER JOIN gives the same result as INTERSECT
EmpID EmpName DeptID SELECT E.EmpID, E.EmpName, D.DeptName
1 Riya 101
2 Arjun 102 FROM Employees E
3 Meera 103 INNER JOIN Departments D
4 Neha 104
ON E.DeptID = D.DeptID;
Result :
DeptID DeptName EmpID EmpName DeptName
101 HR 1 Riya HR
102 IT 2 Arjun IT
103 Finance 3 Meera Finance
Advanced SQL(Relational Set Operators) -
MINUS/EXCEPT
- Returns rows from the first query that are not in the
second.
Example:
SELECT EmpName FROM Employee WHERE DeptID = 101
EXCEPT
SELECT EmpNameFROM Employee WHERE DeptID = 102;
SQL JOIN Operators
The relational join operation merges rows from two tables
and returns the rows with one of the following conditions:
• Have common values in common columns (natural join).
• Meet a given join condition (equality or inequality).
• Have common values in common columns or have no
matching values (outer join).
1) CROSS JOIN:
- CROSS JOIN produces a Cartesian product of two tables.
- Every row of the first table is paired with every row of the
second table.
- Number of rows in result = (Rows in Table A) × (Rows in Table
B
SQL JOIN Operators - CROSS
JOIN(Cartesian Product)
Departments
Employees
dept_id dept_name
emp_na 10 HR
emp_id dept_id
me 20 IT
1 Alice 10 30 Marketing
2 Bob 20
Example: emp_i
emp_name dept_name
SELECT e.emp_id, d
e.emp_name, 1 Alice HR
d.dept_name 1 Alice IT
1 Alice Marketing
FROM Employees e 2 Bob HR
CROSS JOIN 2 Bob IT
Departments d; 2 departments,
Bob Marketing
- Every employee is matched with all regardless of actual
SQL JOIN Operators - INNER JOIN
- INNER JOIN = Matching rows only
- Use when you want only the records that exist in
both tables
- If there’s no match, the row is not included in the result
Employees
emp_na Departments
emp_id dept_id
me dept_na
dept_id
1 Alice 10 me
2 Bob 20 10 HR
3 Charlie 30 20 IT
4
SELECT David e.emp_name,
e.emp_id, 40 Marketin
30
emp_id emp_name dept_name
d.dept_name g
1 Alice HR
FROM Employees e 2 Bob IT
INNER JOIN Departments d 3 Charlie Marketing
SQL JOIN Operators - NATURAL JOIN
- A NATURAL JOIN automatically joins tables based on
columns with the same name and compatible data types.
- No need to explicitly mention the join condition.
- multiple same-name columns exist do not perform
NATURAL JOIN
Employees Departments
emp_na dept_na
emp_id dept_id dept_id
me me
1 Alice 10 10 HR
2 Bob 20 20 IT
3 Charlie 30 Marketin
4 David 40 30
emp_id emp_name dept_name
g
SELECT emp_id, emp_name, dept_name 1 Alice HR
FROM Employees 2 Bob IT
NATURAL JOIN Departments; 3 Charlie Marketing
SQL JOIN Operators - JOIN USING
- Works like NATURAL JOIN, but you explicitly mention
the common column(s)
Employees Departments
emp_na dept_na
emp_id dept_id dept_id
me me
1 Alice 10 10 HR
2 Bob 20 20 IT
3 Charlie 30 Marketin
4 David 40 30
g
SELECT emp_id, emp_name, emp_id emp_name dept_name
1 Alice HR
dept_name
2 Bob IT
FROM Employees 3 Charlie Marketing
JOIN Departments USING
SQL JOIN Operators - JOIN … ON
- The ON clause is used to explicitly specify the join
condition.
- You have full control: you can join on equal columns,
different names, multiple conditions, or even inequalities.
emp_i emp_na dept_i SELECT e.emp_id, e.emp_name,
city
d me d d.dept_name,
1 Alice 10 Delhi e.city AS emp_city, d.city AS
2 Bob 20 Mumbai dept_city
3 Charlie 30 Delhi FROM Employees e
dept_i dept_na JOIN Departments d
city
d me emp_na dept_na emp_cit dept_cit
10 HR Delhi emp_idON e.dept_id = d.dept_id;
me me y y
20 IT Pune
1 Alice HR Delhi Delhi
30 Marketing Delhi
2 Bob IT Mumbai Pune
- Unlike USING or NATURAL JOIN, 3
the ON clause Marketin
does not hide or merge same-name columns.
Charlie Delhi Delhi
SQL JOIN Operators- OUTER JOIN

- An INNER JOIN only shows rows that match in both


tables.
- An OUTER JOIN shows all rows from one table even if
there’s no match in the other table.
- Types of OUTER JOINs:
• LEFT OUTER JOIN (LEFT JOIN)
• RIGHT OUTER JOIN (RIGHT JOIN)
• FULL OUTER JOIN (FULL JOIN)
SQL JOIN Operators- OUTER JOIN
LEFT OUTER JOIN (LEFT JOIN) :- keeps all rows from
the left table
Employees
emp_id emp_name dept_id SELECT emp_id, emp_name,
1 Alice 10 dept_name
2 Bob 20
3 Charlie 30 FROM Employees
4 David NULL
LEFT JOIN Departments
ON Employees.dept_id =
Departments Departments.dept_id;
emp_nam dept_nam
dept_id dept_name emp_id
10 HR
e e
20 Finance 1 Alice HR
40 IT 2 Bob Finance
3 Charlie NULL
4 David NULL
SQL JOIN Operators- OUTER JOIN
RIGHT OUTER JOIN (RIGHT JOIN):- keeps all rows from
the right table.
Employees
emp_id emp_name dept_id SELECT emp_id, emp_name,
1 Alice 10 dept_name
2 Bob 20
3 Charlie 30 FROM Employees
4 David NULL
RIGHT JOIN Departments
ON Employees.dept_id =
Departments Departments.dept_id;
dept_id dept_name emp_id emp_name dept_name
10 HR 1 Alice HR
20 Finance
40 IT 2 Bob Finance
NULL NULL IT
SQL JOIN Operators- OUTER JOIN
FULL OUTER JOIN (FULL JOIN):-keeps all rows from
both tables.
Employees SELECT emp_id, emp_name,
emp_id emp_name dept_id
1 Alice 10 dept_name
2 Bob 20
3 Charlie 30 FROM Employees
4 David NULL FULL OUTER JOIN Departments
ON Employees.dept_id =
Departments emp_id emp_name dept_name
Departments.dept_id;
dept_id dept_name 1 Alice HR
10 HR 2 Bob Finance
20 Finance
40 IT 3 Charlie NULL
4 David NULL
NULL NULL IT
Key points
• NATURAL JOIN = joins on all same-name columns.
• JOIN USING (col) = joins only on the specified column(s).
• INNER JOIN = Only matching rows.
• LEFT JOIN = All from left + matches.
• RIGHT JOIN = All from right + matches.
• FULL JOIN = All rows from both.
Date/Time Functions
1. CURRENT_DATE:
SELECT CURRENT_DATE;
2. CURRENT_TIME
SELECT CURRENT_TIME;
3. CURRENT_TIMESTAMP / NOW()
SELECT CURRENT_TIMESTAMP;
SELECT NOW();
4. EXTRACT():
SELECT EXTRACT(YEAR FROM CURRENT_DATE) AS year_part;
SELECT EXTRACT(HOUR FROM CURRENT_TIME) AS hour_part;
Date/Time Functions
5. DATE_ADD()
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 10 DAY);
6. DATE_SUB()
SELECT DATE_SUB(CURRENT_DATE, INTERVAL 5 DAY);
7. DATEDIFF()
SELECT DATEDIFF('2025-12-31', '2025-08-17');
8. LAST_DAY()
SELECT LAST_DAY('2025-08-17') AS last_day;
9.DATE_FORMAT(date, format)
Format Specifiers
Specifier Meaning Example Result
%Y Year (4 digits) 2025
%y Year (2 digits) 25
%M Month name August
%m Month (2 digits) 08
%b Abbreviated month Aug
%d Day (2 digits) 18
%H Hour (00–23) 15
%i Minutes 45
%s Seconds 09

SELECT DATE_FORMAT(NOW(), '%d-%M-%Y') AS


formatted_date;
Numeric Functions
1. ABS(x): absolute (positive) value of a number
SELECT ABS(-25); o/p : 25
2. CEIL(x) / CEILING(x) : upwards to the nearest integer
SELECT CEIL(4.2) ; o/p: 5

3. FLOOR(x):downwards to the nearest integer.


SELECT FLOOR(4.6); o/p: 4

4. ROUND(x, d): rounds a number to ‘d’ decimal places (default


= 0).
SELECT ROUND(243.358, 2); o/p: 243.36
String Functions
1. CONCAT(str1, str2, …)
SELECT CONCAT('Hello', ' ', 'FYMCA') AS result; o/p: Hello FYMCA
SELECT CONCAT(emp_name, ' works in department ', dept_id) AS info FRO
Employees;
2. LENGTH(str):
SELECT LENGTH('FYMCA') AS len; o/p:5
3. UPPER(str) / UCASE(str):
SELECT UPPER('fymca'); o/p: FYMCA
4. LOWER(str) / LCASE(str):
SELECT LOWER('FYMCA'); o/p: fymca
5. SUBSTRING(str, start, length)
SELECT SUBSTRING('Database', 5, 3); O/P: bas

You might also like