02 | Advanced SELECT Statements

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

Chapter 4 Joining Multiple Tables
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Introduction to SQL Structured Query Language Martin Egerhill.
Introduction to Databases Chapter 7: Data Access and Manipulation.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Chapter 9 Joining Data from Multiple Tables
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
04 | Grouping and Aggregating Data Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Module 18 Querying XML Data in SQL Server® 2008 R2.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Copyright © 2004, Oracle. All rights reserved. Lecture 4: 1-Retrieving Data Using the SQL SELECT Statement 2-Restricting and Sorting Data Lecture 4: 1-Retrieving.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
05 | SET Operators, Windows Functions, and Grouping Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Thinking in Sets and SQL Query Logical Processing.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Module 2: Querying and Filtering Data. Using the SELECT Statement Filtering Data Working with NULL Values Formatting Result Sets Performance Considerations.
 CONACT UC:  Magnific training   
Slide 1 of 32ASH-Training Querying and Managing Data Using SQL Server 2014 By: Segla In this session, you will learn to: Query data by using joins Query.
Brian Alderman | MCT, CEO / Founder of MicroTechPoint Pete Harris | Microsoft Senior Content Publisher.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CHAPTER 7 DATABASE ACCESS THROUGH WEB
SQL Query Getting to the data ……..
More SQL: Complex Queries,
Relational Database Design
Writing Basic SQL SELECT Statements
Basic select statement
Sorting and Filtering Data
Querying Multiple Tables
20761A 10: Using Subqueries Module 10   Using Subqueries.
05 | Using Functions and Aggregating Data
03 | Querying Multiple Tables with Joins
Using Subqueries to Solve Queries
Sorting and Filtering Data
Querying Multiple Tables
06 | Using Subqueries and APPLY
20761B 12: Using Set Operators Module 12   Using Set Operators.
Using the Set Operators
Writing SELECT Queries
02 | Querying Tables with SELECT
20761B 10: Using Subqueries Module 10   Using Subqueries.
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Using Table Expressions
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Access: SQL Participation Project
Chapter 7 Introduction to Structured Query Language (SQL)
SQL Fundamentals in Three Hours
Using Subqueries to Solve Queries
Contents Preface I Introduction Lesson Objectives I-2
Using Subqueries to Solve Queries
Using Subqueries to Solve Queries
Subqueries Schedule: Timing Topic 25 minutes Lecture
02 | Querying Tables with SELECT
Grouping and Aggregating Data
Presentation transcript:

02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager

Module 4: Managing Security Course 2786B Module 4: Managing Security Course Topics Querying Microsoft SQL Server 2012 Jump Start 01 | Introducing SQL Server 2012 SQL Server types of statements; other SQL statement elements; basic SELECT statements 02 | Advanced SELECT Statements DISTINCT, Aliases, scalar functions and CASE, using JOIN and MERGE; Filtering and sorting data, NULL values 03 | SQL Server Data Types Introduce data types, data type usage, converting data types, understanding SQL Server function types 04 | Grouping and Aggregating Data Aggregate functions, GROUP BY and HAVING clauses, subqueries; self-contained, correlated, and EXISTS; Views, inline-table valued functions, and derived tables | Lunch Break Eat, drink, and recharge for the afternoon session

Module Overview Advanced SELECT clauses (DISTINCT, aliases, CASE, and scalar functions) Query multiple tables using JOIN statements Filtering and sorting data

Module 4: Managing Security Course 2786B Module 4: Managing Security Advanced SELECT Clauses

Understanding DISTINCT Course 10774A Understanding DISTINCT Module 4: Writing SELECT Queries Specifies that only unique rows can appear in the result set Removes duplicates based on column list results, not source table Provides uniqueness across set of selected columns Removes rows already operated on by WHERE, HAVING, and GROUP BY clauses Some queries may improve performance by filtering out duplicates prior to execution of SELECT clause

SELECT DISTINCT syntax Course 10774A SELECT DISTINCT syntax Module 4: Writing SELECT Queries SELECT DISTINCT <column list> FROM <table or view> SELECT DISTINCT StoreID FROM Sales.Customer; StoreID ------- 1234 570 902 1898 710

Using aliases to refer to columns Course 10774A Using aliases to refer to columns Module 4: Writing SELECT Queries Column aliases using AS Column aliases using = Accidental column aliases SELECT SalesOrderID, UnitPrice, OrderQty AS Quantity FROM Sales.SalesOrderDetail; SELECT SalesOrderID, UnitPrice, Quantity = OrderQty FROM Sales.SalesOrderDetail; SELECT SalesOrderID, UnitPrice Quantity FROM Sales.SalesOrderDetail;

Using aliases to refer to tables Course 10774A Using aliases to refer to tables Module 4: Writing SELECT Queries Create table aliases in the FROM clause using AS Table aliases without AS Using table aliases in the SELECT clause SELECT SalesOrderID, ProductID FROM Sales.SalesOrderDetail AS SalesOrders; SELECT SalesOrderID, ProductID FROM Sales.SalesOrderDetail SalesOrders; SELECT SalesOrders.SalesOrderID, SalesOrders.ProductID FROM Sales.SalesOrderDetail AS SalesOrders;

T-SQL CASE expressions Course 10774A T-SQL CASE expressions Module 4: Writing SELECT Queries Simple CASE Compares one value to a list of possible values and returns first match If no match, returns value found in optional ELSE clause If no match and no ELSE, returns NULL Searched CASE Evaluates a set of predicates, or logical expressions Returns value found in THEN clause matching first expression that evaluates to TRUE T-SQL CASE expressions return a single (scalar) value CASE expressions may be used in: SELECT column list (behaves as calculated column requiring an alias) WHERE or HAVING clauses ORDER BY clause

Writing simple CASE expressions Course 10774A Writing simple CASE expressions Module 4: Writing SELECT Queries Keyword Expression component SELECT <select list> CASE <value to compare> WHEN <value to match> THEN <result> END N/A FROM <table source> SELECT ProductID, Name, ProductSubCategoryID, CASE ProductSubCategoryID WHEN 1 THEN 'Beverages' ELSE 'Unknown Category' END FROM Production.Product

Module 4: Managing Security Using basic SELECT clauses Course 2786B Module 4: Managing Security Demo Using basic SELECT clauses

Module 4: Managing Security Course 2786B Module 4: Managing Security JOIN Statements

Module 5: Querying Multiple Tables Course 10774A Overview of JOIN types Module 5: Querying Multiple Tables JOIN types in FROM clause specify the operations performed on the virtual table: Join Type Description Cross Combines all rows in both tables (creates Cartesian product). Inner Starts with Cartesian product; applies filter to match rows between tables based on predicate. Outer Starts with Cartesian product; all rows from designated table preserved, matching rows from other table retrieved. Additional NULLs inserted as placeholders.

Understanding INNER JOINS Course 10774A Understanding INNER JOINS Module 5: Querying Multiple Tables Returns only rows where a match is found in both tables Matches rows based on attributes supplied in predicate ON clause in SQL-92 syntax Why filter in ON clause? Logical separation between filtering for purposes of JOIN and filtering results in WHERE Typically no difference to query optimizer If JOIN predicate operator is =, also known as equi-join

Module 5: Querying Multiple Tables Course 10774A INNER JOIN Syntax Module 5: Querying Multiple Tables List tables in FROM Clause separated by JOIN operator Table order does not matter, and aliases are preferred FROM t1 JOIN t2 ON t1.column = t2.column SELECT SOH.SalesOrderID, SOH.OrderDate, SOD.ProductID, SOD.UnitPrice, SOD.OrderQty FROM Sales.SalesOrderHeader AS SOH JOIN Sales.SalesOrderDetail AS SOD ON SOH.SalesOrderID = SOD.SalesOrderID;

Understanding OUTER JOINS Course 10774A Understanding OUTER JOINS Module 5: Querying Multiple Tables Returns all rows from one table and any matching rows from second table One table’s rows are “preserved” Designated with LEFT, RIGHT, FULL keyword All rows from preserved table output to result set Matches from other table retrieved Additional rows added to results for non-matched rows NULLs added in place where attributes do not match Example: Return all customers and for those who have placed orders, return order information. Customers without matching orders will display NULL for order details.

Module 5: Querying Multiple Tables Course 10774A OUTER JOIN examples Module 5: Querying Multiple Tables Customers that did not place orders: SELECT CUST.CustomerID, CUST.StoreID, ORD.SalesOrderID, ORD.OrderDate FROM Sales.Customer AS CUST LEFT OUTER JOIN Sales.SalesOrderHeader AS ORD ON CUST.CustomerID = ORD.CustomerID WHERE ORD.SalesOrderID IS NULL;

Understanding CROSS JOINS Course 10774A Understanding CROSS JOINS Module 5: Querying Multiple Tables Combine each row from first table with each row from second table All possible combinations are displayed Logical foundation for inner and outer joins INNER JOIN starts with Cartesian product, adds filter OUTER JOIN takes Cartesian output, filtered, adds back non-matching rows (with NULL placeholders) Due to Cartesian product output, not typically a desired form of JOIN Some useful exceptions: Generating a table of numbers for testing

Module 5: Querying Multiple Tables Course 10774A CROSS JOIN Example Module 5: Querying Multiple Tables Create test data by returning all combinations of two inputs: SELECT EMP1.BusinessEntityID, EMP2.JobTitle FROM HumanResources.Employee AS EMP1 CROSS JOIN HumanResources.Employee AS EMP2;

Understanding Self-Joins Course 10774A Understanding Self-Joins Module 5: Querying Multiple Tables Why use self-joins? Compare rows in same table to each other Create two instances of same table in FROM clause At least one alias required Example: Return all employees and the name of the employee’s manager

Module 5: Querying Multiple Tables Course 10774A Self-Join examples Module 5: Querying Multiple Tables Return all employees with ID of employee’s manager when a manager exists (INNER JOIN): Return all employees with ID of manager (OUTER JOIN). This will return NULL for the CEO: SELECT EMP.EmpID, EMP.LastName, EMP.JobTitle, EMP.MgrID, MGR.LastName FROM HR.Employees AS EMP INNER JOIN HR.Employees AS MGR ON EMP.MgrID = MGR.EmpID ; SELECT EMP.EmpID, EMP.LastName, EMP.Title, MGR.MgrID FROM HumanResources.Employee AS EMP LEFT OUTER JOIN HumanResources.Employee AS MGR ON EMP.MgrID = MGR.EmpID;

Module 4: Managing Security Course 2786B Module 4: Managing Security Demo Using JOINS to view data from multiple tables

Module 4: Managing Security Course 2786B Module 4: Managing Security Filtering and Sorting Data

Using the ORDER BY clause Course 10774A Using the ORDER BY clause Module 6: Sorting and Filtering Data ORDER BY sorts rows in results for presentation purposes 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 clause specified Declare sort order with ASC or DESC

ORDER BY clause examples Course 10774A ORDER BY clause examples Module 6: Sorting and Filtering Data ORDER BY with column names: ORDER BY with column alias: ORDER BY with descending order: SELECT SalesOrderID, CustomerID, OrderDate FROM Sales.SalesOrderHeader ORDER BY OrderDate; SELECT SalesOrderID, CustomerID, YEAR(OrderDate) AS OrderYear FROM Sales.SalesOrderHeader ORDER BY OrderYear; SELECT SalesOrderID, CustomerID, OrderDate FROM Sales.SalesOrderHeader ORDER BY OrderDate DESC;

Filtering data in the WHERE clause Course 10774A Filtering data in the WHERE clause Module 6: Sorting and Filtering Data 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 are 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

Module 6: Sorting and Filtering Data Course 10774A WHERE clause syntax Module 6: Sorting and Filtering Data Filter rows for customers in territory 6 Filter rows for orders in territories greater than or equal to 6 Filter orders within a range of dates SELECT CustomerID, TerritoryID FROM Sales.Customer WHERE TerritoryID = 6; SELECT CustomerID, TerritoryID FROM Sales.Customer WHERE TerritoryID >= 6; SELECT CustomerID, TerritoryID, StoreID FROM Sales.Customer WHERE StoreID >= 1000 AND StoreID <= 1200;

Filtering data in the SELECT clause Course 10774A Filtering data in the SELECT clause Module 6: Sorting and Filtering Data TOP allows you to limit the number or percentage of rows returned 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

Module 6: Sorting and Filtering Data Course 10774A Filtering using TOP Module 6: Sorting and Filtering Data Filter rows for customers to display top 20 TotalDue items Filter rows for customers to display top 20 TotalDue items with ties Filter rows for customers to display top 1% of TotalDue items SELECT TOP (20) SalesOrderID, CustomerID, TotalDue FROM Sales.SalesOrderHeader ORDER BY TotalDue DESC; SELECT TOP (20) WITH TIES SalesOrderID, CustomerID, TotalDue FROM Sales.SalesOrderHeader ORDER BY TotalDue DESC; SELECT TOP (1) PERCENT SalesOrderID, CustomerID, TotalDue FROM Sales.SalesOrderHeader ORDER BY TotalDue DESC;

Handling NULL in queries Course 10774A Handling NULL in queries Module 6: Sorting and Filtering Data 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 CustomerID, StoreID, TerritoryID FROM Sales.Customer WHERE StoreID IS NULL ORDER BY TerritoryID

Module 4: Managing Security Sorting and filtering data Course 2786B Module 4: Managing Security Demo Sorting and filtering data

Module 4: Managing Security Course 2786B Summary Module 4: Managing Security The SELECT statement requires columns specified (* all columns) and the FROM clause to identify what view or table the rows of data are being pulled from Clauses like DISTINCT provide control over what items are returned in the result set. Aliases are used to define the names of columns or tables being referenced in the SELECT statement CASE statements are used for performing comparisons in a list of values and returns first match

Module 4: Managing Security Course 2786B Summary Module 4: Managing Security JOINS are used to display content from multiple tables in a single result set. INNER, OUTER, CROSS, and SELF JOINS can all be used to create the desire result set ORDER BY is used to sort the rows returned in the result set WHERE is used to filter the rows returned in the result set The TOP clause is used to define the number of rows returned in the result set by specifying the number of rows or a percentage of rows returned.

Module 4: Managing Security Course 2786B Module 4: Managing Security