Top Banner
Click to edit Master subtitle style 02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager
34

Advanced SELECT Statements SQL SERVER

Sep 25, 2015

Download

Documents

chirag2709

SQL SERVER
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

02 | Advanced SELECT StatementsBrian Alderman | MCT, CEO / Founder of MicroTechPointTobias Ternstrom | Microsoft SQL Server Program ManagerClick to edit Master subtitle style1Course TopicsQuerying Microsoft SQL Server 2012 Jump Start01 | Introducing SQL Server 2012 SQL Server types of statements; other SQL statement elements; basic SELECT statements02 | Advanced SELECT Statements DISTINCT, Aliases, scalar functions and CASE, using JOIN and MERGE; Filtering and sorting data, NULL values03 | SQL Server Data Types Introduce data types, data type usage, converting data types, understanding SQL Server function types04 | 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 sessionModule 4: Managing SecurityCourse 2786B2Advanced SELECT clauses (DISTINCT, aliases, CASE, and scalar functions)Query multiple tables using JOIN statementsFiltering and sorting dataModule Overview3Advanced SELECT ClausesModule 4: Managing SecurityCourse 2786B4Understanding DISTINCTSpecifies that only unique rows can appear in the result setRemoves duplicates based on column list results, not source tableProvides uniqueness across set of selected columnsRemoves rows already operated on by WHERE, HAVING, and GROUP BY clausesSome queries may improve performance by filtering out duplicates prior to execution of SELECT clauseModule 4: Writing SELECT QueriesCourse 10774A5SELECT DISTINCT syntaxSELECT DISTINCT

FROM SELECT DISTINCT StoreID FROM Sales.Customer;StoreID-------12345709021898710Module 4: Writing SELECT QueriesCourse 10774A6Using aliases to refer to columnsColumn 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;Module 4: Writing SELECT QueriesCourse 10774A7Using aliases to refer to tablesCreate 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;Module 4: Writing SELECT QueriesCourse 10774A8T-SQL CASE expressionsSimple CASECompares one value to a list of possible values and returns first matchIf no match, returns value found in optional ELSE clauseIf no match and no ELSE, returns NULLSearched CASEEvaluates a set of predicates, or logical expressionsReturns value found in THEN clause matching first expression that evaluates to TRUET-SQL CASE expressions return a single (scalar) valueCASE expressions may be used in: SELECT column list (behaves as calculated column requiring an alias)WHERE or HAVING clausesORDER BY clause

Module 4: Writing SELECT QueriesCourse 10774A9Writing simple CASE expressionsSELECT ProductID, Name, ProductSubCategoryID, CASE ProductSubCategoryID WHEN 1 THEN 'Beverages' ELSE 'Unknown Category' ENDFROM Production.ProductKeywordExpression componentSELECT

CASE

WHEN

THEN

END N/AFROM

Module 4: Writing SELECT QueriesCourse 10774A10Using basic SELECT clausesDemoModule 4: Managing SecurityCourse 2786B11JOIN StatementsModule 4: Managing SecurityCourse 2786B12Overview of JOIN typesJOIN types in FROM clause specify the operations performed on the virtual table:Join TypeDescriptionCrossCombines all rows in both tables (creates Cartesian product).InnerStarts with Cartesian product; applies filter to match rows between tables based on predicate.OuterStarts with Cartesian product; all rows from designated table preserved, matching rows from other table retrieved. Additional NULLs inserted as placeholders.Module 5: Querying Multiple TablesCourse 10774A13Understanding INNER JOINSReturns only rows where a match is found in both tablesMatches rows based on attributes supplied in predicateON clause in SQL-92 syntax Why filter in ON clause?Logical separation between filtering for purposes of JOIN and filtering results in WHERETypically no difference to query optimizerIf JOIN predicate operator is =, also known as equi-joinModule 5: Querying Multiple TablesCourse 10774A14INNER JOIN SyntaxList tables in FROM Clause separated by JOIN operatorTable order does not matter, and aliases are preferred

SELECT SOH.SalesOrderID, SOH.OrderDate, SOD.ProductID, SOD.UnitPrice, SOD.OrderQtyFROM Sales.SalesOrderHeader AS SOH JOIN Sales.SalesOrderDetail AS SOD ON SOH.SalesOrderID = SOD.SalesOrderID;FROM t1 JOIN t2 ON t1.column = t2.columnModule 5: Querying Multiple TablesCourse 10774A15Understanding OUTER JOINSReturns all rows from one table and any matching rows from second tableOne tables rows are preservedDesignated with LEFT, RIGHT, FULL keywordAll rows from preserved table output to result setMatches from other table retrievedAdditional rows added to results for non-matched rowsNULLs added in place where attributes do not matchExample: 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 TablesCourse 10774A16OUTER JOIN examplesCustomers that did not place orders:SELECT CUST.CustomerID, CUST.StoreID, ORD.SalesOrderID, ORD.OrderDateFROM Sales.Customer AS CUSTLEFT OUTER JOIN Sales.SalesOrderHeader AS ORDON CUST.CustomerID = ORD.CustomerIDWHERE ORD.SalesOrderID IS NULL;Module 5: Querying Multiple TablesCourse 10774A17Understanding CROSS JOINSCombine each row from first table with each row from second tableAll possible combinations are displayed Logical foundation for inner and outer joinsINNER JOIN starts with Cartesian product, adds filterOUTER JOIN takes Cartesian output, filtered, adds back non-matching rows (with NULL placeholders)Due to Cartesian product output, not typically a desired form of JOINSome useful exceptions: Generating a table of numbers for testingModule 5: Querying Multiple TablesCourse 10774A18CROSS JOIN ExampleCreate test data by returning all combinations of two inputs:SELECT EMP1.BusinessEntityID, EMP2.JobTitleFROM HumanResources.Employee AS EMP1 CROSS JOIN HumanResources.Employee AS EMP2;Module 5: Querying Multiple TablesCourse 10774A19Understanding Self-JoinsWhy use self-joins?Compare rows in same table to each otherCreate two instances of same table in FROM clauseAt least one alias required

Example: Return all employees and the name of the employees manager

Module 5: Querying Multiple TablesCourse 10774A20Self-Join examplesReturn all employees with ID of employees 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.LastNameFROM HR.Employees AS EMPINNER JOIN HR.Employees AS MGR ON EMP.MgrID = MGR.EmpID ;SELECT EMP.EmpID, EMP.LastName, EMP.Title, MGR.MgrIDFROM HumanResources.Employee AS EMPLEFT OUTER JOIN HumanResources.Employee AS MGRON EMP.MgrID = MGR.EmpID;Module 5: Querying Multiple TablesCourse 10774A21Using JOINS to view data from multiple tablesDemoModule 4: Managing SecurityCourse 2786B22Filtering and Sorting DataModule 4: Managing SecurityCourse 2786B23Using the ORDER BY clauseORDER BY sorts rows in results for presentation purposesUse of ORDER BY guarantees the sort order of the resultLast clause to be logically processedSorts all NULLs togetherORDER BY can refer to:Columns by name, alias or ordinal position (not recommended)Columns not part of SELECT list unless DISTINCT clause specifiedDeclare sort order with ASC or DESC

Module 6: Sorting and Filtering DataCourse 10774A24ORDER BY clause examplesORDER BY with column names:

ORDER BY with column alias:

ORDER BY with descending order:SELECT SalesOrderID, CustomerID, OrderDateFROM Sales.SalesOrderHeaderORDER BY OrderDate;SELECT SalesOrderID, CustomerID, YEAR(OrderDate) AS OrderYearFROM Sales.SalesOrderHeaderORDER BY OrderYear;SELECT SalesOrderID, CustomerID, OrderDateFROM Sales.SalesOrderHeaderORDER BY OrderDate DESC;Module 6: Sorting and Filtering DataCourse 10774A25Filtering data in the WHERE clauseWHERE clauses use predicatesMust be expressed as logical conditionsOnly rows for which predicate evaluates to TRUE are acceptedValues of FALSE or UNKNOWN are filtered outWHERE clause follows FROM, precedes other clausesCant see aliases declared in SELECT clauseCan be optimized by SQL Server to use indexesModule 6: Sorting and Filtering DataCourse 10774A26WHERE clause syntaxFilter 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, TerritoryIDFROM Sales.CustomerWHERE TerritoryID = 6;SELECT CustomerID, TerritoryIDFROM Sales.CustomerWHERE TerritoryID >= 6;SELECT CustomerID, TerritoryID, StoreIDFROM Sales.CustomerWHERE StoreID >= 1000 AND StoreID