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

5 Advanced DML Statements

Uploaded by

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

5 Advanced DML Statements

Uploaded by

hientkls123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Advanced

DML Statements
FSOFT ACADEMY

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use


Lesson Objectives

This is a sample text that you can edit. You


01 Understand about SQL Joins
can change incolor,
font(size, SQLname),
Server
or apply
any desired formatting.

02 Understand
Recognize howsubqueries in SQL
to use built-in Server
functions to perform
operations on data

03 Understand CTE and ranking functions


03
04 Apply SQL Join, Subqueries, CTE to real projects

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 2


Agenda

1. SQL JOINS

2. Sub-Queries

3. CTE and Ranking Functions

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 3


Section 1

SQL JOINS

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 4


WHAT’S SQL JOINS?
 SQL Joins are used to combine rows from two or more tables based on logical
relationships between the tables.
 Types of Join in SQL:
 Inner Join
 Outer Join
 Cross Join
 Self Join

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 5


INNER JOIN
 The INNER JOIN selects all rows from both tables as long as there is a
match between the columns in both tables.
 Eliminate the rows that do not match with a row from the other table
Syntax
SELECT col_names
FROM Table_A A INNER JOIN Table_B B
ON A.Col1 = B.Col1

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 6


INNER JOIN
 Example:

SELECT c.CustName, o.OrderID


FROM Customer c INNER JOIN [Order] o ON c.CustID = o.CustID
ORDER BY c.CustName;

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 7


OUTER JOIN
 Outer Join: Return all rows from at least one of the tables mentioned in
the FROM clause, as long as those rows meet any WHERE or HAVING
search conditions:
 LEFT OUTER JOIN (or LEFT JOIN)

 RIGHT OUTER JOIN (or RIGHT JOIN)

 FULL OUTER JOIN (or FULL JOIN)

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 8


LEFT OUTER JOIN
 Return all of the records in the left table (table A) regardless if any of
those records has a match in the right table (table B)
 In the results where there is no matching condition, the row contains NULL
values for the right table’s columns.
 Syntax
SELECT col_names
FROM Table_A A LEFT JOIN Table_B B
ON A.Col1 = B.Col1

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 9


LEFT OUTER JOIN
 Example:
SELECT c.CustName, o.OrderID
FROM Customer c LEFT JOIN [Order] o ON c.CustID = o.CustID
ORDER BY c.CustName;

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 10


RIGHT OUTER JOIN
 Return all of the records in the right table (table B) regardless if any of
those records have a match in the left table (table A)
 In the results where there is no matching condition, the row contains NULL values for
the left table’s columns.
 Syntax
SELECT col_names
FROM Table_A A RIGHT JOIN Table_B B
ON A.Col1 = B.Col1

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 11


RIGHT OUTER JOIN
 Example:
SELECT c.CustName, o.OrderID
FROM Customer c RIGHT JOIN [Order] o ON c.CustID = o.CustID
ORDER BY c.CustName;

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 12


FULL OUTER JOIN
 Return all of the records from both tables, joining records from the left
table (table A) that match records from the right table (table B)
 Syntax
SELECT col_names

FROM Table_A A FULL JOIN Table_B B

ON A.Col1 = B.Col1

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 13


FULL OUTER JOIN
 Example:
SELECT c.CustName, o.OrderID
FROM Customer c FULL JOIN [Order] o ON c.CustID = o.CustID
ORDER BY c.CustName;

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 14


CROSS JOIN
 Return records that are multiplication of record number from both the
tables
 No need any condition to join
 Syntax
SELECT col_names
FROM Table_A A CROSS JOIN Table_B B

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 15


CROSS JOIN
 Example:
SELECT c.CustName, o.OrderID
FROM Customer c CROSS JOIN [Order] o

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 16


Self JOIN
 A SELF JOIN is a join of a table to itself. In SELF JOIN, we can use:
 INNER JOIN

 OUTER JOIN

 CROSS JOIN

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 17


Self JOIN
 Example:

SELECT e1.EMP_NAME AS Employee_Name, e2.EMP_NAME AS Manager_Name


FROM Employee e1 LEFT JOIN Employee e2 ON e1.EMP_SUPV = e2.EMP_ID

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 18


LEFT Excluding JOIN
 Return all of the records in the left table (table A) that do not match any
records in the right table (table B)
 Syntax
SELECT col_names
FROM Table_A A LEFT JOIN Table_B B ON A.Col1 = B.Col1
WHERE B.Col1 IS NULL

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 19


RIGHT Excluding JOIN
 Returns records in the right table (table B) that do not match any records
in the left table (table A)
 In the results where there is no matching condition, the row contains NULL values for the right table’s
columns.

 Syntax
SELECT col_names
FROM Table_A A RIGHT JOIN Table_B B ON A.Col1 = B.Col1
WHERE A.Col1 IS NULL

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 20


OUTER JOIN EXCLUDING JOIN
 Return all of the records in the left table (table A) and all of the records in
the right table (table B) that do not match.
 Syntax
SELECT col_names
FROM Table_A A
FULL OUTER JOIN Table_B B ON A.Col1 = B.Col1
WHERE A.Col1 IS NULL OR B.Col1 IS NULL

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 21


Joining Three or More Tables
 Since FROM clauses can contain multiple join specifications, this allows
many tables to be joined for a single query.
 Syntax
SELECT col_names
FROM Table_A A JOIN Table_B B
ON A.Col1 = B.Col1 LEFT JOIN Table_C C
ON B.Col2 = C.Col2
….

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 22


Section 2

SUBQUERY

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 23


What is a subquery?
 A sub-query, also called an inner query, is a SQL query nested inside a
larger query.
 The subquery can be nested inside a SELECT, INSERT, UPDATE, or
DELETE statement or inside another subquery.
 You can use the comparison operators, such as >, <, or =. The comparison
operator can also be a multiple-row operator, such as IN, ANY, or ALL.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 24


What is a subquery?
 Syntax (example: subquery within the Where) :

 Exam:
SELECT SUM (Sales) AS Sale_Sum FROM Store_Information
WHERE Store_Name IN
(SELECT Store_Name FROM Geography
WHERE Region_Name = 'West');

Sale_Sum
2050

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 25


What is a subquery? (3/3)
 How to work?:
 Inner query is independent of outer query.

 Inner query is executed first and the results are stored.

 Outer query then runs on the stored results.

 Note about specific type: Correlated subqueries (be mentioned in the next
slides)

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 26


Subquery Types
 Single row subquery
 Multiple row subquery
 Multiple column subquery
 Correlated subquery
 Nested subquery

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 27


Single row subquery
 A single row subquery returns zero or one row to the outer SQL statement.
You can place a subquery in a WHERE clause, a HAVING clause, or a
FROM clause of a SELECT statement.
 Exam: Single Row subqueries in WHERE clause
SELECT agent_name, agent_code, phone_no
FROM agents
WHERE agent_code = (SELECT agent_code FROM agents WHERE agent_name = 'Alex')

agents table

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 28


Multiple row subquery
 Multiple row subquery returns one or more rows to the outer SQL statement. You may use
the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple
rows.
 Ex: Multiple row Subquery in a WHERE clause

SELECT ord_num, ord_amount, ord_date, cust_code, agent_code


FROM orders
WHERE agent_code IN (SELECT agent_code FROM agents WHERE working_area='Bangalore')

orders table

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 29


Multiple column subquery
 You can write subqueries that return multiple columns.
 Ex: Multiple column Subquery in a FROM clause
SELECT ord_num, agent_code, ord_date, ord_amount
FROM orders o1
WHERE EXISTS(
SELECT agent_code, ord_amount
FROM orders o2
WHERE o1.agent_code = o2.agent_code AND o1.ord_amount = o2.ord_amount)
ORDER BY ord_amount ASC

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 30


Correlated subquery
 Reference one or more columns in the outer SQL statement. The subquery is
known as a correlated subquery because the subquery is related to the outer SQL
statement.
 Ex: Correlated Subquery in a FROM clause

SELECT * FROM orders o


WHERE agent_code IN ( SELECT agent_code FROM agents a
WHERE o.ship_city = a.working_area)

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 31


Nested subquery
 A subquery can be nested inside other subqueries.
 Ex: Nested Subquery in a WHERE clause
SELECT *
FROM orders
WHERE ship_city IN (SELECT DISTINCT working_area FROM agents WHERE agent_code
IN
(SELECT agent_code FROM agents WHERE commission >= 0.14))

 Result:

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 32


Common caseS use subquery
 We focus on some typical usecases for Subquery:
 Subqueries with Aliases: Many statements in which the subquery and the outer query
refer to the same table

 Subqueries with IN / NOT IN: The result of a subquery introduced with IN (or with NOT
IN) is a list of zero or more values. After the subquery returns results, the outer query
makes use of them

 Subqueries with EXISTS / NOT EXISTS: The subquery functions as an existence test.

 Subqueries in UPDATE, DELETE, INSERT, SELECT

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 33


Rules that subqueries must follow
 You must enclose a subquery in parenthesis.
 A subquery must include a SELECT clause and a FROM clause.
 Subqueries that return more than one row can only be used with multiple
value operators, such as the IN operator.
 A subquery can include optional WHERE, GROUP BY, and HAVING
clauses.
 A subquery cannot include COMPUTE or FOR BROWSE clauses.
 You can include an ORDER BY clause only when a TOP clause is
included.
 You can nest subqueries up to 32 levels.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 34


Section 3

COMMON TABLE EXPRESSIONS

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 35


Common Table Expressions
 A CTE can be thought of as a temporary result set that is defined within the
execution scope of a single SELECT, INSERT, UPDATE, DELETE. It can be used:
 This is used to store result of a complex sub query for further use.(As a temporary table)
 Create a recursive query.
 Syntax:
;WITH CTE_Name [ col_names]
AS
(
CTE_query_definition
)

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 36


Common Table Expressions
 This is used to store result of a complex sub query for further use.(As a
temporary table)
 Subquery :
SELECT a.agent_name, a.working_area, COUNT(o.agent_code) AS AMOUNT_AGENT
FROM dbo.agents a INNER JOIN dbo.orders o ON A.agent_code = O.agent_code
WHERE A.working_area = 'Bungnlme'
GROUP BY a.agent_name, a.working_area

 Replace by CTE:
; WITH cte_Agents(agent_name, working_area, amount_of_agent)
AS
(
SELECT a.agent_name, a.working_area, COUNT(o.agent_code) AS AMOUNT_AGENT
FROM dbo.agents a INNER JOIN dbo.orders o ON A.agent_code = O.agent_code
GROUP BY a.agent_name, a.working_area
)
SELECT * FROM cte_Agents cte
WHERE cte.working_area = 'Bungnlme'

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 37


Common Table Expressions
 Create a recurszive query.
Category
Id
Name
Description
ParentID

 Ex:

Proplem: Select the Level of each element ??


09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 38
Common Table Expressions
 Solution for this example: Result:

;WITH temp(id, name, aLevel)


AS
(
SELECT id, name, 0 AS aLevel
FROM Category WHERE parent_id is null
UNION All
SELECT b.id, b.name, a.alevel + 1
FROM temp AS a, Category AS b
WHERE a.id = b.parent_id
)
SELECT * FROM temp

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 39


Common Table Expressions
 Recursive Queries Using Common Table Expressions
 Syntax:
WITH cte_name ( col_names)
AS
(
-- Anchor member is defined.
CTE_query_definition
UNION ALL
-- Recursive member is defined referencing cte_name.
CTE_query_definition
)
-- Statement using the CTE
SELECT * FROM cte_name

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 40


Session 4

RANKING FUNCTIONS

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 41


Ranking functions
 Ranking functions: Ranking functions provides the ability to rank each
row of data.
RANK NTILE

DENSE_RANK ROW_NUMBER

 Four kinds of Ranking functions:


ROW_NUMBER
RANK_DENSE
NTILE
RANK

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 42


Ranking functions
 Let's take following sample table and data to know about RANK, RANK_DENSE, NTILE
and ROW_NUMBER with examples:
CREATE TABLE ExamResult(FullName varchar(50), Subject varchar(20), Marks int)

INSERT INTO ExamResult VALUES('Adam','Maths',70)


INSERT INTO ExamResult VALUES ('Adam','Science',80)
INSERT INTO ExamResult VALUES ('Adam','Social',60)

INSERT INTO ExamResult VALUES('Rak','Maths',60)


INSERT INTO ExamResult VALUES ('Rak','Science',50)
INSERT INTO ExamResult VALUES ('Rak','Social',70)

INSERT INTO ExamResult VALUES('Sam','Maths',90)


INSERT INTO ExamResult VALUES ('Sam','Science',90)
INSERT INTO ExamResult VALUES ('Sam','Social',80)

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 43


Ranking functions
 Row_Number: Returns the sequential number of a row within a partition of
a result set
 Example:
SELECT FullName, Subject, Marks, ROW_NUMBER() OVER(ORDER BY FullName) RowNumber
FROM ExamResult
ORDER BY FullName, Subject

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 44


Ranking functions
 Rank: Returns the rank of each row within the partition of a result set
 Example:
SELECT FullName, Subject, Marks, RANK() OVER(PARTITION BY
FullName ORDER BY Marks DESC) Rank
FROM ExamResult
ORDER BY FullName, Subject

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 45


Ranking functions
 Dense_Rank: Returns the rank of rows within the partition of a result set, without
any gaps in the ranking
 Example:
SELECT FullName, Subject, Marks, DENSE_RANK()
OVER (PARTITION BY FullName ORDER BY Marks DESC) Rank
FROM ExamResult
ORDER BY FullName

Dense_Rank
Rank

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 46


Ranking functions
 Ntitle: Distributes the rows in an ordered partition into a specified number of
groups
 Example:
SELECT FullName, Subject, Marks,
NTILE(2) OVER (ORDER BY Marks DESC)Quartile
FROM ExamResult

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 47


Summary
SQL JOINs
 Inner Join
 Outer Join
 Self Join
 Cross Join
Sub-Query
CTE and RANKING Functions

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 48


References
 https://learn.microsoft.com/en-us/sql/relational-databases/performance/joins?view=sql-server-ver16/
 https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/
 https://learnsql.com/blog/what-is-common-table-expression/

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 49


THANK YOU!

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use

You might also like