3. Lesson 1: Sorting Data
•
Using the ORDER BY Clause
•
ORDER BY Clause Syntax
•
ORDER BY Clause Examples
•
Demonstration: Sorting Data
4. Using the ORDER BY Clause
•
ORDER BY sorts rows in results for presentation
purposes
•
No guaranteed order of rows without ORDER BY
•
Use of ORDER BY guarantees the sort order of the result
•
Last clause to be logically processed
•
Sorts all NULLs together
•
ORDER BY can refer to:
•
Columns by name, alias or ordinal position (not recommended)
•
Columns not part of SELECT list
•
Unless DISTINCT specified
•
Declare sort order with ASC or DESC
5. ORDER BY Clause Syntax
• Writing ORDER BY using column names:
• Writing ORDER BY using column aliases:
• Specifying sort order in the ORDER BY clause:
SELECT <select list>
FROM <table source>
ORDER BY <column1_name>, <column2_name>;
SELECT <column> AS <alias>
FROM <table source>
ORDER BY <alias>;
SELECT <column> AS <alias>
FROM <table source>
ORDER BY <column_name|alias> ASC|DESC;
6. ORDER BY Clause Examples
• ORDER BY with column names:
• ORDER BY with column alias:
• ORDER BY with descending order:
SELECT orderid, custid, orderdate
FROM Sales.Orders
ORDER BY orderdate;
SELECT orderid, custid, YEAR(orderdate) AS
orderyear
FROM Sales.Orders
ORDER BY orderyear;
SELECT orderid, custid, orderdate
FROM Sales.Orders
ORDER BY orderdate DESC;
8. Lesson 2: Filtering Data with Predicates
•
Filtering Data in the WHERE Clause with Predicates
•
WHERE Clause Syntax
•
Demonstration: Filtering Data with Predicates
9. Filtering Data in the WHERE Clause with
Predicates
• WHERE clauses use predicates
• Must be expressed as logical conditions
• Only rows for which predicate evaluates to TRUE are
accepted
• Values of FALSE or UNKNOWN filtered out
• WHERE clause follows FROM, precedes other clauses
• Can’t see aliases declared in SELECT clause
• Can be optimized by SQL Server to use indexes
• Data filtered server-side
• Can reduce network traffic and client memory usage
10. WHERE Clause Syntax
• Filter rows for customers from Spain
• Filter rows for orders after July 1, 2007
• Filter orders within a range of dates
SELECT contactname, country
FROM Sales.Customers
WHERE country = N'Spain';
SELECT orderid, orderdate
FROM Sales.Orders
WHERE orderdate > '20070101';
SELECT orderid, custid, orderdate
FROM Sales.Orders
WHERE orderdate >= '20070101' AND orderdate < '20080101';
11. Demonstration: Filtering Data with
Predicates
In this demonstration, you will see how to:
•
Filter data in a WHERE clause
12. Lesson 3: Filtering Data with TOP and
OFFSET-FETCH
•
Filtering in the SELECT Clause Using the TOP Option
•
Filtering in the ORDER BY Clause Using OFFSET-
FETCH
•
OFFSET-FETCH Syntax
•
Demonstration: Filtering Data with TOP and OFFSET-
FETCH
13. Filtering in the SELECT Clause Using the
TOP Option
• TOP allows you to limit the number or percentage of rows
returned by a query
• Works with ORDER BY clause to limit rows by sort order
• If ORDER BY list is not unique, results are not deterministic (no
single correct result set)
• Modify ORDER BY list to ensure uniqueness, or use TOP WITH
TIES
• Added to SELECT clause:
• SELECT TOP (N) | TOP (N) Percent
• With percent, number of rows rounded up
• SELECT TOP (N) WITH TIES
• Retrieve duplicates where applicable (nondeterministic)
• TOP is proprietary to Microsoft SQL Server
14. Filtering in the ORDER BY Clause Using
OFFSET-FETCH
OFFSET-FETCH is an extension to the ORDER BY clause:
• Allows filtering a requested range of rows
• Dependent on ORDER BY clause
• Provides a mechanism for paging through results
• Specify number of rows to skip, number of rows to retrieve:
• New option in SQL Server 2012
• Based on draft SQL:2011 standard
• Provides more compatibility than TOP
ORDER BY <order_by_list>
OFFSET <offset_value> ROW(S)
FETCH FIRST|NEXT <fetch_value> ROW(S) ONLY
15. OFFSET-FETCH Syntax
• OFFSET value must be supplied
• May be zero if no skipping is required
• The optional FETCH clause allows all rows following
the OFFSET value to be returned
• Natural Language approach to code:
• ROW and ROWS interchangeable
• FIRST and NEXT interchangeable
• OFFSET value and FETCH value may be constants or
expressions, including variables and parameters
OFFSET <offset_value> ROW|ROWS
FETCH FIRST|NEXT <fetch_value> ROW|ROWS [ONLY]
16. Demonstration: Filtering Data with TOP
and OFFSET-FETCH
In this demonstration, you will see how to:
•
Filter data using TOP and OFFSET-FETCH
17. Lesson 4: Working with Unknown Values
•
Three-Valued Logic
•
Handling NULL in Queries
•
Demonstration: Working with NULL
18. Three-Valued Logic
• SQL Server uses NULLs to mark missing values
• NULL can be "missing but applicable" or "missing but
inapplicable"
• Customer middle name: Not supplied, or doesn’t have one?
• With no missing values, predicate outputs are TRUE or FALSE only
( 5 >2, 1=1)
• With missing values, outputs can be TRUE, FALSE or UNKNOWN
(NULL > 99, NULL = NULL)
• Predicates return UNKNOWN when comparing missing value to
another value, including another missing value
19. Handling NULL in Queries
• Different components of SQL Server handle NULL differently
• Query filters (ON, WHERE, HAVING) filter out UNKNOWNs
• CHECK constraints accept UNKNOWNS
• ORDER BY, DISTINCT treat NULLs as equals
• Testing for NULL
• Use IS NULL or IS NOT NULL rather than = NULL or <> NULL
SELECT custid, city, region, country
FROM Sales.Customers
WHERE region IS NOT NULL;
Question
Describe why, if you declare an alias for a column in the SELECT clause, you cannot use that alias in the WHERE clause, but you can use it in the ORDER BY clause.
Answer
This is because of the order in which clauses of a SELECT query are process. The WHERE clause is processed before the SELECT column list, so column aliases are not yet processed. The ORDER BY clause is processed last, so column aliases are available and can be used without errors.
ORDER BY returns a cursor, not a set. This is important for understanding why table expressions and set operations will not work with cursors. See later modules for more information on table expressions.
Remind students that, without an ORDER BY, the lab exercises may return results in different order from the supplied lab answers. If they want to check results, they can add an ORDER BY clause, both to their solution and the provided one. This will affect all labs!
ORDER BY sorts all NULLs together. See the next lesson for more information on NULL.
Use of ordinal position (for example, ORDER by 1,2) is not recommended as, if the SELECT clause changes the position of columns, the ORDER BY clause is not automatically updated to refer to new positions. This may lead to errors in client applications.
ASC is the default sort.
Note: ORDER BY may also include a COLLATE clause, which helps sort by a specific collation, not the collation of the column in the table. Collations will be discussed further in Module 6 of this course.
Preparation Steps
Start the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines.
Demonstration Steps
Sort Data Using the ORDER BY Clause
Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.
Run D:\Demofiles\Mod05\Setup.cmd as an administrator.
Start SQL Server Management Studio and connect to the MIA-SQL database engine instance using Windows authentication.
Open the Demo.ssmssln solution in the D:\Demofiles\Mod05\Demo folder.
If the Solution Explorer pane is not visible, on the View menu, click Solution Explorer.
Open the 11 – Demonstration A.sql script file.
Follow the instructions contained within the comments of the script file.
Keep SQL Server Management Studio open for the next demonstration.
Question
You have a table named Employees that includes a column named StartDate. You want to find who started in any year other than 2014. What query would you use?
Answer
Multiple answers are possible. For example:
SELECT FirstName, LastName
FROM Employees
WHERE Employees.StartDate NOT BETWEEN '20140101' AND '20143112';
Remind the students of three-value logic. NULLs will be discussed later in this module.
Preparation Steps
Complete the previous demonstration in this module. Alternatively, start the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd, and run D:\Demofiles\Mod05\Setup.cmd as an administrator.
Demonstration Steps
Filter Data in a WHERE Clause
Ensure that you have completed the previous demonstration in this module. Alternatively, start the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd, and run D:\Demofiles\Mod05\Setup.cmd as an administrator.
If SQL Server Management Studio is not already open, start it and connect to the MIA-SQL database engine instance using Windows authentication, and then open the Demo.ssmssln solution in the D:\Demofiles\Mod05\Demo folder.
In Solution Explorer, open the 21 – Demonstration B.sql script file.
Follow the instructions contained within the comments of the script file.
Keep SQL Server Management Studio open for the next demonstration.
Question
You have a table named Products in your Sales database. You are creating a paged display of products in an application that shows 20 products on each page ordered by name. Which of the following queries would return the third page of products?
( )Option 1: SELECT ProductID, ProductName, ProductNumber
FROM Sales.Products
ORDER BY ProductName ASC
OFFSET 60 ROWS FETCH NEXT 20 ROWS ONLY
( )Option 2: SELECT ProductID, ProductName, ProductNumber
FROM Sales.Products
ORDER BY ProductName ASC
OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY;
( )Option 3: SELECT TOP (20) ProductID, ProductName, ProductNumber
FROM Sales.Products
ORDER BY ProductName ASC
( )Option 4: SELECT TOP (20) WITH TIES ProductID, ProductName, ProductNumber
FROM Sales.Products
ORDER BY ProductName ASC
Answer
(√) Option 2: SELECT ProductID, ProductName, ProductNumber
FROM Sales.Products
ORDER BY ProductName ASC
OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY;
Note that if TOP is used, ORDER BY fills two purposes – first to support the TOP operator in the SELECT clause, then again to determine the output order of rows for display purposes.
If ORDER BY list is not unique, the results are not deterministic, which means there is not just one correct set of rows. SQL Server will return rows as they are accessed. To address this, either add expressions to the ORDER BY list to ensure uniqueness, or use TOP (N) with TIES.
While TOP may be used without ORDER BY (with mixed results), OFFSET/FETCH without an ORDER BY will return an error.
Note: The code example is a partial representation of the OFFSET/FETCH syntax only. More complete syntax and examples are presented on the next slide.
Note that the interchangeability of ROW for ROWs and FIRST for NEXT allows for English language-like code.
In an application that calls these queries in sequence, each query is independent and not related to the other. No state is maintained on the server (unlike a cursor).
In paging scenarios like the ones mentioned above, it is a best practice to use unique ordering, avoiding the chance of the same row appearing in multiple pages. This is an unlikely, though technically possible, outcome.
Unlike those found in any previous modules, examples of OFFSET/FETCH must be executed by SQL Server 2012 or later. OFFSET/FETCH was not supported in SQL Server 2008 R2 or earlier.
Preparation Steps
Complete the previous demonstration in this module. Alternatively, start the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd, and run D:\Demofiles\Mod05\Setup.cmd as an administrator.
Demonstration Steps
Filter Data Using TOP and OFFSET-FETCH
Ensure that you have completed the previous demonstration in this module. Alternatively, start the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd, and run D:\Demofiles\Mod05\Setup.cmd as an administrator.
If SQL Server Management Studio is not already open, start it and connect to the MIA-SQL database engine instance using Windows authentication, and then open the Demo.ssmssln solution in the D:\Demofiles\Mod05\Demo folder.
In Solution Explorer, open the 31 – Demonstration C.sql script file.
Follow the instructions contained within the comments of the script file.
Keep SQL Server Management Studio open for the next demonstration.
Question
You have the following query:
SELECT e.Name, e.Age
FROM HumanResources.Employees AS e
WHERE YEAR(e.Age) < 1990;
Several employees have asked for their age to be removed from the Human Resources database. Will the above query return these employees?
Answer
No
Missing but applicable: License plate number of an employee who owns an automobile.
Missing but inapplicable: License plate number of an employee who is a pedestrian.
Celko’s joke: Hair color of a bald man? (He’s bald).
Predicates should be written to handle not just TRUE or FALSE, but also UNKNOWN.
Preparation Steps
Complete the previous demonstration in this module. Alternatively, start the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd, and run D:\Demofiles\Mod05\Setup.cmd as an administrator.
Demonstration Steps
Test for NULL
Ensure that you have completed the previous demonstration in this module. Alternatively, start the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd, and run D:\Demofiles\Mod05\Setup.cmd as an administrator.
If SQL Server Management Studio is not already open, start it and connect to the MIA-SQL database engine instance using Windows authentication, and then open the Demo.ssmssln solution in the D:\Demofiles\Mod05\Demo folder.
In Solution Explorer, open the 41 – Demonstration D.sql script file.
Follow the instructions contained within the comments of the script file.
Close SQL Server Management Studio without saving any files.