SlideShare a Scribd company logo
1 of 20
Sorting and Filtering Data
Module Overview
•
Sorting Data
•
Filtering Data with Predicates
•
Filtering Data with TOP and OFFSET-FETCH
•
Working with Unknown Values
Lesson 1: Sorting Data
•
Using the ORDER BY Clause
•
ORDER BY Clause Syntax
•
ORDER BY Clause Examples
•
Demonstration: Sorting Data
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
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;
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;
Demonstration: Sorting Data
In this demonstration, you will see how to:
•
Sort data using the ORDER BY clause
Lesson 2: Filtering Data with Predicates
•
Filtering Data in the WHERE Clause with Predicates
•
WHERE Clause Syntax
•
Demonstration: Filtering Data with Predicates
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
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';
Demonstration: Filtering Data with
Predicates
In this demonstration, you will see how to:
•
Filter data in a WHERE clause
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
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
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
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]
Demonstration: Filtering Data with TOP
and OFFSET-FETCH
In this demonstration, you will see how to:
•
Filter data using TOP and OFFSET-FETCH
Lesson 4: Working with Unknown Values
•
Three-Valued Logic
•
Handling NULL in Queries
•
Demonstration: Working with NULL
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
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;
Demonstration: Working with NULL
In this demonstration, you will see how to:
•
Test for NULL

More Related Content

Similar to filterAndSort.pptx

Using SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.pptUsing SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
MohammedJifar1
 
Less07 schema
Less07 schemaLess07 schema
Less07 schema
Imran Ali
 

Similar to filterAndSort.pptx (20)

Sql server 2016 queries
Sql server 2016 queriesSql server 2016 queries
Sql server 2016 queries
 
Excel Tips 101
Excel Tips 101Excel Tips 101
Excel Tips 101
 
Excel tips
Excel tipsExcel tips
Excel tips
 
Tech Jam 01 - Database Querying
Tech Jam 01 - Database QueryingTech Jam 01 - Database Querying
Tech Jam 01 - Database Querying
 
chapter03.ppt
chapter03.pptchapter03.ppt
chapter03.ppt
 
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.pptUsing SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
 
122 sql for-beginners
122 sql for-beginners122 sql for-beginners
122 sql for-beginners
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Excel Tips.pptx
Excel Tips.pptxExcel Tips.pptx
Excel Tips.pptx
 
Querying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptxQuerying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptx
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command Statements
 
Oracle 12c New Features for Developers
Oracle 12c New Features for DevelopersOracle 12c New Features for Developers
Oracle 12c New Features for Developers
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
 
ADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database SystemsADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database Systems
 
IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
 
2..basic queries.pptx
2..basic queries.pptx2..basic queries.pptx
2..basic queries.pptx
 
Less07 schema
Less07 schemaLess07 schema
Less07 schema
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Dan Hotka's Top 10 Oracle 12c New Features
Dan Hotka's Top 10 Oracle 12c New FeaturesDan Hotka's Top 10 Oracle 12c New Features
Dan Hotka's Top 10 Oracle 12c New Features
 
MySQL basics
MySQL basicsMySQL basics
MySQL basics
 

Recently uploaded

Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
amitlee9823
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
JoseMangaJr1
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
amitlee9823
 
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
amitlee9823
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
amitlee9823
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
amitlee9823
 

Recently uploaded (20)

Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFx
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
 
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
 
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Capstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics ProgramCapstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics Program
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 

filterAndSort.pptx

  • 2. Module Overview • Sorting Data • Filtering Data with Predicates • Filtering Data with TOP and OFFSET-FETCH • Working with Unknown Values
  • 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;
  • 7. Demonstration: Sorting Data In this demonstration, you will see how to: • Sort data using the ORDER BY clause
  • 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;
  • 20. Demonstration: Working with NULL In this demonstration, you will see how to: • Test for NULL

Editor's Notes

  1. 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.
  2. 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.
  3. 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.
  4. 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';
  5. Remind the students of three-value logic. NULLs will be discussed later in this module.
  6. 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.
  7. 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;
  8. 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.
  9. 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.
  10. 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.
  11. 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.
  12. 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
  13. 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.
  14. 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.