Writing SELECT Queries

Slides:



Advertisements
Similar presentations
Writing Basic SQL SELECT Statements. Capabilities of SQL SELECT Statements A SELECT statement retrieves information from the database. Using a SELECT.
Advertisements

Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
Ceng 356-Lab1. Objectives After completing this lesson, you should be able to do the following: Get Familiar with the development environment List the.
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
Chapter 2 Basic SQL SELECT Statements
Module 1: Introduction to Transact-SQL
04 | Grouping and Aggregating Data Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
Introduction to SQL PART Ⅰ 第一讲 Writing Basic SQL SELECT Statements.
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.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
Module 2: Querying and Filtering Data. Using the SELECT Statement Filtering Data Working with NULL Values Formatting Result Sets Performance Considerations.
1 Copyright © 2007, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
Oracle 10g Retrieving Data Using the SQL SELECT Statement.
1 Copyright © 2009, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
1 Copyright © 2004, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
SQL IMPLEMENTATION & ADMINISTRATION Indexing & Views.
CHAPTER 7 DATABASE ACCESS THROUGH WEB
Retrieving Data Using the SQL SELECT Statement
Using DML to Modify Data
Relational Database Design
Writing Basic SQL SELECT Statements
Introduction to T-SQL Querying
02 | Advanced SELECT Statements
Sorting and Filtering Data
Basic Data Manipulation - Reading Data
Querying Multiple Tables
09 | Modifying Data Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master.
20761A 10: Using Subqueries Module 10   Using Subqueries.
Using the Set Operators
05 | Using Functions and Aggregating Data
20761A 11: Using Set Operators Module 11   Using Set Operators.
03 | Querying Multiple Tables with Joins
Using Window Ranking, Offset, and Aggregate Functions
Aggregating Data Using Group Functions
Sorting and Filtering Data
Querying Multiple Tables
Writing Basic SQL SELECT Statements
06 | Using Subqueries and APPLY
20761B 12: Using Set Operators Module 12   Using Set Operators.
20761B 12: Using Set Operators Module 12   Using Set Operators.
Using the Set Operators
09 | Modifying Data Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master.
02 | Querying Tables with SELECT
20761B 10: Using Subqueries Module 10   Using Subqueries.
Retrieving Data Using the SQL SELECT Statement
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
Using Table Expressions
Introduction to LINQ Chapter 11.
Writing Basic SQL SELECT Statements
Access/SQL Server Eliminate Duplicates with SELECT DISTINCT
Reporting Aggregated Data Using the Group Functions
Retrieving Data Using the SQL SELECT Statement
Topic 12 Lesson 2 – Retrieving Data with Queries
Reporting Aggregated Data Using the Group Functions
Using the Set Operators
Reporting Aggregated Data Using the Group Functions
Using DML to Modify Data
02 | Querying Tables with SELECT
Aggregating Data Using Group Functions
Pivoting and Grouping Sets
Grouping and Aggregating Data
Presentation transcript:

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