01-Relational databases advanced queries
01-Relational databases advanced queries
QUERY REVIEW
Lê Hồng Hải
UET-VNUH
Relational DB
2
Relational DB
The data in
Relational DB is
stored in objects
called tables
3
Keys
4
Sample Database
https://www.mysqltutorial.org/mysql-sample-
database.aspx
5
Sample Database
8
SQL (Structured Query Language)
SQL ~ Relational DB
9
Some SQL Operations
Query
◼ SELECT
Sorting data
◼ ORDER BY
Filter data
◼ WHERE, AND, OR, IN, BETWEEN, LIKE, LIMIT,
IS NULL
Join Tables
◼ Joins: INNER JOIN, LEFT JOIN, RIGHT JOIN,
Self-join
10 10
Sort values in multiple columns
11
Sort a result set by an expression
12
WHERE clause with AND operator
13
MySQL WHERE clause with the IN operator example
14
WHERE with the LIKEoperator example
15
WHERE clause with the IS NULL operator
16
MySQL supports the following types of joins:
1. Inner join
2. Left join
3. Right join
4. Cross join
17
INNER JOIN
18
INNER JOIN:
Product Purchase
name category prodName store
19 19
LEFT JOIN
20
LEFT OUTER JOIN:
Product Purchase
name category prodName store
21 21
Hands-on
22
SELFT JOIN
23
SELFT JOIN
24
SELF JOIN example
25
GROUP BY
26
GROUP BY syntax
SELECT
c1, c2,..., cn, aggregate_function(ci)
FROM
table
WHERE
where_conditions
GROUP BY c1 , c2,...,cn;
27
Aggregate function
28
SUM function
29 29
GROUP BY evaluation
30
Hands-on
31
Hands-on
32
ROLLUP
33
ROLLUP
SELECT
productLine,
orderYear,
SUM(orderValue) totalOrderValue
FROM
sales
GROUP BY
productline,
orderYear
WITH ROLLUP;
34
Date functions
Allow you to
manipulate date
and time data
effectively
35
Hands-on
36
MySQL Window Functions
37
Window Function
SELECT
fiscal_year,
sales_employee,
sale,
SUM(sale) OVER (PARTITION BY fiscal_year)
total_sales
FROM
sales;
38
Subquery
39
Subquery in WHERE clause
40
Subquery example
SELECT
customerNumber,
checkNumber,
amount
FROM
payments
WHERE
amount = (SELECT MAX(amount) FROM payments);
41
Subquery example
SELECT
customerName
FROM
customers
WHERE
customerNumber NOT IN (SELECT DISTINCT
customerNumber
FROM orders)
42
Subquery in FROM clause
43
Correlated subquery
44
Correlated subquery example
Select products whose buy prices are greater than the average
buy price of all products in each product line
SELECT
productname,
buyprice
FROM
products p1
WHERE
buyprice > (SELECT
AVG(buyprice)
FROM
products
WHERE
productline = p1.productline)
45
Question
46
Full-Text Search
47
Full-Text Search
48
Full-Text Search
SELECT
productName,
productLine
FROM products
WHERE
MATCH(productName)
AGAINST('1932,Ford’)
49
THANKS YOU