2021 02 03 Class Presentation - SQL FROM

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Querying data with T-SQL

WELCOME TO OUR SESSION ON


QUERYING DATA WITH T-SQL

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


REFERENCE TO THE MICROSOFT T-SQL QUERIES SITE
Microsoft T-SQL
https://docs.microsoft.com/en-us/s
ql/t-sql/language-reference?view=s
ql-server-ver15
REFERENCE

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


MainREFERENCE TO EXAMPLES USING SQL KEYWORDS
Heading | Subheading

Examples using SQL keywords on W3Schools


https://www.w3schools.com/sql/default.asp
REFERENCE

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
SQL QUERIES – CLAUSES IN THE SELECT STATEMENT
SELECT [DISTINCT] [TOP] … <select_list>
FROM … JOIN ON
WRITTEN ORDER

APPLY The SQL language was created


in 1970 by IBM. The developers
PIVOT wanted the structure to be
UNPIVOT based on normal English
WHERE … sentence structures e.g.:
GROUP BY …
HAVING … Select the top 5 movies from
ORDER BY … Netflix where the main actor’s
surname contains the text
OFFSET … FETCH … “Bale” or “Cooper”.

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


SQL QUERIES - CLAUSES IN THE SELECT STATEMENT
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
PROCESSING ORDER

        (1-2) APPLY In most programming


        (1-3) PIVOT languages, the code is
processed in the order in which
        (1-4) UNPIVOT it is written.
(2) WHERE … However, in SQL, the first
clause that is processed is the
(3) GROUP BY … FROM clause, whereas the
(4) HAVING … SELECT clause, which is typed
(6) ORDER BY … first, is processed almost last.
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


1. THE FROM CLAUSE
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
        (1-2) APPLY
FROM CLAUSE

        (1-3) PIVOT


        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


1 THE FROM CLAUSE
The FROM clause is used to specify the objects (mostly tables or views) from
which the data should be retrieved.
SELECT customer_name, customer_cell_number
FROM Customers
FROM CLAUSE

In some cases where a Variable


single data item is DECLARE @MyCounter int;
retrieved from variables SET @MyCounter = 0;
or functions, the FROM
clause can be omitted: WHILE (@MyCounter < 26)
BEGIN;
Function SET @MyCounter = @MyCounter + 1;
SELECT GETDATE() END;
2020-07-17
10:36:53.240 SELECT @MyCounter
26

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


PRACTICAL
Visit https://www.wiseowl.co.uk/sql/exercises/standard and do the Simple
Queries exercises.

Store your sql code and a snapshot of the result in a Word document.
FROM CLAUSE

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


1-1 JOIN ON
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
        (1-2) APPLY
        (1-3) PIVOT
1-1 JOIN ON

        (1-4) UNPIVOT


(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


1-1 JOIN ON
When data is retrieved from multiple tables, we can include JOIN
structures in the FROM clause to:
- join (merge) the data from these tables,
- based on the data in columns that we specify using the ON keyword.
1-1 JOIN ON

The columns used to join the tables are normally primary and foreign keys,
but they don’t have to be. They can even be columns with no relationships
between them at all.

Therefor, do not assume that SQL Server will automatically join tables using
their primary and foreign keys. Your query still has to specify the
columns to be used for joining the tables.

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


USING
Main DIFFERENT
Heading COLUMNS TO JOIN TABLES
| Subheading
SELECT Sales.Customer.CustomerID
FROM Sales.Customer
EXAMPLES – JOIN ON

-- 19 820 rows

SELECT Sales.SalesOrderHeader.SalesOrderID
FROM Sales.SalesOrderHeader
-- 31 465 rows

SELECT Sales.Customer.CustomerID
FROM Sales.Customer
JOIN Sales.SalesOrderHeader
ON Sales.Customer.CustomerID = Sales.SalesOrderHeader.CustomerID
-- 31 465 rows

SELECT Sales.Customer.CustomerID
FROM Sales.Customer
JOIN Sales.SalesOrderHeader
ON Sales.Customer.TerritoryID = Sales.SalesOrderHeader.TerritoryID
-- 13 000 000+ rows

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
1-1 JOIN ON
SELECT *
FROM dbo.Customers A
INNER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
1-1 JOIN ON

In a typical query like this, the Customers table is referred to as the


Left table and Orders is referred to as the Right table.

Note that each table has an alias (A and B), which can be used to
refer to the tables in other clauses of the query.

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


CUSTOMERS EXAMPLE DATA

The following examples demonstrate the use of different kinds of


joins.

The Customers and Orders tables on the left will be used as


1-1 JOIN ON

input.

ORDERS Note: Although customer_id is used as FK in the Orders table,


there is no foreign key constrains implemented on
Orders.customer_id.

This is done to accommodate records 101 and 104 in the Orders


table, which has no corresponding customers in the Customers
table (to demonstrate the various kinds of joins).

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
CUSTOMERS INNER JOIN (The INNER keyword is optional)
This is the simplest and most common join. This query will return all of
the records in the left table (table A) that have a matching record in the
right table (table B).

SELECT *
1-1 JOIN ON

FROM dbo.Customers A
JOIN dbo.Orders B
ON A.customer_id = B.customer_id
ORDERS

RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
CUSTOMERS LEFT OUTER JOIN (The OUTER keyword is optional)
This query will return all of the records in the left table (table A) regardless
if any of those records have a match in the right table (table B). It will also
return any matching records from the right table.

SELECT *
1-1 JOIN ON

FROM dbo.Customers A
LEFT JOIN dbo.Orders B
ON A.customer_id = B.customer_id
ORDERS
RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
CUSTOMERS RIGHT OUTER JOIN (The OUTER keyword is optional)
This query will 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). It will also return any matching records from the left table.

SELECT *
FROM dbo.Customers A
1-1 JOIN ON

RIGHT JOIN dbo.Orders B


ON A.customer_id = B.customer_id
ORDERS
RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
CUSTOMERS FULL OUTER JOIN
This Join can be referred to as a FULL OUTER JOIN or a FULL JOIN.
This query will 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).
SELECT *
1-1 JOIN ON

FROM dbo.Customers A
FULL OUTER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
ORDERS
RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
CUSTOMERS LEFT EXCLUDING JOIN
This query will return all of the records in the left table
(table A) that do not match any records in the right
table (table B).
1-1 JOIN ON

SELECT *
FROM dbo.Customers A
LEFT JOIN dbo.Orders B
ORDERS ON A.customer_id = B.customer_id
WHERE B.customer_id IS NULL

RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
CUSTOMERS RIGHT EXCLUDING JOIN
This query will return all of the records in the right table (table B) that
do not match any records in the left table (table A).

SELECT *
FROM dbo.Customers A
1-1 JOIN ON

RIGHT JOIN dbo.Orders B


ON A.customer_id = B.customer_id
ORDERS WHERE A.customer_id IS NULL

RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
CUSTOMERS OUTER EXCLUDING JOIN
This query will 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.
1-1 JOIN ON

SELECT *
FROM dbo.Customers A
ORDERS FULL OUTER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
WHERE A.customer_id IS NULL OR
B.customer_id IS NULL

RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
PRACTICAL
Visit https://www.wiseowl.co.uk/sql/exercises/standard and do the exercises
on Basic joins and More exotic joins.

Store your sql code and a snapshot of the results in a Word document.
1-1 JOIN ON

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


1-2 APPLY
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
        (1-2) APPLY
        (1-3) PIVOT
1-2 APPLY

        (1-4) UNPIVOT


(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


CUSTOMERS 1-2 APPLY
The APPLY operator applies the right table
expression to every row from the left input.
SELECT *
FROM dbo.Customers AS A
CROSS APPLY
1-2 APPLY

( SELECT TOP (2) B.order_id, B.customer_id


FROM dbo.Orders AS B
ORDERS WHERE B.customer_id = A.customer_id
ORDER BY order_id DESC) AS C;

RESULT

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


1-3 PIVOT
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
1-3 PIVOT & 1-4 UNPIVOT

(1) FROM … (1-1) JOIN ON


        (1-2) APPLY
        (1-3) PIVOT
        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


1-3 PIVOT & 1-4 UNPIVOT
You use the PIVOT operator to rotate, or pivot, data from
1-3 PIVOT & 1-4 UNPIVOT

rows to columns, performing aggregations along the way.


UNPIVOT turns columns into rows.

SELECT empid, [2013], [2014], [2015]


FROM ( SELECT empid, YEAR(orderdate) AS orderyear, val
        FROM Sales.OrderValues ) AS D
PIVOT( SUM(val) FOR orderyear IN([2013],[2014],[2015]) ) AS P;

RESULT
empid   2013      2014       2015
------ --------- ---------- ---------
9       9894.52   26310.39   41103.17
3      18223.96  108026.17   76562.75
6      16642.61   43126.38   14144.16
7      15232.16   60471.19   48864.89

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
2 THE WHERE CLAUSE

        (1-2) APPLY


        (1-3) PIVOT
        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE
The ON keyword that was used with the JOIN operations, is used as
primary filter, because it stipulates how tables should be joined and
2 THE WHERE CLAUSE

subsequently which records should primarily be included by the JOIN


operation.

The WHERE clause is now used as a further filtering mechanism - to


filter the retrieved rows on additional predicates that were not part of
the JOIN ON conditions.

Obviously, if you only retrieve records from a single table, the WHERE
clause will be your only change to filter out individual records.

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


CUSTOMERS SELECT *
FROM dbo.Customers A
INNER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
2 THE WHERE CLAUSE

ORDERS

SELECT *
FROM dbo.Customers A
INNER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
WHERE B.amount > 100

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
2 THE WHERE CLAUSE
When multiple operators appear in the same expression, SQL Server
evaluates them based on operator precedence rules. The following list
2 THE WHERE CLAUSE

describes the precedence among operators, from highest to lowest:


1. ( ) (Parentheses)
2. * (Multiplication), / (Division), % (Modulo)
3. + (Positive), – (Negative), + (Addition),
+ (Concatenation), – (Subtraction)
4. =, >, <, >=, <=, <> (Comparison operators)
5. NOT
6. AND
7. BETWEEN, IN, LIKE, OR
8. = (Assignment)

Most of the above operators are well known or self-explanatory. But


Let’s have a further look at BETWEEN, IN and LIKE.

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE
The BETWEEN predicate
You use the BETWEEN predicate to check
whether a value is in a specified range, inclusive
2 THE WHERE CLAUSE

of the two specified delimiters.


ORDERS
SELECT *
FROM dbo.Customers A
INNER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
WHERE B.amount BETWEEN 500 AND 1000

RESULT

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE
The IN predicate
You use the IN predicate to check whether a
value, or scalar expression, is equal to at least
2 THE WHERE CLAUSE

one of the elements in a set.


ORDERS
SELECT *
FROM dbo.Customers A
INNER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
WHERE B.order_id IN(102, 107)

RESULT

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE
CUSTOMERS The LIKE predicate
T-SQL provides a predicate called LIKE that
you can use to check whether a character
2 THE WHERE CLAUSE

string matches a specified pattern.


Following are the wildcards supported in
the patterns.

The % (percent) wildcard
The percent sign represents a string of any
size, including an empty string. For example,
the following query returns customers
where the name starts with M:

SELECT * RESULT
FROM dbo.Customers
WHERE customer_name LIKE N'M%'

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE
CUSTOMERS The LIKE predicate

The _ (underscore) wildcard


2 THE WHERE CLAUSE

An underscore represents a single character.


For example, the following query returns
customers where the second character in
the name is e:

SELECT * RESULT
FROM dbo.Customers
WHERE customer_name LIKE N'_e%'

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE
CUSTOMERS The LIKE predicate

The [list of characters] wildcard


2 THE WHERE CLAUSE

Square brackets with a list of characters (such


as [ABC]) represent a single character that must
be one of the characters specified in the list. For
example, the following query returns customers
where the first character in the name is C, G,
or K:

SELECT * RESULT
FROM dbo.Customers
WHERE customer_name LIKE N'[CGK]%';

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE
CUSTOMERS The LIKE predicate

The [character-character] wildcard


2 THE WHERE CLAUSE

Square brackets with a character range


(such as [A-E]) represent a single character
that must be within the specified range. For
example, the following query returns
employees where the first character in the
last name is a letter in the range A through
E, inclusive.

SELECT * RESULT
FROM dbo.Customers
WHERE customer_name LIKE N'[A-E]%';

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE

Be aware of date formats when including them


in your WHERE clause.
2 THE WHERE CLAUSE

SET LANGUAGE British;


SELECT CAST('02/12/2020' AS DATE);
-- Output 2020-12-02

SET LANGUAGE us_english;


SELECT CAST('02/12/2020' AS DATE);
-- Output 2020-02-12

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


2 THE WHERE CLAUSE

SET LANGUAGE British;


SELECT CAST('20200212' AS DATE);
2 THE WHERE CLAUSE

-- Output 2020-02-12

SET LANGUAGE us_english;


SELECT CAST('20200212' AS DATE);
-- Output 2020-02-12

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


3 THE GROUP BY CLAUSE
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
3 THE GROUP BY CLAUSE

(1) FROM … (1-1) JOIN ON


        (1-2) APPLY
        (1-3) PIVOT
        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


CUSTOMERS You can use the GROUP BY clause to arrange the
rows returned by the previous processes into
3 THE GROUP BY CLAUSE
groups.

SELECT A.customer_id, SUM(B.amount) Elements that do not


FROM dbo.Customers A participate in
INNER JOIN dbo.Orders B the GROUP BY clause
ORDERS ON A.customer_id = B.customer_id are allowed only as
GROUP BY A.customer_id; inputs to an
aggregate function
RESULT such as COUNT, SUM,
AVG, MIN, or MAX.

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
4 THE HAVING CLAUSE
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
4 THE HAVING CLAUSE

        (1-2) APPLY


        (1-3) PIVOT
        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


CUSTOMERS Whereas the WHERE clause is used to filter
individual rows, the HAVING clause is a group filter.
4 THE HAVING CLAUSE

SELECT A.customer_id, SUM(B.amount) Groups with only 1


FROM dbo.Customers A order are excluded.
INNER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
GROUP BY A.customer_id
ORDERS HAVING COUNT(B.customer_id) > 1

RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
5-1 THE SELECT LIST
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
        (1-2) APPLY
5-1 THE SELECT LIST

        (1-3) PIVOT


        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


CUSTOMERS After all the joining, filtering and grouping have been done,
the SELECT LIST stipulates the data that should be included
in the final output (just before the ORDER clause sorts it).
4 THE HAVING CLAUSE
This does not only include table columns, but also computed
data via the use of functions such as COUNT, SUM, AVG,
MIN, and MAX. You may also compile your own functions
and use them in this same way.

SELECT B.customer_id, A.customer_name, Note that you can


ORDERS SUM(B.amount) AS [Total Amount], supply new column
COUNT(B.order_id) AS [Orders] names for the output
FROM dbo.Customers A
by using the AS
INNER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
keyword.
Group by B.customer_id, A.customer_name

RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
5-2 THE SELECT DISTINCT CLAUSE
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
5-2 THE DISTINCT CLAUSE

(1) FROM … (1-1) JOIN ON


        (1-2) APPLY
        (1-3) PIVOT
        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


5-2 THE SELECT DISTINCT CLAUSE CUSTOMERS
SQL provides the means to remove duplicate
values by using the DISTINCT clause.

SELECT DISTINCT B.customer_id


FROM dbo.Orders B
ORDERS
RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
6 THE ORDER BY CLAUSE
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
6 THE ORDER BY CLAUSE

        (1-2) APPLY


        (1-3) PIVOT
        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


6 THE ORDER BY CLAUSE
When your table is newly created, records are
6 THE ORDER BY CLAUSE

normally inserted in sequential order. When you


retrieve these records with a query, they might be
presented in the correct order you wanted.
SELECT *
FROM dbo.Customers
RESULT

But looks can be deceiving…

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


6 THE ORDER BY CLAUSE
If you care about the ordering of your output data,
6 THE ORDER BY CLAUSE

ALWAYS use an ORDER clause to ensure that the rows


are sorted in the correct order.
SELECT * SELECT *
FROM dbo.Customers A FROM dbo.Customers A
ORDER by A.customer_id ORDER by A.customer_name DESC
RESULT RESULT

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


6 THE ORDER BY CLAUSE
You can also sort your data on multiple columns.
6 THE ORDER BY CLAUSE

SELECT *
FROM dbo.Customers A
INNER JOIN dbo.Orders B
ON A.customer_id = B.customer_id
ORDER BY A.customer_name DESC, B.amount ASC

RESULT

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


7 TOP, OFFSET, FETCH
(5) SELECT (5-2) [DISTINCT] (7) [TOP] … (5-1) <select_list>
(1) FROM … (1-1) JOIN ON
7 TOP, OFFSET, FETCH

        (1-2) APPLY


        (1-3) PIVOT
        (1-4) UNPIVOT
(2) WHERE …
(3) GROUP BY …
(4) HAVING …
(6) ORDER BY …
(7) OFFSET … ROWS FETCH …

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za


CUSTOMERS
7 TOP
Get the 2 orders (and their customers)
with the highest values.
SELECT TOP 2 * We sort the rows by
FROM dbo.Customers A amount in DESC order,
7 TOP

ORDERS INNER JOIN dbo.Orders B to ensure the orders


ON A.customer_id = B.customer_id with the largest
ORDER BY B.amount DESC amounts are at the top.

RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
CUSTOMERS
7 OFFSET, FETCH
Perform the same query as in the
previous example, but skip the first 3
7 OFFSET, FETCH

orders and then fetch the next 3.


SELECT * Note that a query that
ORDERS FROM dbo.Customers A uses OFFSET-FETCH must
INNER JOIN dbo.Orders B have an ORDER BY clause.
ON A.customer_id = B.customer_id
ORDER BY B.amount DESC
OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY

RESULT

2 0 2 02 0C2T0U CTTr U
a i nTirnagi nSi nogl u St iool nust i o| nAsl l | RAi gl l hRt si gRhet s eRr ev e
s edr v| ecdt u| t rcat u
i nt irnagi n. ai nc g. z. a c . z a
Thank You!

2020 CTU Training Solutions | All Rights Reserved | ctutraining.ac.za

You might also like