Writing SELECT Queries 20761B 3: Writing SELECT Queries Module 3 The 20761B-MIA-SQL VM used in the lab for this module includes software services that can take a while to start. For the best experience, have students start the MSL-TMG1, 20761B-MIA-DC and 20761B-MIA- SQL VMs at the beginning of the module so that the services are ready before they start the lab. Microsoft Azure Pass There are demonstrations in this course that require access to Microsoft® Azure®. Make enough time for the setup and configuration of a Microsoft Azure pass. Details of how to acquire Microsoft Azure passes are available here: http://go.microsoft.com/fwlink/?LinkId=512034 The Azure demonstration in this module requires a copy of the AdventureWorksLT database. For detailed steps on creating a copy of the AdventureWorksLT database in Azure, see D:\Creating an AdventureWorks Database on Azure.docx. Writing SELECT Queries
Writing Simple CASE Expressions 20761B Module Overview 3: Writing SELECT Queries Writing Simple CASE Expressions
Lesson 1: Writing Simple SELECT Statements 20761B Lesson 1: Writing Simple SELECT Statements 3: Writing SELECT Queries Demonstration: Writing Simple SELECT Statements Question You have a table named Sales with the following columns: Country, NumberOfReps, TotalSales. You want to find out the average amount of sales a sales representative makes in each country. What SELECT query could you use? Answer SELECT Country, (TotalSales / NumberOfReps) AS AverageSalesPerRep FROM Sales;
Elements of the SELECT Statement 20761B Elements of the SELECT Statement 3: Writing SELECT Queries Clause Expression SELECT <select list> FROM <table or view> WHERE <search condition> GROUP BY <group by list> ORDER BY <order by list>
Retrieving Columns from a Table or View 3: Writing SELECT Queries Use SELECT with column list to show columns Use FROM to specify the source table or view Specify both schema and object names Delimit names if necessary End all statements with a semicolon Keyword Expression SELECT <select list> FROM <table or view> SELECT companyname, country FROM Sales.Customers;
Displaying all columns 20761B Displaying Columns 3: Writing SELECT Queries Displaying all columns This is not best practice in production code! Displaying only specified columns SELECT * FROM Sales.Customers; SELECT companyname, country FROM Sales.Customers;
Using Calculations in the SELECT Clause 20761B Using Calculations in the SELECT Clause 3: Writing SELECT Queries Calculations are scalar, returning one value per row Using scalar expressions in the SELECT clause Operator Description + Add or concatenate - Subtract * Multiply / Divide % Modulo SELECT unitprice, qty, (qty * unitprice) FROM Sales.OrderDetails;
Lesson 2: Eliminating Duplicates with DISTINCT 20761B Lesson 2: Eliminating Duplicates with DISTINCT 3: Writing SELECT Queries Demonstration: Eliminating Duplicates with DISTINCT Question You have company departments in five countries. You have the following query for the Human Resources database: SELECT DeptName, Country FROM HumanResources.Departments This returns: DeptName Country --------- -------- Sales UK Sales USA Sales France Sales Japan Marketing USA Marketing Japan Research USA You add a DISTINCT keyword to the SELECT query. How many rows are returned? Answer 7
SQL Sets and Duplicate Rows 20761B SQL Sets and Duplicate Rows 3: Writing SELECT Queries SQL query results are not truly relational: Rows are not guaranteed to be unique No guaranteed order Even unique rows in a source table can return duplicate values for some columns SELECT country FROM Sales.Customers; country ----------- Argentina Belgium Austria
Understanding DISTINCT 20761B Understanding DISTINCT 3: Writing SELECT Queries DISTINCT 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 before execution of SELECT clause
SELECT DISTINCT Syntax 20761B SELECT DISTINCT Syntax 3: Writing SELECT Queries SELECT DISTINCT <column list> FROM <table or view> SELECT DISTINCT companyname, country FROM Sales.Customers; companyname -------------- country ------- Customer AHPOP UK Customer AHXHT Mexico Customer AZJED Germany Customer BSVAR France Customer CCFIZ Poland
Lesson 3: Using Column and Table Aliases 3: Writing SELECT Queries Demonstration: Using Column and Table Aliases Question You have the following query: SELECT FirstName LastName FROM HumanResources.Employees; You are surprised to find that the query returns the following: LastName --------- Fred Rosalind Anil Linda What error have you made in the SELECT query? Answer You have omitted a comma between FirstName and LastName.
Use Aliases to Refer to Columns 20761B Use Aliases to Refer to Columns 3: Writing SELECT Queries Column aliases using AS Column aliases using = Accidental column aliases SELECT orderid, unitprice, qty AS quantity FROM Sales.OrderDetails; Question Which of the following statements use correct column aliases? SELECT Name AS ProductName FROM Production.Product SELECT Name = ProductName FROM Production.Product SELECT ProductName == Name FROM Production.Product SELECT ProductName = Name FROM Production.Product SELECT Name AS Product Name FROM Production.Product Answer Statements 1 and 4 are correct. SELECT orderid, unitprice, quantity = qty FROM Sales.OrderDetails; SELECT orderid, unitprice quantity FROM Sales.OrderDetails;
Use Aliases to Refer to Tables 3: Writing SELECT Queries Create table aliases in the FROM clause Create table aliases with AS Create table aliases without AS Using table aliases in the SELECT clause SELECT custid, orderdate FROM SalesOrders AS SO; SELECT custid, orderdate FROM SalesOrders SO; SELECT SO.custid, SO.orderdate FROM SalesOrders AS SO
The Impact of Logical Processing Order on Aliases 20761B The Impact of Logical Processing Order on Aliases 3: Writing SELECT Queries FROM, WHERE, and HAVING clauses processed before SELECT Aliases created in SELECT clause only visible to ORDER BY Expressions aliased in SELECT clause may be repeated elsewhere in query Note: The reason why an alias created in a SELECT clause may not be referenced elsewhere in the clause is due to the all-at-once processing implemented by SQL Server.
Lesson 4: Writing Simple CASE Expressions 20761B Lesson 4: Writing Simple CASE Expressions 3: Writing SELECT Queries Demonstration: Simple CASE Expressions Question You have the following SELECT query: SELECT FirstName, LastName, Sex FROM HumanResources.Employees; This returns: FirstName LastName Sex ---------- --------- ---- Maya Steele 1 Adam Brookes 0 Naomi Sharp 1 Pedro Fielder 0 Zachary Parsons 0 How could you make these results clearer? Answer Use the following query: SELECT FirstName, LastName, Gender = CASE Sex WHEN 1 THEN ‘Female’ WHEN 0 THEN ‘Male’ ELSE ‘Unspecified’ END
Using CASE Expressions in SELECT Clauses 20761B Using CASE Expressions in SELECT Clauses 3: Writing SELECT Queries T-SQL CASE expressions return a single (scalar) value CASE expressions may be used in: SELECT column list WHERE or HAVING clauses ORDER BY clause CASE returns result of expression Not a control-of-flow mechanism In SELECT clause, CASE behaves as calculated column requiring an alias
Forms of CASE Expressions 20761B Forms of CASE Expressions 3: Writing SELECT Queries Two forms of T-SQL CASE expressions: Simple CASE Compares one value to a list of possible values 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 https://msdn.microsoft.com/en-us/library/ms715950(v=vs.85).aspx