Sei sulla pagina 1di 262

MCT USE ONLY.

STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

O F F I C I A L

M I C R O S O F T

L E A R N I N G

P R O D U C T

PR D ER EV EL ELO EA P SE ED SO US F T IN W G A RE

10774A

Querying Microsoft SQL Server 2012

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

ii

Querying Microsoft SQL Server 2012

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein. 2012 Microsoft Corporation. All rights reserved. Microsoft and the trademarks listed at http://www.microsoft.com/about/legal/en/us/IntellectualProperty /Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners.

Product Number: 10774A Released: 01/2012

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012


1.

MICROSOFT LICENSE TERMS OFFICIAL MICROSOFT LEARNING PRODUCTS MICROSOFT OFFICIAL COURSE Pre-Release and Final Release Versions

These license terms are an agreement between Microsoft Corporation and you. Please read them. They apply to the Licensed Content named above, which includes the media on which you received it, if any. These license terms also apply to any updates, supplements, internet based services and support services for the Licensed Content, unless other terms accompany those items. If so, those terms apply. BY DOWNLOADING OR USING THE LICENSED CONTENT, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT DOWNLOAD OR USE THE LICENSED CONTENT. If you comply with these license terms, you have the rights below. DEFINITIONS.

a. Authorized Learning Center means a Microsoft Learning Competency Member, Microsoft IT Academy Program Member, or such other entity as Microsoft may designate from time to time. b. Authorized Training Session means the Microsoft-authorized instructor-led training class using only MOC Courses that are conducted by a MCT at or through an Authorized Learning Center.

c. Classroom Device means one (1) dedicated, secure computer that you own or control that meets or exceeds the hardware level specified for the particular MOC Course located at your training facilities or primary business location. d. End User means an individual who is (i) duly enrolled for an Authorized Training Session or Private Training Session, (ii) an employee of a MPN Member, or (iii) a Microsoft full-time employee. e. Licensed Content means the MOC Course and any other content accompanying this agreement. Licensed Content may include (i) Trainer Content, (ii) software, and (iii) associated media. f.

Microsoft Certified Trainer or MCT means an individual who is (i) engaged to teach a training session to End Users on behalf of an Authorized Learning Center or MPN Member, (ii) currently certified as a Microsoft Certified Trainer under the Microsoft Certification Program, and (iii) holds a Microsoft Certification in the technology that is the subject of the training session.

g. Microsoft IT Academy Member means a current, active member of the Microsoft IT Academy Program.

h. Microsoft Learning Competency Member means a Microsoft Partner Network Program Member in good standing that currently holds the Learning Competency status. i.

Microsoft Official Course or MOC Course means the Official Microsoft Learning Product instructorled courseware that educates IT professionals or developers on Microsoft technologies.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012


2.

j.

Microsoft Partner Network Member or MPN Member means a silver or gold-level Microsoft Partner Network program member in good standing.

k. Personal Device means one (1) device, workstation or other digital electronic device that you personally own or control that meets or exceeds the hardware level specified for the particular MOC Course. l. Private Training Session means the instructor-led training classes provided by MPN Members for corporate customers to teach a predefined learning objective. These classes are not advertised or promoted to the general public and class attendance is restricted to individuals employed by or contracted by the corporate customer.

m. Trainer Content means the trainer version of the MOC Course and additional content designated solely for trainers to use to teach a training session using a MOC Course. Trainer Content may include Microsoft PowerPoint presentations, instructor notes, lab setup guide, demonstration guides, beta feedback form and trainer preparation guide for the MOC Course. To clarify, Trainer Content does not include virtual hard disks or virtual machines. INSTALLATION AND USE RIGHTS. The Licensed Content is licensed not sold. The Licensed Content is licensed on a one copy per user basis, such that you must acquire a license for each individual that accesses or uses the Licensed Content. 2.1 Below are four separate sets of installation and use rights. Only one set of rights apply to you.

a. If you are a Authorized Learning Center: i. If the Licensed Content is in digital format for each license you acquire you may either: 1. install one (1) copy of the Licensed Content in the form provided to you on a dedicated, secure server located on your premises where the Authorized Training Session is held for access and use by one (1) End User attending the Authorized Training Session, or by one (1) MCT teaching the Authorized Training Session, or 2. install one (1) copy of the Licensed Content in the form provided to you on one (1) Classroom Device for access and use by one (1) End User attending the Authorized Training Session, or by one (1) MCT teaching the Authorized Training Session. ii. You agree that: 1. you will acquire a license for each End User and MCT that accesses the Licensed Content, 2. each End User and MCT will be presented with a copy of this agreement and each individual will agree that their use of the Licensed Content will be subject to these license terms prior to their accessing the Licensed Content. Each individual will be required to denote their acceptance of the EULA in a manner that is enforceable under local law prior to their accessing the Licensed Content, 3. for all Authorized Training Sessions, you will only use qualified MCTs who hold the applicable competency to teach the particular MOC Course that is the subject of the training session, 4. you will not alter or remove any copyright or other protective notices contained in the Licensed Content,

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5. you will remove and irretrievably delete all Licensed Content from all Classroom Devices and servers at the end of the Authorized Training Session, 6. you will only provide access to the Licensed Content to End Users and MCTs, 7. you will only provide access to the Trainer Content to MCTs, and 8. any Licensed Content installed for use during a training session will be done in accordance with the applicable classroom set-up guide.

b. If you are a MPN Member. i. If the Licensed Content is in digital format for each license you acquire you may either: 1. install one (1) copy of the Licensed Content in the form provided to you on (A) one (1) Classroom Device, or (B) one (1) dedicated, secure server located at your premises where the training session is held for use by one (1) of your employees attending a training session provided by you, or by one (1) MCT that is teaching the training session, or 2. install one (1) copy of the Licensed Content in the form provided to you on one (1) Classroom Device for use by one (1) End User attending a Private Training Session, or one (1) MCT that is teaching the Private Training Session. ii. You agree that: 1. you will acquire a license for each End User and MCT that accesses the Licensed Content, 2. each End User and MCT will be presented with a copy of this agreement and each individual will agree that their use of the Licensed Content will be subject to these license terms prior to their accessing the Licensed Content. Each individual will be required to denote their acceptance of the EULA in a manner that is enforceable under local law prior to their accessing the Licensed Content, 3. for all training sessions, you will only use qualified MCTs who hold the applicable competency to teach the particular MOC Course that is the subject of the training session, 4. you will not alter or remove any copyright or other protective notices contained in the Licensed Content, 5. you will remove and irretrievably delete all Licensed Content from all Classroom Devices and servers at the end of each training session, 6. you will only provide access to the Licensed Content to End Users and MCTs, 7. you will only provide access to the Trainer Content to MCTs, and 8. any Licensed Content installed for use during a training session will be done in accordance with the applicable classroom set-up guide. c. If you are an End User: You may use the Licensed Content solely for your personal training use. If the Licensed Content is in digital format, for each license you acquire you may (i) install one (1) copy of the Licensed Content in the form provided to you on one (1) Personal Device and install another copy on another Personal Device as a backup copy, which may be used only to reinstall the Licensed Content; or (ii) print one (1) copy of the Licensed Content. You may not install or use a copy of the Licensed Content on a device you do not own or control.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012


3.

d. If you are a MCT. i. For each license you acquire, you may use the Licensed Content solely to prepare and deliver an Authorized Training Session or Private Training Session. For each license you acquire, you may install and use one (1) copy of the Licensed Content in the form provided to you on one (1) Personal Device and install one (1) additional copy on another Personal Device as a backup copy, which may be used only to reinstall the Licensed Content. You may not install or use a copy of the Licensed Content on a device you do not own or control. ii.

Use of Instructional Components in Trainer Content. You may customize, in accordance with the most recent version of the MCT Agreement, those portions of the Trainer Content that are logically associated with instruction of a training session. If you elect to exercise the foregoing rights, you agree: (a) that any of these customizations will only be used for providing a training session, (b) any customizations will comply with the terms and conditions for Modified Training Sessions and Supplemental Materials in the most recent version of the MCT agreement and with this agreement. For clarity, any use of customize refers only to changing the order of slides and content, and/or not using all the slides or content, it does not mean changing or modifying any slide or content.

2.2 Separation of Components. The Licensed Content components are licensed as a single unit and you may not separate the components and install them on different devices.

2.3 Reproduction/Redistribution Licensed Content. Except as expressly provided in the applicable installation and use rights above, you may not reproduce or distribute the Licensed Content or any portion thereof (including any permitted modifications) to any third parties without the express written permission of Microsoft.

2.4 Third Party Programs. The Licensed Content may contain third party programs or services. These license terms will apply to your use of those third party programs or services, unless other terms accompany those programs and services. 2.5 Additional Terms. Some Licensed Content may contain components with additional terms, conditions, and licenses regarding its use. Any non-conflicting terms in those conditions and licenses also apply to that respective component and supplements the terms described in this Agreement.

PRE-RELEASE VERSIONS. If the Licensed Content is a pre-release (beta) version, in addition to the other provisions in this agreement, then these terms also apply: a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not contain the same information and/or work the way a final version of the Licensed Content will. We may change it for the final version. We also may not release a final version. Microsoft is under no obligation to provide you with any further content, including the final release version of the Licensed Content.

b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, either directly or through its third party designee, you give to Microsoft without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software, Microsoft product, or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software, technologies, or products to third parties because we include your feedback in them. These rights

MCT USE ONLY. STUDENT USE PROHIBITED


vii

BETA COURSEWARE EXPIRES 11/2012

Querying Microsoft SQL Server 2012

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

viii

Querying Microsoft SQL Server 2012

Acknowledgements

Microsoft Learning would like to acknowledge and thank the following for their contribution towards developing this title. Their effort at various stages in the development has ensured that you have a good classroom experience.

Design and Development


Chris Randall Author

This course was designed and developed by SolidQ. Solid Q is a global provider of consulting, mentoring and training services for Microsoft Data Management, Business Intelligence and Collaboration platforms.

Chris Randall is Director of Training, USA for SolidQ. He has worked with SQL Server since 1996, as a trainer, consultant and speaker. Chris has contributed content to courses on T-SQL, SSIS and BI Architecture, has taught thousands of students in classes and at conferences worldwide, including SQL PASS, SQL Saturday and several conferences for Microsoft Certified Trainers. Chris has recently consulted with a large global nonprofit enterprise on integrating with the Microsoft SharePoint and BI stack, and has guided the adoption of SQL Server Analysis Services and Reporting Services into the products of an independent software vendor. He holds the MCT and MCITP certifications for the SQL Server 2008 portfolio.

Grega Jerki Author

Grega Jerki is an independent consultant, mentor and trainer working for SolidQ. For last 10 years, he has been developing, architecting and managing different projects focusing on data warehousing, MDM, data integration, analytical / planning solutions and predictive analytics mostly with Microsoft technology. He invented and was lead architect for a predefined business intelligence solution on top of ERP Microsoft Dynamics NAV BI4Dynamics. The solution is now used worldwide by more than 150+ clients and got two awards by Microsoft for best business intelligence solution for CEE region.

Grega also manages the leading business intelligence consulting company in Slovenia called IN516HT and is a regular speaker at different SQL and business intelligence conferences.

Itzik Ben-Gan Subject Matter Expert

Itzik Ben-Gan is a Mentor and Co-Founder of SolidQ. A SQL Server Microsoft MVP (Most Valuable Professional) since 1999, Itzik has delivered numerous training events around the world focused on T-SQL Querying, Query Tuning and Programming. Itzik is the author of several books including T-SQL Fundamentals, Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions, and others. He has written many articles for SQL Server Pro as well as articles and whitepapers for MSDN. Itzik's speaking activities include major community events around the world such as TechEd and SQL PASS. Itzik is the author of SolidQ's Advanced T-SQL Querying, Programming and Tuning course along with being a primary resource within the company for their T-SQL related activities.

Technical Review
Chris Barker Technical Reviewer

Chris Barker is an MCT working in the New Zealand market and currently employed as a staff trainer at Auldhouse, one of New Zealands major CPLS training centers in Wellington. Chris background includes programming from the early 1970shis first program was written in assembly language and debugged in binary (literally)! While focusing training on programming (mostly .NET) and databases (mostly Microsoft SQL Server) Chris has also been an infrastructure trainer and has both Novell and Microsoft networking qualifications.

MCT USE ONLY. STUDENT USE PROHIBITED


ix

BETA COURSEWARE EXPIRES 11/2012

Querying Microsoft SQL Server 2012

Contents
Module 1: Introduction to Microsoft SQL Server 2012
Lesson 1: Introducing Microsoft SQL Server 2012 Lesson 2: Getting Started with SQL Server Management Studio Lab: Working with SQL Server 2012 Tools 1-3 1-10 1-20

Module 2: Getting Started with SQL Azure


Lesson 1: Overview of SQL Azure Lesson 2: Working with SQL Azure 2-3 2-8

Module 3: Introduction to T-SQL Querying


Lesson 1: Introducing T-SQL Lesson 2: Understanding Sets Lesson 3: Understanding Predicate Logic Lesson 4: Understanding the Logical Order of Operations in SELECT statements Lab: Introduction to T-SQL Querying 3-3 3-15 3-18 3-21 3-29

Module 4: Writing SELECT Queries


Lesson 1: Writing Simple SELECT Statements Lesson 2: Eliminating Duplicates with DISTINCT Lesson 3: Using Column and Table Aliases Lesson 4: Writing Simple CASE Expressions Lab: Writing Basic SELECT Statements 4-3 4-10 4-18 4-25 4-30

Module 5: Querying Multiple Tables


Lesson 1: Understanding Joins Lesson 2: Querying with Inner Joins Lesson 3: Querying with Outer Joins Lesson 4: Querying with Cross Joins and Self-Joins Lab: Querying Multiple Tables 5-3 5-11 5-17 5-23 5-33

Module 6: Sorting and Filtering Data


Lesson 1: Sorting Data Lesson 2: Filtering Data with Predicates Lesson 3: Filtering with TOP and OFFSET-FETCH Lesson 4: Working with Unknown Values Lab: Sorting and Filtering Data 6-3 6-10 6-17 6-24 6-29

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

Querying Microsoft SQL Server 2012

Module 7: Working with SQL Server 2012 Data Types


Lesson 1: Introducing SQL Server 2012 Data Types Lesson 2: Working with Character Data Lesson 3: Working with Date and Time Data Lab: Working with SQL Server 2012 Data Types 7-3 7-15 7-25 7-34

Module 8: Using Built-In Functions


Lesson 1: Writing Queries with Built-In Functions Lesson 2: Using Conversion Functions Lesson 3: Using Logical Functions Lesson 4: Using Functions to Work with NULL Lab: Using Built-In Functions 8-3 8-11 8-20 8-25 8-30

Module 9: Grouping and Aggregating Data


Lesson 1: Using Aggregate Functions Lesson 2: Using the GROUP BY Clause Lesson 3: Filtering Groups with the HAVING Clause Lab: Grouping and Aggregating Data 9-3 9-13 9-21 9-26

Module 10: Using Subqueries


Lesson 1: Writing Self-Contained Subqueries Lesson 2: Writing Correlated Subqueries Lesson 3: Using the EXISTS Predicate with Subqueries Lab: Using Subqueries 10-3 10-10 10-15 10-20

Module 11: Using Table Expressions


Lesson 1: Using Derived Tables Lesson 2: Using Common Table Expressions Lesson 3: Using Views Lesson 4: Using Inline Table-Valued Functions Lab: Using Table Expressions 11-3 11-14 11-18 11-24 11-29

Module 12: Using Set Operators


Lesson 1: Writing Queries with the UNION Operator Lesson 2: Using EXCEPT and INTERSECT Lesson 3: Using APPLY Lab: Using Set Operators 12-3 12-9 12-15 12-23

MCT USE ONLY. STUDENT USE PROHIBITED


xi

BETA COURSEWARE EXPIRES 11/2012

Querying Microsoft SQL Server 2012

Module 13: Using Window Ranking, Offset and Aggregate Functions


Lesson 1: Creating Windows with OVER Lesson 2: Exploring Window Functions Lab: Using Window Ranking, Offset and Aggregate Functions 13-3 13-15 13-26

Module 14: Pivoting and Grouping Sets


Lesson 1: Writing Queries with PIVOT and UNPIVOT Lesson 2: Working with Grouping Sets Lab: Pivoting and Grouping Sets 14-3 14-10 14-18

Module 15: Querying SQL Server Metadata


Lesson 1: Querying System Catalog Views and Functions Lesson 2: Executing System Stored Procedures Lesson 3: Querying Dynamic Management Objects Lab: Querying SQL Server Metadata 15-3 15-11 15-19 15-25

Module 16: Executing Stored Procedures


Lesson 1: Querying Data with Stored Procedures Lesson 2: Passing Parameters to Stored Procedures Lesson 3: Creating Simple Stored Procedures Lesson 4: Working with Dynamic SQL Lab: Executing Stored Procedures 16-3 16-7 16-12 16-17 16-23

Module 17: Programming with T-SQL


Lesson 1: T-SQL Programming Elements Lesson 2: Controlling Program Flow Lab: Programming with T-SQL 17-3 17-10 17-16

Module 18: Implementing Error Handling


Lesson 1: Using TRY / CATCH Blocks Lesson 2: Working with Error Information Lab: Implementing Error Handling 18-3 18-7 18-13

Module 19: Implementing Transactions


Lesson 1: Transactions and the Database Engine Lesson 2: Controlling Transactions Lab: Implementing Transactions 19-3 19-10 19-18

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

xii

Querying Microsoft SQL Server 2012

Module 20: Improving Query Performance


Lesson 1: Factors in Query Performance Lesson 2: Displaying Query Performance Data Lab: Improving Query Performance 20-3 20-16 20-25

Appendix C: Writing Specialized Queries


Lesson 1: Working with Full-text Data Lesson 2: Querying Full-text Data Lesson 3: Working with XML Data Lesson 4: Converting Query Results to XML with FOR XML Lesson 5: Querying XML Data with XQuery Lab: Writing Specialized Queries C-3 C-6 C-12 C-17 C-33 C-42

Appendix: Lab Answer Keys


Module 1 Lab: Working with SQL Server 2012 Tools L1-1 Module 3 Lab: Introduction to T-SQL Querying L3-7 Module 4 Lab: Writing Basic SELECT Statements L4-11 Module 5 Lab: Querying Multiple Tables L5-21 Module 6 Lab: Filtering and Sorting Data L6-29 Module 7 Lab: Working with SQL Server Data Types L7-37 Module 8 Lab: Using Built-In Functions L8-47 Module 9 Lab: Grouping and Aggregating Data L9-55 Module 10 Lab: Using Subqueries L10-65 Module 11 Lab: Using Table Expressions L11-73 Module 12 Lab: Using Set Operators L12-85 Module 13 Lab: Using Window Ranking, Offset and Aggregate Functions L13-95 Module 14 Lab: Pivoting and Grouping Sets L14-103 Module 15 Lab: Querying SQL Server Metadata L15-113 Module 16 Lab: Executing Stored Procedures L16-119 Module 17 Lab: Programming with T-SQL L17-129 Module 18 Lab: Implementing Error Handling L18-139 Module 19 Lab: Implementing Transactions L19-147 Module 20 Lab: Improving Query Performance L20-153 Appendix C Lab: Writing Specialized Queries LC-159

MCT USE ONLY. STUDENT USE PROHIBITED


i

BETA COURSEWARE EXPIRES 11/2012

About This Course

About This Course


Course Description
This 5-day instructor led course provides students with the technical skills required to write basic Transact-SQL

This section provides you with a brief description of the course, audience, suggested prerequisites, and course objectives.

queries for Microsoft SQL Server 2012. This course is the foundation for all SQL Server-related disciplines; namely, Database Administration, Database Development and Business Intelligence. This course helps people prepare for exam 70-461. Many of the exercises in this course are SQL Azure enabled. The Beta version of this course (10774AB) utilizes pre-release software in the virtual machine for the labs.

Audience
taking the exam; namely, report writers, business analysts and client application developers.

This course is intended for Database Administrators, Database Developers, and Business Intelligence professionals.

The course will very likely be well attended by SQL power users who arent necessarily database-focused or plan on

Student Prerequisites
This course requires that you meet the following prerequisites: Working knowledge of relational databases. Basic knowledge of the Microsoft Windows operating system and its core functionality.

Course Objectives
After completing this course, students will be able to: Write SELECT Queries Query Multiple Tables Use Built-In Functions Use Subqueries Execute Stored Procedures Use Set Operators Implement Error Handling Implementing Transactions Use Table Expressions Sort and Filter Data Use Window Ranking, Offset and Aggregate Functions Query SQL Server Metadata Program with T-SQL Improve Query Performance

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

ii

About This Course

Course Outline
This section provides an outline of the course: Module 1, Introduction to Microsoft SQL Server 2012" Module 2, Getting Started with SQL Azure" Module 3, Introduction to T-SQL Querying" Module 4, Writing SELECT Queries" Module 5, Querying Multiple Tables Module 6, Sorting and Filtering Data Module 7, Working with SQL Server 2012 Data Types Module 8, Using Built-In Functions Module 9, Grouping and Aggregating Data Module 10, Using Subqueries Module 11, Using Table Expressions Module 12, Using Set Operators Module 13, Using Window Ranking, Offset and Aggregate Functions Module 14, Pivoting and Grouping Sites Module 15, Querying SQL Server Metadata Module 16, Executing Stored Procedures Module 17, Programming with T-SQL Module 18, Implementing Error Handling Module 19, Implementing Transactions Module 20, Improving Query Performance

MCT USE ONLY. STUDENT USE PROHIBITED


iii

BETA COURSEWARE EXPIRES 11/2012

Ab bout This Course

Cours se Mate erials


Th he following materials m are in ncluded with your kit: Course Handbook A su uccinct classroom learning g guide that prov vides all the cr ritical technical information n in a crisp, tig ghtly-focused format, f which is just right fo or an effective in-class learnin ng experience. .

Lesson ns: Guide you through t the le earning object ives and provi de the key points that are critical to the suc ccess of the in-class learning experience. Labs: Provide P a real-world, hands-on platform fo or you to apply y the knowled dge and skills le earned in the module. m Modul le Reviews an nd Takeaways s: Provide impr roved on-the-j job reference material to bo oost knowle edge and skills s retention. Lab An nswer Keys: Provide step-by y-step lab solu ution guidance e at your finge ertips when its s needed d.

Course e Companion Content on the t http://ww ww.microsoft.c com/learning g/companionm moc/ Site: Se earchable, easy y-to-navigate digital content t with integrate ed premium on n-line resource es designe ed to suppleme ent the Course e Handbook. Fo or this Prerele ease Coursewa are on Prerele ease
Softwa are:

Th he Companion Content will be published wh hen the final c course is released.

Stu udents who at ttend the prerelease classes c can download t the Companion Content whe en the fin nal course is rel leased.

Modules: Include co ompanion cont tent, such as q questions and answers, detai iled demo step ps and additio onal reading lin nks, for each le esson. Additio nally, they include Lab Revie ew questions a and answer rs and Module e Reviews and Takeaways T sec ctions, which c contain the rev view questions s and answer rs, best practices, common is ssues and trou ubleshooting ti ips with answe ers, and real-w world issues and a scenarios with answers.

Resour rces: Include well-categorize w ed additional r resources that give you imm mediate access to the most up-to-date u premium content t on TechNet, MSDN, Micr rosoft Press.

Studen nt Course files on the http: ://www.micro osoft.com/lea arning/compa anionmoc/ Sit te: Include es the Allfiles.e exe, a self-extra acting executa able file that co ontains all the e files required for the labs an nd demonstrations.

Course eva aluation At the t end of the course, you w will have the op pportunity to complete an o online evaluation to provide fee edback on the course, trainin ng facility, and d instructor.

To o provide additional comme ents or feedbac ck on the cour rse, send e-ma ail to support@ @mscoursewar re.com. To o inquire abou ut the Microsoft Certification n Program, sen nd e-mail to m mcphelp@micr rosoft.com.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

iv

About This Course

Virtual Machine Environment


This section provides the information for setting up the classroom environment to support the business scenario of the course.

Virtual Machine Configuration


In this course, you will use Microsoft Hyper-V to perform the labs. The following table shows the role of each virtual machine used in this course: Virtual machine 10774A-MIA-DC1 10774A-MIA-SQL1 Role Domain Controller SQL Server VM for Modules 1-20

Software Configuration
The following software is installed on each VM:

Microsoft SQL Server 2012 RC0 (on the SQL Server VM)

Course Files

There are files associated with the labs in this course. The lab files are located in the folder F:\10774A_Labs on the student computers.

Classroom Setup
Each classroom computer will have the same virtual machine configured in the same way.

Course Hardware Level

To ensure a satisfactory student experience, Microsoft Learning requires a minimum equipment configuration for trainer and student computers in all Microsoft Certified Partner for Learning Solutions (CPLS) classrooms in which Official Microsoft Learning Product courseware are taught. This course requires hardware level 6.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-1

Module 1
Introduction to Microsoft SQL Server 2012
Contents:
Lesson 1: Introducing Microsoft SQL Server 2012 Lesson 2: Getting Started with SQL Server Management Studio Lab: Working with SQL Server 2012 Tools 1-3 1-10 1-20

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-2 Introduction n to Microsoft SQL Se erver 2012

Module Over rview

Befo ore you begin to learn how to t write querie es with SQL Se erver 2012, it is s useful to und derstand the o overall SQL L Server databa ase platform, including its ba asic architectu ure, the various s editions available for SQL S Server 2012, and the too ols a query writ ter will use. Th his module will l also prepare you to use SQ QL Server Man nagement Stud dio, SQL Serve er's primary de evelopment an nd administrati ion tool, to connect to SQL S Server instances and crea ate, organize, and execute queries. q

Obj jectives
Afte er completing this module, you y will be able to: Describe the architecture and editions of SQL Server 20 012 Work with SQ QL Server Management Stud dio

MCT USE ONLY. STUDENT USE PROHIBITED


1-3

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Lesson n1

Introd ducing Microso oft SQL L Server r 2012

In n this lesson, yo ou will learn about the basic c architecture a and concepts of Microsoft S SQL Server 201 12. You will w learn how in nstances, services, and datab bases interact, which edition ns of SQL Serve er 2012 are ava ailable, s are structure what w their distin nguishing features are, and how h databases ed. This will help prepare you u to be egin working with w SQL Serve er queries in upcoming mod dules.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe th he basic archite ecture of SQL Server. Describe th he versions of SQL S Server. Describe th he editions of SQL S Server. Describe th he role and stru ucture of SQL Server databa ses.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-4 Introduction n to Microsoft SQL Se erver 2012

SQ QL Server Architectur A re

This s topic will intr roduce you to the basic elem ments that mak ke up SQL Serv ver 2012. While there are many com mponents that ship with SQL Server 2012, this t course foc cuses on writin ng queries aga ainst the datab base eng gine. Therefore e, this lesson will w similarly foc cus on those e elements of SQ QL Server 2012 that you will most freq quently encoun nter when writ ting queries.

Ser rvices
In Windows, W services are applica ations that start without use er interaction, t typically at com mputer startup p. Whe en SQL Server is installed, multiple services are set up on n the compute er. These include some or all l of the following, dep pending on op ptions chosen during d installa ation: SQL Server 20 012 database engine, e which is responsible for executing commands su ubmitted in Transact-SQL L, or T-SQL, lan nguage, databa ase manageme ent, memory a and disk alloca ation, and othe er core features of SQL Server r SQL Server Ag gent, which is responsible fo or executing sc cheduled jobs,, monitoring th he system for defined alert conditions, an nd other admin nistrative tasks s Business intel lligence compo onents, which include SQL S Server Reportin ng Services, SQ QL Server Analysis Services, and SQL Server Int tegration Serv vices

A myriad m of other r services and support s applic cations may be e installed whe en SQL Server is set up. As a query writ ter, you will primarily be inte eracting with the SQL Server 2012 databas se engine, whic ch we will refe er to simply as SQL Server.

Instances

The basic unit of installation i and d program exe ecution for SQ QL Server is an instance. An in nstance is a co opy of the SQLSERVR.EXE E executable program, p which h runs as a Wi ndows service e. Logically, an instance repre esents the programs and d resource allocations that su upport a single e copy of SQL Server running on a compu uter, such h as memory, configuration files, and CPU. Multiple inst ances of SQL S Server may be e installed side-bylated side e on a single co omputer, whet ther the comp puter is a physi ical or a virtual server. Each instance is isol from m other instances on the sam me computer, including disk k files used, sec curity permissions, and resou urces allocated. The exc ception to this is shared com mponents such as manageme ent tools and d documentation.

MCT USE ONLY. STUDENT USE PROHIBITED


1-5

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

One of the instances may be set up as the default instance, which means you will access it using only the name of the host computer. All other instances on the same computer must be named instances, which you will access using a combination of the host name and the instance name. Note You will work with instance names in a later lesson in this module.

It is important to understand that an instance of SQL Server, as an installed copy of the database engine, is a container for databases. An instance can contain one or many databases. Logically, databases exist a level down from instances in a hierarchy of SQL Server objects. A database cannot span multiple instances.

Tools

SQL Server ships with a number of tools to manage, develop with and query the database engine. You will find shortcuts to many of these tools on the Windows Start menu in the subfolders for Microsoft SQL Server 2012. In this course, you will primarily work with SQL Server Management Studio, or SSMS. SSMS is an integrated management, development, and querying application with many features for exploring and working with your databases. Other tools you may encounter include: SQLCMD, a command-line client that allows you to submit T-SQL commands as an alternative to using the graphical SSMS application.

SQL Server Configuration Manager, which while primarily a tool for administrators, also includes features useful for managing SQL Server software installed on client machines, such as the ability to create and manage aliases to SQL Servers. SQL Server Installation Center, which provides the ability to add, remove, and modify SQL Server program features, if you have permission to do so.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-6 Introduction n to Microsoft SQL Se erver 2012

SQ QL Server Versions V

SQL L Server 2012 is only the late est version in th he history of S SQL Server dev velopment. Originally develo oped for the t OS/2 oper rating system (versions ( 1.0 and 1.1), versio ns 4.21 and later of SQL Ser rver moved to the Win ndows operatin ng system. SQL L Server's engin ne received a major rewrite for version 7.0 0, and subsequ uent versions h have continued d to imp prove and extend SQL Server r's capabilities from the work kgroup to the largest enterp prises. Note Altho ough its name e might sugges st it, SQL Serve er 2008 R2 is n not a service pack for SQL Server 2008. 2 It is an in ndependent ve ersion (version n number 10.5) ) with enhance ed multiserver management capab bilities as well as a new busine ess intelligence e features. ed with any ve ersions of SQL Server prior to o SQL Server 2 2012? Question: Have you worke

MCT USE ONLY. STUDENT USE PROHIBITED


1-7

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

SQL Server Editions

SQ QL Server ship ps in several ed ditions that pro ovide different t feature sets t targeting different business sc cenarios. In the e SQL Server 2012 2 release, th he number of editions has b been streamlined from previo ous ve ersions. The main editions ar re: Enterprise, which is the flagship f edition. It contains a all of SQL Serv ver 2012's features, including g business int telligence serv vices and support for virtuali zation. Standard, which w includes s the core data abase engine a as well as core e reporting and d analytics capabilities. However, it supports s fewer r processor cor res and does n not offer all of f the availabilit ty, security, an nd data wareho ousing feature es found in the e Enterprise ed dition.

Business In ntelligence, which w is a new edition. It prov vides the core database eng gine, full report ting ce services. Ho and analytics capabilities, , and full busin ness intelligenc owever, like the Standard ed dition, it supports fe ewer processor r cores and does not offer al l of the availab bility, security, , and data warehousin ng features.

QL Server 2012 2 also offers ot ther editions, such s as Paralle el Data Wareh ouse, Web, De eveloper, and Express, SQ ea ach targeted fo or specific use e cases. Th his course uses s core databas se engine featu ures found in a all editions. For More e Information n See the SQL L Server 2012 Editions guide e at http://ww ww.microsoft.co om/sqlserver/e en/us/future-e editions/sql20 12-editions.aspx Question: What W edition of o SQL Server 2012 are you o or will you be using in your organizatio on?

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-8 Introduction n to Microsoft SQL Se erver 2012

SQ QL Server Databases D

Databases in SQL Server are con ntainers for da ata and objects s, including tables, views, sto ored procedures, user e logical entity r accounts, and d other manag gement object ts. A SQL Serve er database is always a single y, backed by multiple physical file es.

Whe en client applications send requests r to the e database eng gine as T-SQL statements, SQ QL Server perf forms all file, f memory, and a processor utilization on the t client's be half. Clients ne ever directly access database e files, unlike in desktop database applications. SQL L Server suppo orts two types of o databases: system s and use er. TSQL2012, the sample da atabase you w will be usin ng to write que eries, is a user database. SQL L Server's syste em databases i include: master, the sy ystem configuration databas se msdb, the configuration da atabase for the e SQL Server A Agent service a nd other syste em services model, the te emplate for new user databases

tempdb, used d by the datab base engine to store tempora ary data such a as work tables s. This database is dropped and recreated eac ch time SQL Se erver restarts - never store an nything you need to depend d on in it! Resource, a hidden system configuration database that t provides syst tem objects to other databas ses

Database adminis strators and de evelopers can create c user da atabases to hol ld data and ob bjects for app plications. You connect to a user u database to execute you ur queries. You u will need sec curity credenti ials to log in to SQL Serv ver and a database account with w permissio ons to access d data objects in the database. .

MCT USE ONLY. STUDENT USE PROHIBITED


1-9

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

About A the Course Sample Data abase

In n this course, most m of your queries will be written w agains st a sample dat tabase named TSQL2012. Th his da atabase is desi igned as a sma all, low-complexity database e suitable for le earning to write T-SQL quer ries. It co ontains several types of obje ects:

user-define ed schemas, wh hich are containers for table es and views (y you will learn a about schemas s later in this course) ) tables, whic ch relate to oth her tables via foreign f key co onstraints views, which display aggr regated inform mation

Th he TSQL2012 database d is mo odeled to resemble a sales-t tracking applic cation for a sm mall business. S Some of th he tables you will w use include e: Sales.Order rs, which stores data typically y found in the e header of an invoice (order r ID, customer ID, order date, etc.)

Sales.Order rDetails, which stores transac ction detail ab bout each orde er (parent orde er ID, product ID, unit price, etc.) Sales.Custo omers, which st tores information about cust tomers (comp pany name, con ntact details, e etc.)

HR.Employees, which stores information about the co ompany's emp ployees (name e, birthdate, hir re date, etc.)

Other O tables are e supplied to add a context to o these tables, such as additio onal product i information.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-10

Introductio on to Microsoft SQL Server 2012

Lesson 2

Getting Starte ed with SQL Se erver Ma anagem ment Stu udio

In th his lesson, you u will learn how w to use SQL Server S Manage ement Studio ( (SSMS) to conn nect to an inst tance of SQL S Server, exp plore the datab bases containe ed in the instan nce, and work k with script file es that contain n TSQL L queries.

Les sson Objecti ives


Afte er completing this lesson, yo ou will be able to: Use SSMS to connect to on-premises SQL L Server instan nces Explore a SQL L Server instan nce using Obje ect Explorer Create and or rganize script files Execute T-SQ QL queries Use Books On nline

MCT USE ONLY. STUDENT USE PROHIBITED


1-11

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Starting SSMS

SS SMS is an integ grated management, develo opment, and q querying applic cation with ma any features fo or ex xploring and working w with your y databases s. SSMS is base ed on the Visua al Studio shell. If you have ex xperience with h Visual Studio o, you will likely y feel comfort able with SSM MS. To o start SSMS, you y may: Use its shor rtcut on the Windows W Start menu m in the SQ QL Server 2012 subfolder. window. Enter its file ename, SSMS.E EXE, in a comm mand prompt w Type SSMS S in the Searc ch Programs an nd Files box.

By y default, SSMS will display a Connect to Server S dialog b box. Using this s box you can specify the ser rver (or in nstance) name and your secu urity credentials. If you use t he Options bu utton to access s the Connection Pr roperties tab, you y can also supply the data abase to which h you wish to c connect. Howe ever, you can e explore many m of SSMS's s features without initially co onnecting to a SQL Server in nstance, so you u may also can ncel the Connect to Serv ver box and co onnect to a ser rver later. ols, Once O SSMS is ru unning, you may m wish to exp plore some of its settings, su uch as those fo ound in the Too Options O box. SS SMS can be customized in many m ways, suc h as setting a default font, turning on line e nu umbers for scr ripts, and controlling the beh havior of SSMS S's many wind dows. For More e Information n See Books Online O at http:://msdn.microsoft.com/enus/library y/ms174173(v= =SQL.110).aspx x.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-12

Introductio on to Microsoft SQL Server 2012

Co onnecting to t SQL Ser rver

In order o to connect to an instan nce of SQL Serv ver, you need to specify sev eral items, no matter which tool you use to connec ct:

The name of the instance to o which you want w to connec ct, in the form hostname\instancenam me. For example, MIA-SQL\Pr roseware wou uld connect to o the Prosewar re instance on the Windows server named d MIA-SQL. If you y are connec cting to the de efault instance e, you may om mit the hostnam me. For SQL Azure, the server name n is a four-part name in t the form <hos st>.databas se.windows.net. The name of the database. If you do not specify a data base name, yo ou will be conn nected to the database designated as you ur account's de efault by the d database admi inistrator, or to o the master database if no o default has been b specifical lly assigned. In n SQL Azure, it t is important t to connect to the correct datab base since you may not chan nge connection ns between us er databases o once connecte ed. You must disc connect and re econnect to th he desired data abase.

The authentic cation mechan nism required by the server. This may be W Windows Authe entication, in w which your Window ws network credentials will be e passed to SQ QL Server (no e entry required), or SQL Serve er Authenticatio on, in which a username u and password for your account must be creat ted by a datab base administrator r (you enter them at connect tion time). SQ L Server Authe entication is th he only mechanism supported by y SQL Azure. Question: Which W authentic cation method d do you use t o log in to SQ QL Server in your organization? ?

MCT USE ONLY. STUDENT USE PROHIBITED


1-13

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Working W with w Object t Explorer

Object O Explorer r is a graphical tool for mana aging SQL Serv ver instances a and databases. . It is one of se everal SS SMS window panes p available e from the View w menu. Obje ect Explorer pro ovides direct interaction with most SQ QL Server data a objects, such as tables, view ws, and proced dures. Right-cl licking an obje ect, such as a table, will w display cont text-sensitive commands, c including query y-generators an nd script gene erators for obje ect de efinitions. ny operation performed p in SS SMS requires a appropriate pe ermissions gra anted by a Note An database administrator. a Being able to see an object or command does not nece essarily imply permission n to use the ob bject or issue the t command..

SQ QL Server query writers most commonly use Object Exp lorer to learn a about the stru ucture and definition of f the data obje ects they want t to use in their queries. For e example, to le earn the names s of columns in na ta able, you follow w these steps: 1. . 2. . 3. . 4. . 5. . Connect to the SQL Serve er, if necessary y. Expand the e Databases folder to expose e the list of dat tabases. Expand the e relevant database to expose the Tables fo older. Expand the e Tables folder to view the lis st of tables in t the database.

Locate the table you are interested in and a expand it t to find the Co lumns folder. The Columns f folder will display the names, da ata types and other o informat tion about the e columns that t make up the table. You can even drag the na ame of a datab base, table, or column into t the query wind dow to have it entered and d avoid typing g it yourself. Note Selecting objects s in the Object t Explorer pan e does not cha ange any conn nections made in other o windows. .

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-14

Introductio on to Microsoft SQL Server 2012

Wo orking wit th Script Fi iles and Pr rojects

SSM MS allows you to t create and save T-SQL co ode in text files s, typically give en a .sql file ex xtension. Like o other Win ndows applicat tions that open n, edit, and sav ve files, SSMS provides acces ss to file mana agement throu ugh the File menu and d through stan ndard toolbar buttons. b In addition to dire ectly manipula ating individua al script files, S SMS provides a mechanism for initially sav ving groups of files tog gether and for r opening, saving, and closin ng them togeth her. This mech hanism uses se everal conceptual layers to work with T-SQL T script files and related d documents, and uses the S Solution Explo orer pan ne to display an nd control: Ob bject So olution Parent P None Descriptio on

Top-level container for r projects. Stor red as a text fil le with an .ssm mssln n, which refere ences components contained d within it. Ma ay extension contain multiple m projec cts. Displayed in Solution Exp plorer at the to op of the objec ct hierarchy. Containe er for T-SQL sc ripts (called qu ueries), stored database connectio on metadata, a and miscellane eous files. Stor red as a text fil le with an .s ssmssqlproj ex xtension, which h references co omponent scri ipts and othe er files.

Project

Solution

Sc cript

Project

T-SQL scr ript file with a .sql extension n. The core item m of work in SSMS.

The benefits to us sing scripts org ganized in proj jects and solut tions include t the ability to o open multiple script files s in SSMS at on nce. You can open o the soluti ion or project file from withi in SSMS or Windows Explore er. To create c a new solution, click the t File menu and a click New w Project. (Ther re is no New S Solution com mmand.) Assign n a name for the initial proje ect, its parent s solution, and w whether you w want the projec ct to be stored s in a sub bfolder below the t solution file in the locati ion you specify y. Click OK to create the par rent obje ects.

MCT USE ONLY. STUDENT USE PROHIBITED


1-15

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

To interact with Solution Explorer, open the pane (if necessary) from the View menu. To create a new script that will be stored as part of the project, right-click the Queries folder in the project and click New Query. Note Using the New Query toolbar button or the new query commands on the File menu will create a new script temporarily stored with the solution in the Miscellaneous Files folder. If you wish to move an existing open query document into a solution currently open in Solution Explorer, you will need to save the file. Then you can drag the query into the project tree to save it in the Queries folder. This will make a copy of the script file and place it into the solution.

It is important to remember to save the solution when exiting SSMS or opening another solution in order to preserve changes to the solution's file inventory. Saving a script using the Save toolbar button or the Save <Queryname>.sql command on the File menu will only save changes to the contents of the current script file. To save the entire solution and all its files, use the Save All command on the File menu or when prompted to save the .ssmssln and .ssmssqlproj files on exit.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-16

Introductio on to Microsoft SQL Server 2012

Exe ecuting Qu ueries

To execute e T-SQL L code in SSMS S, you first nee ed to open the e .sql file that c contains the qu ueries, or type your que ery into a new query window w. Then decide how much of f the code in th he script is to b be executed: Select the cod de you wish to o execute or If nothing is selected s SSMS will execute th he entire scrip pt, which is the e default behav vior.

Onc ce you have de ecided what yo ou wish to exe ecute, you can run the code by: Clicking the Execute E button n on the SSMS toolbar Clicking the Query Q menu, then clicking Ex xecute Query Pressing the F5 F key, the Alt+X keyboard shortcut, s or th he Ctrl+E keyb oard shortcut. .

By default, d SSMS will w display your results in a new pane of t the query wind dow. The locat tion and app pearance of the e results can be changed in the t Options bo ox accessible f from the Tools s menu. To tog ggle the display of the results and re eturn to a full-s screen T-SQL e editor, use the e Ctrl+R keybo oard shortcut. SSM MS provides sev veral formats for f the display y of query resu ults:

Grid, which is s a spreadsheet-like view of the t results, wit th row numbe ers and resizable columns. Yo ou can use Ctrl+D to o select this be efore executing g a query. Text, which is s a Windows Notepad-like N display that pad ds column wid dths. You can u use Ctrl+T to s select this before ex xecuting a que ery.

File, which allows you to directly save que ery results to a text file with an .rpt extens sion. Executing g the query will pro ompt for a loca ation for the re esults file. The e file may then be opened by y any applicati ion that can read text files, such h as Windows Notepad and SSMS itself. Yo ou can use Ctr rl+Shift+F to s select this before ex xecuting a que ery.

MCT USE ONLY. STUDENT USE PROHIBITED


1-17

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Using U Book ks Online

Bo ooks Online (o often abbreviated BOL) is the e product doc umentation fo or SQL Server. BOL includes help on SQ QL Server's arc chitecture and concepts, as well w as syntax reference for T T-SQL. BOL can be accessed from th he Help menu in SSMS. In a script s window, , context-sens itive help for T T-SQL keyword ds is available by se electing the ke eyword and pressing Shift+F1.

Bo ooks Online ca an be browsed d directly on Microsoft's M web bsite at http://msdn.microsoft.com/enus s/library/ms13 30214(v=SQL.1 110).aspx. Opti ionally, it can b be downloade ed and installed locally, then viewed in n the Help View w application installed i with SQL S Server and d client tools. Note Pre evious versions of SQL Serve er provided the e option to ins stall Books Online locally during SQ QL Server setup p. In SQL Serve er 2012, Books Online does n not ship with t the product installation n media, so it must be down nloaded and in nstalled separa ately from SQL L Server itself.

Th he first time Help is invoked, , you will be prompted to sp pecify whether r you wish to v view Books On nline co ontent online or o locally. This s setting may be b changed lat ter by using th he Help Library y Manager, loc cated in th he Windows St tart menu in th he SQL Server 2012 folder an nd the Docum mentation & Co ommunity subf folder.

Fo or detailed instructions on how to downlo oad, install, and d configure Bo ooks Online for local offline u use, see th he topic "Get Started S with Microsoft Books s Online for SQ QL Server" at h http://msdn.mi icrosoft.com/e enus s/library/ms16 66019(v=SQL.1 110).aspx.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-18

Introductio on to Microsoft SQL Server 2012

De emonstration: Introd ducing Mic crosoft SQL Server 2 2012

Dem monstration n Steps


1.
On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, click S SQL Server Mana agement Stud dio. In the Con nnect to Serve er window, typ pe Proseware in the Server Name text bo ox and click Co onnect. If the Object Explorer pane is not visible e, click View an nd click Objec ct Explorer. Expand the Databases D fold der to see the list l of database es. Expand the AdventureWo A rks2008R2 da atabase. Expand the Tables T folder. Expand the Sales.Custome er table. Expand the Columns C folder. Show the list of columns, an nd point out the data type i nformation fo or the Modified dDate column. .

2. 3. 4. 5. 6. 7. 8. 9.

If the Solutio on Explorer pa ane is not visib ble, click View and click Solu ution Explore er. It will be em mpty, initially.

10. Click the File menu, click New N , click Project 11. In the New Project P box, un nder Installed Templates, c click SQL Serve er Manageme ent Studio
Projects.

12. In the middle e pane, click SQ QL Server Scri ipts. 13. In the Name box, type Module 1 Demonstration. 14. In the Locatio on box, type or o browse to F:\10774A_Lab bs\10774A_01 1_PRJ. 15. Point out the solution name, then click OK O . 16. In the Solutio on Explorer pane, p right-click Queries, the en click New Q Query.

MCT USE ONLY. STUDENT USE PROHIBITED


1-19

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

17. Type the following T-SQL code:


USE AdventureWorks2008R2; GO SELECT CustomerID, AccountNumber FROM Sales.Customer;

18. Select the code and click Execute on the toolbar. 19. Point out the results pane. 20. Click File, and then click Save All. 21. Click File, and then click Close Solution.

22. Click File, click Recent Projects and Solutions, and then click Module 01 Demonstration.ssmssln. 23. Point out the Solution Explorer pane.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-20

Introductio on to Microsoft SQL Server 2012

Lab: Working W with SQ QL Serv ver 2012 2 Tools

Lab b Setup
For this lab, you will w use the ava ailable virtual machine m enviro onment. Befor re you begin the lab, you mu ust mplete the follo owing steps: com

1. 2. 3.

On the host computer, c click k Start, point to t Administra ative Tools, an nd click Hyper r-V Manager. Maximize the e Hyper-V Ma anager window w. If the virtual machine m 1077 74A-MIA-DC1 1 is not started : In the Virtual Machine es list, right-click 10774A-M MIA-DC1 and c click Start. Right-clic ck 10774A-MIA-DC1 and click Connect.

In the Virtual Machine e Connection window, wait until the Press CTRL+ALT+ +DELETE to log g on message appears, and then close the e Virtual Mach hine Connect tion window.

4.

If the virtual machine m 1077 74A-MIA-SQL1 is not started d: In the Virtual Machine es list, right-click 10774A-M MIA-SQL1 and d click Start. Right-clic ck 10774A-MIA-SQL1 and click c Connect .

In the Virtual Machine e Connection window, wait until the Press CTRL+ALT+ +DELETE to log g on message appears, and then close the e Virtual Mach hine Connect tion window.

5. 6.

In Virtual Ma achine Conne ection window w, click the Rev vert toolbar ico on. If you are pro ompted to con nfirm that you want to revert t, click Revert. Wait for the r revert action to complete.

MCT USE ONLY. STUDENT USE PROHIBITED


1-21

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

7.

If you are not already logged on:

In the Virtual Machine Connection window, click the Ctrl-Alt-Delete menu item on the Action menu. Click Switch User, and then click Other User. Log on using the following credentials: User name: AdventureWorks\Administrator Password: Pa$$w0rd

8. 9.

In the Virtual Machine Connection window, click Full Screen Mode on the View menu.

If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.

Lab Scenario

The Adventure Works Cycles Bicycle Manufacturing Company has adopted SQL Server 2012 as its relational database management system of choice. You are an information worker who will be required to find and retrieve business data from several SQL Server databases. In this lab, you will begin to explore the new environment and become acquainted with the tools for querying SQL Server.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-22

Introduction to Microsoft SQL Server 2012

Exercise 1: Working with SQL Server Management Studio


Scenario
The first exercise will focus on getting familiar with the SQL Server development tool. The main tasks for this exercise are as follows:

1. 2.

Open Microsoft SQL Server Management Studio. Configure the editor settings.

X Task 1: Open Microsoft SQL Server Management Studio

Using SQL Server Management Studio (SSMS), connect to Proseware using Windows authentication (if you are connecting to an on-premises instance of SQL Server) or SQL Server authentication (if you are using SQL Azure). Close the Object Explorer and Solution Explorer windows. Using the View menu, show the Object Explorer and Solution Explorer windows in SSMS.

X Task 2: Configure the editor settings


On the Tools menu, choose Options to open the Options window in SSMS and change the font size to 14 for the text editor. Change several additional settings in the Options window: Disable IntelliSense. Change the tab size to 6 spaces for T-SQL. Enable the option to include column headers when copying the result from the grid. Look under Query Results, SQL Server, Results to Grid for the check box Include column headers when copying or saving the results.

Results: After this exercise, you should be able to open SSMS and configure different editor settings.

MCT USE ONLY. STUDENT USE PROHIBITED


1-23

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 2: Creating and Organizing T-SQL Scripts


Scenario

Usually you will organize your T-SQL code in multiple query files inside one project. You will practice how to create a project and add different query files to it. The main tasks for this exercise are as follows:

1. 2.

Create a project. Create a new query file and add it to the project.

X Task 1: Create a project


Add a new query file to the created project and name it MyFirstQueryFile.sql. Save the project and the query file by clicking the Save All option.

Create a new project called MyFirstProject and store it in the folder F:\10774A_Labs\10774A_01_PRJ.

X Task 2: Add an additional query file


Add an additional query file called MySecondQueryFile.sql to the created project and save it. Open Windows Explorer, navigate to the project folder, and observe the created files in the file system.

Back in SSMS, using Solution Explorer, remove the query file MySecondQueryFile.sql from the created project. (Choose the Remove option, not Delete.) Again look in the file system. Is the file MySecondQueryFile.sql still there? Now back in SSMS, remove the file MyFirstQueryFile.sql and this time choose the Delete option. Observe the files in Windows Explorer. What is different this time?

X Task 3: Reopen the created project


Save the project, close SSMS, reopen SSMS, and open the project MyFirstProject.

Drag and drop the query file MySecondQueryFile.sql from Windows Explorer to the Queries folder under the project MyFirstProject in Solution Explorer. (Note: If the Solution Explorer window is not visible, enable it as you did in exercise 1). Save the project.

Results: After this exercise, you should have a basic understanding of how to create a project in SSMS and add query files to it.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

1-24

Introduction to Microsoft SQL Server 2012

Exercise 3: Using Books Online


Scenario
To be effective in your training and exercises to come, you will practice how to use Books Online to efficiently check for T-SQL syntax. The main tasks for this exercise are as follows:

1. 2. 3. 4. 5.

Launch Books Online from the Windows Start menu. Configure offline usage. Search for the SELECT statements syntax. Copy some sample code, paste it into the SSMS query editor. Use SSMSs context-sensitive help.

X Task 1: Launch Books Online


Launch SQL Server Documentation (Books Online) from the Windows Start menu. Configure Books Online to use the local help (offline) option and not online help option.

X Task 2: Search for the SELECT syntax


Using the Index tab, find the syntax for the SELECT statement [SQL Server]. Browse the SELECT statements definition. Click the SELECT Examples (Transact-SQL) link under Reference in the See Also section.

Back in SSMS, create a new query file named MyThirdQueryFile.sql and add it to the project MyFirstProject. Copy and paste the first SELECT code sample from Books Online to the created query file.

X Task 3: Use context-sensitive help


Close Books Online. In the query file MyThirdQueryFile.sql, highlight the ORDER BY clause and open Books Online by pressing the F1 key. Browse the ORDER BY definition in Books Online. Save the project and close it.

Results: After this exercise, you should have an understanding how to open Books Online and use context-sensitive help.

MCT USE ONLY. STUDENT USE PROHIBITED


1-25

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Modu ule Revi iew

Review R Ques stions


1. 2. 3.
Can a SQL Server database be stored acro oss multiple in nstances? If no T-SQL co ode is selected d in a script window, which l ines will be run when you cl lick the Execut te button? What does a SQL Server Ma anagement Stu udio solution c contain?

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-1

Module 2
Getting Started with SQL Azure
Contents:
Lesson 1: Overview of SQL Azure Lesson 2: Working with SQL Azure 2-3 2-8

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-2 Getting Star rted with SQL Azure

Module Over rview

SQL L Azure is a clo oud-based database service from f Microsof ft. A part of Microsoft's Wind dows Azure plat tform-as-a-ser rvice solution, SQL Azure offe ers the databa ase manageme ent services of on-premises S SQL Serv ver without req quiring a local physical infrastructure. Just t as you can wr rite queries ag gainst on-prem mises SQL L Server, you will w also be able e to write mos st queries agai nst a database e hosted by SQ QL Azure. In th his module, yo ou will learn ho ow to set up an account, pro ovision a serve er, and create a database in S SQL Azure so that you will be prepared to perform m the lab exerc cises in this course either on a local virtual l mac chine or in a SQ QL Azure data abase.

Obj jectives
Afte er completing this module, you y will be able to: Describe the basic features of SQL Azure Create a free 90-day trial Windows W Azure e account Provision a SQ QL Azure serve er and configu ure its security Create a SQL Azure database and connec ct to it using lo ocal SQL Serve er tools

MCT USE ONLY. STUDENT USE PROHIBITED


2-3

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Lesson n1

Overv view of SQL Az zure

SQ QL Azure is the e database part of Microsoft t's cloud platfo orm, which pro ovides cost-eff fective scalabil lity, hi igh availability y, and reduced d management t overhead. SQ QL Azure can b be used to aug gment an existing onpremises SQL Se erver infrastructure or suppo ort new applic ations without t requiring loc cal database se ervers to be e set up. In n this lesson, yo ou will learn so ome core conc cepts supporti ng SQL Azure,, and some dis stinctions betw ween SQ QL Azure and on-premises SQL S Server. Thi is lesson is not t designed to b be a comprehe ensive treatme ent of SQ QL Azure; it is intended to provide a basic foundation fo or those who w will be writing queries agains st either cloud-based or on-premises SQL S Server dat tabases.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe th he role of SQL Azure compar red to on-prem mises SQL Serv ver. Describe ke ey differences between SQL Azure and on-premises edit tions of SQL Se erver.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-4 Getting Star rted with SQL Azure

Wh hat is SQL Azure?

SQL L Azure is the database d comp ponent of Microsoft's Windo ows Azure plat tform. SQL Azu ure is a rapidly ydeveloping toolse et, which at the e time of this writing w include es database management, re eporting, and data sync c services, with h import-export capabilities in developme nt. Note SQL Azure is a mov ving target. An ny information n in this modu ule was correct t at time of writing, but SQL Azure ma ay change with hout notice.

A go oal of SQL Azu ure is to provid de quickly prov visioned datab bases that scal e to meet the needs of a business. Another r goal is to rem move the need to manage ph hysical servers s, including the e operating sys stem, from m database ma anagement, which lets administrators prim marily focus on n the logical m management of f SQL Serv ver. In contrast t, in an on-pre emises deploym ment, administ trators focus i is split between the logical man nagement and d the physical management. m Note The abstraction of physical serve ers from logica al servers will b be a key factor r in differentiatin ng which featu ures of SQL Server are suppo orted by SQL A Azure. For exam mple, SQL Azure does not n support ac ccess to the server's file syste em, which mea ans that datab base creation stat tements that re eference local files on an on n-premises serv ver will need to be modified to run in SQL Azure. From m the perspective of the SQL Server query y writer, SQL A Azure operates much like a tr raditional onprem mise SQL Server, with a few key distinction ns, which will b be covered in t this lesson. Yo ou will be able to writ te SELECT quer ries against tab bles and views s, and invoke f functions and s stored procedures against data abases hosted in SQL Azure just j as you wo ould locally. For More In nformation Additional rea ading can be f found on the S SQL Azure Lan nding Page at http://ms sdn.microsoft.c com/en-us/lib brary/windowsa azure/gg6193 386.aspx.

MCT USE ONLY. STUDENT USE PROHIBITED


2-5

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Key K Concep pts in SQL Azure

Be eyond the rela ational databas se engine prov vided by SQL A Azure, it is nec cessary to understand the model be ehind the Azure platform so o that you can set up your ow wn account, provision a serv ver, and create e da atabases.

Th here is a relatio onship betwee en three core objects o in SQL L Azure: the acc count, the serv ver, and the da atabase. Azure A object Azure Accoun nt Descrip ption

Accounts are the un nit of subscript ion and billing g. All Azure act tivity is metere ed and irst create an a account, and t then add serve ers. An assigned to an account. You will fi Azure account may have zero or m more servers.

SQL Azure Se erver

SQL Azure servers, which w belong t to an account, are provisione ed and assigne ed a Domain Name Syste em (DNS) nam me, administrat tor accounts, a and firewall rules. SQL h zero or m more databases s created within. Azure servers may have SQL Azure database es, like databas ses in on-prem mises SQL Serve er, are contain ners for o such as s tables, views, functions, and d procedures, as well as user r data objects securit ty accounts. Unlike on-prem mises SQL Serve er, SQL Azure does not expo ose system m databases ot ther than mast ter.

SQL Azure Database

Th herefore, the process p of crea ating a SQL Az zure database begins at the a account level. You will learn how to es stablish an Azu ure account in the next lesso on. Note Du ue to the relati ionship betwee en account, se erver, and data abase, operatio ons that span databases or span servers (e.g., cross-d database quer ries, replication n, or other high availability e not supporte ed in SQL Azur re. Therefore, c careful evaluat tion of on-pre emises setups) are applications is needed before b migratin ng to SQL Azu ure.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-6 Getting Star rted with SQL Azure

Key Distincti ions Betwe een SQL Se erver Azur re and On-Premises SQL Serve er

As you y have learn ned, a goal of SQL S Azure is th he abstraction of logical dat tabase adminis stration from phy ysical. In SQL Azure, A Microsof ft administers physical hardw ware and stora age. Your orga anization's adm ministrators wil ll still manage security, imple ement databas ses, and create e database obj jects such as tables, view ws, and indexe es. However, th here are some key distinction ns between ho ow some of the ese tasks are perf formed in a SQ QL Azure envir ronment:

Ad dministrative task t Se erver-level sec curity account management m

On-Premises Login ns created at in nstance level, , mapped to W Windows accou unts or groups s Can choose c Windo ows Authentication and d/or SQL Serve er Authenticat ion for accou unt types and conn nections Firew walls managed on physical server usin ng ating system c commands, opera typically limited to opening up well-known w por rts Administrators hav ve access w range of to a wide moni itoring and oth her types of tools in order to o manage level resource usage. low-l Backup and restore e required for disaster recover ry.

SQ QL Azure

A Administrative accounts crea ated in Azure Mana agement Portal, no c concept of inst tance-level use er lo ogins

Configuring aut thentication mechanism m

S SQL Server Aut thentication only m mechanism sup ccess pported. All ac v via username/p password c combinations B By default, no access to SQL A Azure database e except throu ugh M Management P Portal. Specific c IP a addresses and ranges must b be a allowed to con nnect.

Fi irewall manage ement

Hardware and resource r management m

V Very limited ac ccess to server r-level information du ue to abstractio on m model. No sup pport for backu up a and restore.

MCT USE ONLY. STUDENT USE PROHIBITED


2-7

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

In addition, not all SQL Server database engine features are supported by SQL Azure, including multidatabase and multi-server capabilities. For More Information For information on what T-SQL statements are currently supported, see http://msdn.microsoft.com/en-us/library/windowsazure/ee336250.aspx. For more information on SQL Azure Security Administration, see http://msdn.microsoft.com/enus/library/windowsazure/ee336235.aspx .

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-8 Getting Star rted with SQL Azure

Lesson 2

Workin ng with h SQL Az zure

In th his lesson, you u will learn how w to create and d connect to a SQL Azure da atabase. In ord der to create a SQL Azure database yo ou will need to o sign up for a Windows Azu ure account an nd provision a SQL Azure ser rver. You u will learn how w to do this in this lesson.

Les sson Objecti ives


Afte er completing this lesson, yo ou will be able to: Sign up for a 90-day free tr rial Azure acco ount Provision a SQ QL Azure serve er Create a SQL Azure database using the Azure A Managem ment Portal Configure init tial security settings Connect to SQ QL Azure using g SSMS

MCT USE ONLY. STUDENT USE PROHIBITED


2-9

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Signing Up p for a Win ndows Azu ure Accoun nt

Ea arlier in this module you learned that a SQ QL Azure datab base is contain ned by a SQL A Azure server an nd that a SQL Azure ser rver is associat ted with a single Windows A Azure account. Therefore, in order to begin n the process of creat ting SQL Azure e databases, yo ou will need to o create a Win ndows Azure account. For the pu urposes of this s course, you will w learn how to take advant tage of Micros soft's free 90-d day trial accou unt. Note Th here are severa al options for creating c Windo ows Azure acc ounts, includin ng via an MSDN sub bscription. See e http://www.w windowsazure.c com/en-us/pricing/member roffers/msd dn-benefits.

To create a trial t Window ws Azure ac ccount:


1. . 2. . 3. . 4. . In a web br rowser, navigate to http://ww ww.windowsaz zure.com/en-u us/pricing/free e-trial/ Click sign up u now.

Sign in to Windows W Live using u an existing account, o r create a new w Windows Live e account if yo ou do not already y have one.

You will the en begin the process p of supp plying billing i nformation, w which will be us sed to convert t your free trial int to a paid acco ount at the end d of the 90-day y trial period.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-10 Getting Started with SQL Azure e

Pro ovide Billin ng Information

To create c a trial account, you will need to sup pply billing info ormation, inclu uding a credit card number and a mob bile phone num mber. To go th hrough the billing steps: 1. 2. 3. 4. Supply a mob bile phone num mber and click k Send text m message. Micro osoft will send a verification code to the mobile e number you supply. Enter the veri ification code sent to your mobile m number r and click Ver rify code. Whe en successful, click the arrow to the t right of the screen. When promp pted, supply yo our credit card information, a and click to ag gree to the ter rms of the Subscription Agreement A an nd Rate plan. Click C Next. Click the link to go to the Azure A Management Portal. Note Your r billing inform mation will only y be used to co onvert your fr ee trial into a paid account at the end of the 90-day trial pe eriod.

MCT USE ONLY. STUDENT USE PROHIBITED


2-11

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Provisionin P ng a SQL Azure A Serve er

Now that you have h establishe ed a Windows Azure account t, you may pro ovision a SQL A Azure server. H Here are so ome things you need to consider when set tting up the se erver: You will be prompted to select a region n for your serv ver, based on t the locations o of Microsoft's A Azure data center rs. You cannot move a server from one dat ta center to an nother, so be s sure you have chosen a region that will provide e adequate con nnection to yo our location wi ith minimal lat tency. Addition nally, should you decide to exp plore other Azu ure offerings, s such as Report ting Services, m make sure you u place your Repor rt Server at the e same data ce enter as your S SQL Azure serv ver, to minimiz ze data traffic c charges. Once you have h chosen a region and co ontinued the se erver provision ning, you will b be assigned a fourpart DNS name for your server. s There is no indication n in the name as to which re egion you have e chosen, alth hough that inf formation is pr rovided elsewh here in the Azure Managem ment Portal.

To provision n a new SQL Azure Serv ver:


1. . 2. . 3. .

From the Management M Portal P Home screen, https:// /windows.azure e.com, click New Database Server in toolbar

In Create Server S box, select a region closest to you f from the list of f Azure datace enters, then cli ick next. You will be guided through the process of creating a an administrato or account and d configuring the firewall rule es in the next topic. t

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-12 Getting Started with SQL Azure e

Co onfiguring Initial Sec curity

Befo ore you compl lete the proces ss of provision ning a SQL Azu ure server, you u will need to c create an adm ministrator acco ount and allow w client connections through h the Azure fir rewall.

You u will be able to o connect and d manage your r SQL Azure se erver from the web-based m management po ortal usin ng the Window ws Live ID asso ociated with yo our Azure acco ount. By creatin ng a new adm ministrator acco ount, you will be able to o connect to SQL S Azure from m other tools, such as SSMS.

Similarly, you will be able to con nnect to SQL Azure A from the e web-based m management p portal regardle ess of your IP address. You Y will need to authorize IP P addresses to connect throu ugh the firewall in order to u use othe er tools such as a SSMS.

To configure initial securi ity:


1. From the Cre eate Server bo ox, provide a name and pass word for the s server administrator (not you ur Windows Live e ID informatio on), then click Next. Note Acco ounts named admin a , administrator, sa, ro oot, guest, db bmanager or l login are not permitte ed. 2. 3. Specify a firew wall rule to allo ow connection ns to your SQL L Azure databa ase. Click Add, provide a nam me for the firewa all rule, and enter the starting g and ending IP addresses. C Click OK. Click Finish and a review the e server information. Note th he server name e and four-par rt fully qualifie ed server names. You will use the t four-part name n to conne ect to your SQ QL Azure server from tools ot ther than the port tal.

MCT USE ONLY. STUDENT USE PROHIBITED


2-13

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Creating C Yo our First SQ QL Azure Database

Now that you have h provisione ed your server r, you may crea ate an SQL Az ure database f from within th he po ortal. (You may also create a database late er, using script ts while connected from a client such as SS SMS.)

To create a SQL S Azure database: d


1. . 2. . 3. . Select the SQL S Azure serv ver name in the managemen nt portal. Click the Cr reate button in the database e ribbon.

Provide nam me, edition, an nd size for new w database. Fo or the purposes of this course e, select Web edition and select 1 GB in size. Note Yo ou will be offer red several cho oices for editio on and size. Th hese choices w will affect the cost of the e database. See e Microsoft's pricing p informa ation at http:// //www.azurehu ub.com/enus/pricing/details/#data abase.

4. . 5. .

Select your new SQL Azure database on n the left side of the screen, click Test Con nnectivity in t the ribbon, pro ovide your adm ministrator cred dentials (not y your Windows Live ID), click Connect. On a successful result, clic ck Close.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-14 Getting Started with SQL Azure e

Cre eating Dat tabases on n SQL Azur re

In addition to usin ng the Azure Management M Portal P to creat e databases, y you can also cr reate them using clien nt tools such as a SSMS. Either r through the graphical user r interface (GU UI) in SSMS or by executing T T-SQL scrip pts, you can cr reate database es using your administrator a a account. Onc ce you have created a database with which hever method you prefer, yo ou can create d database objects, such h as schemas, tables, and vie ews using SSMS, scripts, or o other tools.

To load data into a SQL Azure database, d you can run scripts s, use tools suc ch as SQL Serv ver Integration n Serv vices, the bcp program, or ot ther Azure-compatible clien nts. SQL Azure will appear to o these tools ju ust like an on-premises o database.

MCT USE ONLY. STUDENT USE PROHIBITED


2-15

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Connecting C g to SQL Azure A with SSMS

Now that you have h opened a Windows Azu ure account, pr rovisioned a SQ da QL Azure server, and created da atabase, you will w be able to connect to your SQL Azure d database from m SSMS. While the process is s quite similar to conne ecting to an on n-premises SQ QL Server, there e are some considerations: In the Conn nect to Server r box, specify the t SQL Azure e server's four-part name, in the form <server>.d database.wind dows.net. In the Auth hentication bo ox, choose SQL Server Auth hentication. C Connecting to SQL Azure using is not support Windows Authentication A ted.

In the Login box, provide e the name of the SQL Azure e administrato or account you u created in the e Azure Manageme ent Portal (not your Window ws Live ID). Late er, once individ dual user acco ounts have bee en created, you can use one instead of an administrator r account. By default, you will conne ect to the mas ster database. T To connect to a user databa ase instead, clic ck the Options bu ox and reveal the Connectio utton to expan nd the Connec ct to Server bo on Properties s panel, which you can c use to ent ter the name of o the desired d database. Note Re emember that once a connec ction to a user r database is m made, you cann not switch to another da atabase without disconnecting and reconn necting to the e next database e. Switching from the master m databas se to a user da atabase is supp ported by the SSMS GUI, but not in code with the USE U statement.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

2-16 Getting Started with SQL Azure e

De emonstration: Conne ecting to SQL S Azure with SQL Server Ma anagement Stu udio

Dem monstration n Steps


1.

On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, and cl lick SQL Server Management M Studio. In the e Connect to S Server window w, type <4 par rt name of Az zure server> in th he Server Nam me text box, se et Authenticat tion to SQL Se erver Authent tication, enter valid administrator r credentials, and a click Conn nect. From the File menu, click Open, O click Proj ject/Solution, navigate to F:\10774A_La abs\10774A_02 2_PRJ\10774A_ _2_PRJ.ssmssln n and click Ope en. From the View w menu, click Solution Explo orer. To create and d populate the e sample datab base on the SQ QL Azure serve er, open and ex xecute the 00 Setup.sql script file from within Solution Explorer. E Follow the ins structions cont tained within the t comments s of the script f file.

2. 3. 4. 5. 6.

Open the file 11- Demonstration A.sql an nd follow the in nstructions co ontained within n the commen nts of the script file. .

MCT USE ONLY. STUDENT USE PROHIBITED


2-17

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2012

Modu ule Revi iew and d Takeaw ways

Review R Ques stions


1. . 2. . 3. . What authe entication mec chanism does SQL S Azure use e? How do you switch from one user data abase to anoth her on a SQL A Azure server? What choic ces are there fo or creating a database d on a SQL Azure ser rver

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-1

Module 3
Introduction to T-SQL Querying
Contents:
Lesson 1: Introducing T-SQL Lesson 2: Understanding Sets Lesson 3: Understanding Predicate Logic 3-3 3-15 3-18

Lesson 4: Understanding the Logical Order of Operations in SELECT statements 3-21 Lab: Introduction to T-SQL Querying 3-29

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-2 Introduction n to T-SQL Querying

Module Over rview

Tran nsact-SQL, or T-SQL, T is the la anguage in wh hich you will w write your quer ries for SQL Se erver 2012. In t this mod dule, you will learn l that T-SQ QL has many elements e in co mmon with ot ther computer r languages: com mmands, variab bles, functions, , operators, an nd the like. You u will also lear rn that T-SQL c contains some e uniq que elements that t may require some adjus stment if your r background i includes exper rience with proc cedural langua ages. In order to make the most m of your ef ffort in writing g T-SQL querie es, you will also o lear rn in this modu ule the process s by which SQL Server evalua ates your quer ries. Understan nding the logical orde er of operation ns of SELECT statements s will l be vital to lea arning how to write effective e queries.

Ob bjectives
Afte er completing this module, you y will be able to: Describe the elements of T-SQL and their r role in writing g queries Understand the use of sets in SQL Server Understand the use of pred dicate logic in SQL Server Understand the logical orde er of operation ns in SELECT s tatements

MCT USE ONLY. STUDENT USE PROHIBITED


3-3

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Lesson n1

Introd ducing T-SQL

In n this lesson, yo ou will learn th he role of T-SQ QL in writing S SELECT stateme ents. You will l learn about many of th he elements of f the T-SQL lan nguage, and which w elements s will be useful l to you in writ ting queries.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe Microsofts M implementation of the standard d SQL language e. Categorize SQL statemen nts into their dialects. Identify the e elements of T-SQL, T includin ng predicates, operators, exp pressions and comments.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-4 Introduction n to T-SQL Querying

Ab bout T-SQL L

T-SQ QL is Microsof fts implementa ation of the in ndustry standa rd Structured Query Langua age. Originally developed to support the new relational r data a model at Inte ernational Bus iness Machine es (IBM) in the early 1970s, SQL has go one on to wide e adoption in the t industry. S SQL became a standard of th he American National Standard l Organization ds Institute (AN NSI) and of the e International n for Standardi ization (ISO) in n the 1980s.

The ANSI standard d has gone through several revisions, inclu uding SQL-89 and SQL-92, w whose specifications are either fully or partly support ted by T-SQL. SQL Server 20 012 also implements features from later stan ndards, such as s ANSI SQL-20 008. Microsoft, like many ven ndors, has also o extended the e language to include SQL Serve er-specific feat tures and funct tions. Besi ides Microsofts implementa ation as T-SQL in SQL Server,, Oracle implements SQL as PL/SQL, IBM imp plements it as SQL S PL, and Sy ybase maintain ns its own imp lementation o of T-SQL.

An important i con ncept to under rstand when working w with T-SQL is that it is a set-based and declarativ ve lang guage, not a procedural p lang guage. When you y write a qu uery to retrieve e data from SQ QL Server, you desc cribe the data you wish to display; you do not tell SQL S Server exactly h how to retriev ve it. Instead of f prov viding a proce edural list of steps to take, yo ou provide the e attributes of the data you s seek. For exam mple, if Portland, a pro you want to retrie eve a list of cus stomers who are a located in P ocedural meth hod might look k like this:
1) 2) 3) 4) 5) 6) 7) 8) Open a cursor to consume rows, one e at a time Fetch the first cursor record. Examine first row. If the city is Portland, return th he row. Move to next row. If the city is Portland, return th he row. Fetch the next record (Repeat until end of table is reac ched).

MCT USE ONLY. STUDENT USE PROHIBITED


3-5

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Your procedural code must not only contain the logic to select the data that meets your needs, but you must also determine and execute a well-performing path through the data. Note This course mentions cursors for comparative purposes, but does not provide training on writing code with them. See Books Online for definitions and concerns regarding the use of cursors: http://msdn.microsoft.com/enus/library/ms191179(v=SQL.110).aspx

With a declarative language such as T-SQL, you will provide the attributes and values that describe the set you wish to retrieve, such as the following pseudo-code:
Display all customers whose city is Portland.

With T-SQL, the SQL Server 2012 database engine will determine the optimal path to access the data and return a matching set. Your role is to learn to write efficient and accurate T-SQL in order to properly describe the set you wish to retrieve. If you have a background in other programming environments, adopting a new mindset may present a challenge. This course has been designed to help you bridge the gap between procedural and set-based declarative T-SQL. Note Sets will be discussed later in this module.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-6 Introduction n to T-SQL Querying

Categories of o T-SQL St tatements

T-SQ QL statements s can be organ nized into several categories::

-SQL statemen Data Manipu ulation Langu uage, or DML, is the set of Tnts that focus on querying and modifying da ata. This includes SELECT, the e primary focu us of this cours se, as well as m modification statements su uch as INSERT, UPDATE, and DELETE. You will learn abou ut SELECT statements in modules 4 through 15. Data Definition Language e, or DDL, is th he set of T-SQL L statements th e definition an nd hat handle the lifecycle of da atabase object ts, such as tables, views, and procedures. T This includes st tatements such h as CREATE, ALTE ER, and DROP. .

Data Control Language, or o DCL, is the set s of T-SQL st atements used d to manage security permis ssions for users and objects. DCL includes i statem ments such as GRANT, REVO OKE, and DENY Y. re beyond the scope of this c course. For mo ore informatio on about Note DCL commands ar 2 security, including DCL L, see Microsof ft Official Cour rse 10775: Mai intaining a SQL Server 2012 SQL Server 2012 2 Database e. nformation Additional ref ference on DM ML, DDL, and D DCL command ds can be For More In found in Bo ooks Online at http://msdn.m microsoft.com/ /enus/library/bb b510741(v=SQ QL.110).aspx.

MCT USE ONLY. STUDENT USE PROHIBITED


3-7

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

T-SQL T Lang guage Elem ments

Like many programming lang guages, T-SQL contains many y elements tha at you will use e in your querie es. You will w use predicates to filter row ws, operators to t perform co mparisons, fun nctions and ex xpressions to manipulate m data a or retrieve sy ystem informa ation, and com mments to docu ument your co ode. If you nee ed to go be eyond writing SELECT statem ments to create e stored proce edures, trigger rs, and other o objects, you ma ay use el lements such as a control-of-f flow statement ts, variables to o temporarily s store values, an nd batch separators. Th he next severa al topics in this s lesson will int troduce you to o many of thes se elements. Note Th he purpose of this t lesson is to o introduce m any elements of the T-SQL l language, which will be presented here at a high h conceptual le evel. Subseque ent modules in n this course de more detaile ed explanation ns. will provid

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-8 Introduction n to T-SQL Querying

T-S SQL Langu uage Eleme ents: Predicates and d Operator rs

The T-SQL langua age provides elements for sp pecifying and e evaluating logical expression ns. In SELECT statements, you can use logical expressions to o define filters for WHERE an nd HAVING cla auses. You will l write thes se expressions using predicates and operators. Pred dicates suppor rted by T-SQL include the fo ollowing: IN, used to de etermine whet ther a value matches m any val lue in a list or subquery BETWEEN, used to specify a range of valu ues LIKE, used to match charact ters against a pattern

Ope erators include e several comm mon categories: Comparison for f equality an nd inequality te ests: =, <, >, > >=, <=, !=, !>, !< (Note that !>, !< and != are not ISO stand dard. It is a bes st practice to use u standard o options when t they exist.) Logical, for te esting the valid dity of a condition: AND, OR R, NOT Arithmetic, fo or performing mathematical operations: + , -, *, /, % (mo odulo) Concatenatio on, for combini ing character strings: s + Assignment, for f setting a va alue: =

MCT USE ONLY. STUDENT USE PROHIBITED


3-9

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

As with other mathematical environments, operators are subject to rules governing precedence. The following table describes the order in which T-SQL operators are evaluated: Order of Evaluation 1 2 3 4 5 6 7 8 Operators ( ) Parentheses *, /, % (Multiply, Divide, Modulo) +, - (Add/Positive/Concatenate, Subtract/Negative) =, <, >, >=, <=, !=, !>, !< (Comparison) NOT AND BETWEEN, IN, LIKE, OR = (Assignment)

For More Information Information on other categories of operators, including bitwise, unary, and scope assignment, can be found in Books Online at http://msdn.microsoft.com/en-us/library/ms174986(v=SQL.110).aspx.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-10

Introductio on to T-SQL Querying

T-S SQL Langu uage Eleme ents: Functions

SQL L Server 2012 provides p a wid de range of fun nctions availab ble to your T-S SQL queries. Th hey range from m scalar functions su uch as SYSDAT TETIME, which return a single e-valued resul lt, to functions s that operate on and return entire sets, such as the windowing functions you u will learn abo out in module 13. As with w operators, SQL Server fu unctions can be b organized in nto categories s. Here are som me common cate egories of scala ar (single-value) functions av vailable to you u as you write your queries: String functio ons SUBSTRING, LEFT, L RIGHT, LEN, DATALENGTH REPLACE, REP PLICATE UPPER, LOWE ER, RTRIM, LTR RIM Date and time functions GETDATE, SYS SDATETIME, GETUTCDATE G DATEADD, DA ATEDIFF YEAR, MONTH, DAY Aggregate functions SUM, MIN, MAX, M AVG COUNT, COU UNTBIG Mathematical functions RAND, ROUN ND, POWER, AB BS CEILING, FLOOR

MCT USE ONLY. STUDENT USE PROHIBITED


3-11

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Note The purpose of this lesson is to introduce many elements of the T-SQL language, which will be presented here at a high conceptual level. Subsequent modules in this course will provide more detailed explanations. For More Information Additional information on these functions, with sample code, can be found in Books Online at http://msdn.microsoft.com/enus/library/ms174318(v=SQL.110).aspx.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-12

Introductio on to T-SQL Querying

T-S SQL Langu uage Eleme ents: Varia ables

Like e many programming langua ages, T-SQL pr rovides a mean ns of tempora rily storing a v value of a spec cific data a type. Howev ver, unlike othe er programmin ng environmen nts, all usercr reated variable es are local to t the TSQL L batch that cre eated them, and visible only y to that batch h. There are no o global or pub blic variables avai ilable to users in SQL Server. . To create c a local variable v in T-SQL, you must provide a nam me, a data type e, and an initia al value. The na ame mus st start with a single s @ (at) symbol, s and th he data type m must be system m-supplied or u user-defined and stor red in the data abase your cod de will run against. Note You may find refer rences in SQL Server S literatu re, websites, e etc., to so-calle ed system variables, named with a double d @@, su uch as @@ERR ROR. It is more e accurate to r refer to tem functions, since users may not assign a value to them. This course e will these as syst differentiate e user variables s prefixed with h a single @ fro om system fun nctions prefixe ed with @@.

If yo our variable is not initialized in the DECLARE statement, it will be creat ted with a valu ue of NULL and you can subsequently assign a value e with the SET statement. SQ QL Server 2008 8 introduced th he capability to o nam me and initializ ze a variable in n the same stat tement. The following exa ample creates a local integer r variable called d MyVar and a assigns it an in nitial value of 3 30:
DE ECLARE @MyVar r int = 30;

The following exa ample creates a local date va ariable called M MyDate and se eparately assig gns it an initial value of 15 1 Feb 2012:
DE ECLARE @MyDat te date; SE ET @MyDate = 20120215;

MCT USE ONLY. STUDENT USE PROHIBITED


3-13

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

You will learn more about data types, including dates, in module7. You will learn more about working with variables in T-SQL in module 17. Note If persistent storage or global visibility for a value is needed, consider creating a table in a database for that purpose. SQL Server provides both session-temporary and permanent storage in databases. See http://msdn.microsoft.com/enus/library/ms186986.aspx for more information on temporary tables and objects.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-14

Introductio on to T-SQL Querying

T-S SQL Langu uage Eleme ents: Expre essions

T-SQ QL provides th he use of comb binations of identifiers, symb bols, and operators that are evaluated by S SQL Serv ver to return a single result. These T combinations are kno own as express sions.

Expressions are a very useful and powerful tool for use in yo our queries. In n SELECT statem ments, you ma ay use expressions: In the SELECT T clause to ope erate on and/o or manipulate columns As CASE Expr ressions to replace values ma atching a logic cal expression with another v value In the WHERE E clause to con nstruct predica ates for filterin ng rows further proces As table expressions to crea ate temporary sets used for f ssing is lesson is to introduce man ny elements of f the T-SQL lan nguage, Note The purpose of thi e presented he ere at a high conceptual c leve el. Subsequent t modules in this course which will be will provide more detailed d explanations. .

Expressions may be b based on a scalar (single-value) functio on, on a consta ant value, or on n variables. Mu ultiple expressions may be b joined using g operators if they have the same data typ pe or may be c converted from ma lower precedence e to a higher precedence (e.g g., int to mone ey).

MCT USE ONLY. STUDENT USE PROHIBITED


3-15

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

The following example of an expression operates on a column to add an integer to the results of the YEAR function on a datetime column:
SELECT YEAR(orderdate) AS currentyear, YEAR(orderdate) + 1 AS nextyear FROM Sales.Orders;

Note The preceding example uses T-SQL techniques, such as column aliases and date functions, that will be covered later in this course.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-16

Introductio on to T-SQL Querying

T-S SQL Langu uage Eleme ents: Cont trol of Flow w, Errors, a and Transa actions

While T-SQL is pri imarily a data retrieval langu uage and not a procedural la anguage, it do oes support a limited set of statements that provide some control c of flow w during execut tion. Som me of the comm monly used co ontrol-of-flow statements inc clude: IF . . .ELSE, for r providing bra anching contro ol based on a logical test. WHILE, for repeating a statement or bloc ck of statemen ts while a condition is true. BEGIN . . .END D, for defining the extents of a block of T-SQL statemen nts. TRY . . . CATC CH, for defining g structure exc ception handli ng (error hand dling). BEGIN TRANS SACTION, for marking m a bloc ck of statemen nts as part of a an explicit tran nsaction. Ended by COMMIT TRANS SACTION or RO OLLBACK TRAN NSACTION Note Cont trol-of-flow op perators are no ot used in stan ndalone querie es. If your prim mary role is as a report writer, w for exam mple, it is unlik kely that you w will need to use e them. Howe ever if your responsibilities include cre eating objects such as stored d procedures a and triggers, yo ou will find these elements useful.

MCT USE ONLY. STUDENT USE PROHIBITED


3-17

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

T-SQL T Lang guage Elem ments: Com mments

T-SQL provides two mechanis sms for docum menting code o or for instructing the databa ase engine to ignore ce ertain statements. Which me ethod you will use will typica ally depend on n the number o of lines of code you wish w to mark as s ignored: For single lines, or very fe ew lines of cod de, use the -- ( (double dash) to precede the e text to be marked as a comme ent. Any text following f the dashes d will be ignored by SQ QL Server. For longer blocks of code e, enclose the text between / /* and */ chara acters. Any code between th he characters will w be ignored d by SQL Serve er.

Th he following example uses the -- (double dash) method to mark comm ments:
-- This entire line of text t will be ignored. DECLARE @MyV Var int = 30; --only the text followi ing the dashe es will be ig gnored.

Th he following example uses the /* commen nt block */ met thod to mark c comments:
*/ This is comment te ext that will l be ignored . */

Many M query edi iting tools, suc ch as SSMS or SQLCMD, will color-code co ommented tex xt in a different t color th han the surrounding T-SQL code. c In SSMS, use the Tools s|Options dialo og box to custo omize the colo ors and fo onts used in th he T-SQL script t editor.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-18

Introductio on to T-SQL Querying

T-S SQL Langu uage Eleme ents: Batch h Separato ors

SQL L Server client tools, such as SSMS, send co ommands to th he database en ngine in sets c called batches. If you are manually executing cod de, such as in a query editor,, you can choo ose whether to o send all of th he text in a script as one batch. You ma ay also choose e to insert sepa arators betwee en certain sections of code. The specification of a batch sep parator is hand dled by your cl ient tool. For e example, the k keyword GO is s the defa ault batch sepa arator in SSMS S. You can change this for th he current que ery in Query|Query Options o or glob bally in Tools|O Options|Query y Execution.

For most simple query q purposes s, batch separa ators are not u used, as you w will be submitting a single qu uery at a tim me. However, when w you nee ed to create an nd manipulate objects, you m may need to se eparate statem ments into o distinct batch hes. For examp ple, a CREATE VIEW V stateme nt may not be e included in th he same batch h as othe er statements. The following g example:
CR REATE TABLE t1 t (col1 int) ); CR REATE VIEW v1 1 as SELECT * FROM t1;

retu urns the follow wing error:


Msg 111, Level 15, State 1, 1 Line 2 'C CREATE VIEW' must be the first statem ment in a que ery batch.

Not te that user-de eclared variables are conside ered local to th he batch in wh hich they are declared. If a variable is declare ed in one batch h and is refere enced in anoth her batch, the s second batch would fail. For r exam mple, the follo owing statements sent together as one bat tch work prop perly:
DE ECLARE @cust int = 5; SE ELECT custid, companyname e, contactnam me FR ROM Sales.Cus stomers WH HERE custid = @custid;

MCT USE ONLY. STUDENT USE PROHIBITED


3-19

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

However, if a batch separator were inserted between the variable declaration and the query in which the variable is used, an error would occur. The following example separates the variable declaration from its use in a query:
DECLARE @cust int = 5; GO SELECT custid, companyname, contactname FROM Sales.Customers WHERE custid = @custid;

It returns the following error:


Msg 137, Level 15, State 2, Line 3 Must declare the scalar variable "@custid".

Note

Variables will be covered in more depth in module 17.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-20

Introductio on to T-SQL Querying

De emonstration: T-SQL L Language e Elements s

Dem monstration n Steps


1.

On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, and cl lick SQL Server Management M Studio. In the e Connect to S Server window w, type Prosew ware in the Ser rver name text bo ox and click Co onnect. From the t File menu , click Open, c click Project/So olution, naviga ate to F:\10774A_La abs\10774A_03 3_PRJ\10774A_ _03_PRJ.ssmssl ln, and click O Open.

2. 3. 4.

On the View menu, click So olution Explore er. Open and e execute the 00 0 Setup.sql sc cript file from w within Solution Explorer. Open the 11 Demonstrati ion A.sql script t file. Follow the ins structions cont tained within the t comments s of the script f file.

MCT USE ONLY. STUDENT USE PROHIBITED


3-21

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n2

Unde erstanding Sets s

Th he purpose of this lesson is to t introduce th he concepts of f set theory, on hematical ne of the math un nderpinnings of o relational databases, and to help you ap pply it to how you think abo out querying S SQL Se erver.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe th he role of sets in i a relational database. Understand d the impact of o sets on your T-SQL queries s. Describe at ttributes of set ts that may req quire special tr reatment in yo our queries.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-22

Introductio on to T-SQL Querying

Set t Theory and SQL Se erver

Set theory is one of the mathem matical founda ations of the re elational mode el and hence is s foundational for wor rking with SQL L Server 2012. While W you mig ght be able to go a long way y writing queri ies in T-SQL w without an appreciation a of o sets, you may eventually have difficulty e expressing som me queries in a single, wellperf forming statem ment. This s lesson will set t the stage for r you to begin "thinking in se ets" and unde rstanding the nature of sets. In turn n, this will mak ke it easier for you to: Take advanta age of set-base ed statements in T-SQL Understand why w you still ne eed to sort you ur query outpu ut

Understand why w a set-base ed, declarative approach rath her than proce edural approac ch works best w with SQL Server 20 012

Without delving into the mathe ematics suppor rting set theor ry, we can defi ine a set, for o our purposes, a as "a colle ection of defin nite, distinct ob bjects considered as a whole e." In terms ap pplied to SQL S Server databas ses, we can think of a set as a single unit (such as a ta able) that cont tains zero or m more members s of the same t type. For example, a Cu ustomers table e represents a set, s specifically y the set of all customers. Yo ou will also see e that the results of a SE ELECT statement also form a set, which wil l have importa ant ramificatio ons when learn ning abo out subqueries and table exp pressions, for example. It will w be importan nt, as you learn n more about certain T-SQL L query statements, to think of the entire set at all times, instead of o thinking of individual members. This wi ill better equip p you to write set-based cod de, instead of thinking one row at a time. Workin ng with sets req quires thinking g in terms of o operations that occu ur "all at once" instead of on ne-at-a-time. This T may be an n adjustment f for you, depen nding on your background.

Afte er "collection," the next critic cal term in our r definition is " "distinct", or un nique. All mem mbers of a set must be unique. u In SQL L Server, uniqu ueness is typica ally implement ted using keys s, such as a primary key column. How wever, once yo ou start workin ng with subsets s of data, it wi ll be importan nt to keep mindful of how yo ou will be able a to unique ely address eac ch member of a set.

MCT USE ONLY. STUDENT USE PROHIBITED


3-23

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

This brings us back to the consideration of the set as a "whole." Noted SQL language author Joe Celko suggests mentally adding the phrase "Set of all" in front of the names of SQL objects that represent sets ("set of all customers", for example). This will help you remember that you are addressing a collection of elements when you write T-SQL code, not just one element at a time. One important consideration is what's omitted from set theory: any requirement regarding the order of elements in a set. In short, there is no predefined order in a set. Elements may be addressed (and retrieved) in any order. Applied to your queries, this means that if you need to return results in a certain order, you will need to use the ORDER BY clause in your SELECT statements. See module 6 for more information on ORDER BY. For More Information More information on the set theory and its application to SQL Server queries can be found in chapter 1 of Itzik Ben-Gans Inside Microsoft SQL Server 2008: T-SQL Querying (Microsoft Press, 2009) and chapter 2 of Itzik Ben-Gans Microsoft SQL Server 2008: T-SQL Fundamentals (Microsoft Press, 2008). For more information on the use of "Set of all" see Joe Celko's Thinking in Sets (Morgan Kaufman, 2008).

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-24

Introductio on to T-SQL Querying

Set t Theory Applied A to SQL Serve er Queries

Give en the set-based foundation n of databases, , there are a fe ew consideratio mmendations t to be ons and recom awa are of when wr riting efficient T-SQL queries s: Act on the wh hole set at onc ce This translates to querying the whole table at once, inst tead of cursor r-based or itera ative processin ng Use declarativ ve, set-based processing p

Tell SQL Serve er what you want w to retrieve e by describing g its attributes s, not by navigating to its po osition ue identifiers, such as keys, w Ensure that you are address sing elements via their uniqu when possible Write JOIN clauses referenc cing unique ke eys on one side e of the relatio onship. Provide your own sorting in nstructions Result sets are e not guarante eed to be returned in any or rder.

MCT USE ONLY. STUDENT USE PROHIBITED


3-25

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n3

Unde erstanding Pred dicate Logic L

Along with set theory, t predica ate logic is ano other mathem matical foundat tion for the rel lational databa ase model, m and with h it, SQL Serve er 2012. Unlike set theory, yo ou probably ha ave a fair amount of experie ence with w predicate logic, even if you y have never r used the term m to describe it. This lesson w will introduce predicate logic and examine its i application to querying S SQL Server.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe th he role of predicate logic in a relational da tabase Understand d the use of pr redicate logic on o your T-SQL L queries.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-26

Introductio on to T-SQL Querying

Pre edicate Logic and SQ QL Server

In th heory, predicate logic is a fra amework for expressing e logi ical tests that return true or false. A predic cate is a pr roperty or expression that is true or false. You Y may have heard this ref ferred to as a B Boolean expre ession. Taken by themselves, predicates make compa arisons and ex press the results as true or fa alse. However, , in TSQL L predicates do on't stand alon ne. They are us sually embedd ded in a statem ment that does s something with the true/false resu ult: a WHERE clause c to filter rows, a CASE e expression to m match a value, and even a colu umn constraint t governing th he range of acc ceptable value es for that colu umn in a table's definition. Theres one important omission n in the formal definition of a predicate: ho ow to handle u unknown, or miss sing, values. If a database is set up so that missing value es are not perm mitted (through constraints, or defa ault value assig gnments), then n perhaps this is not an impo ortant omissio on. But in most t real-world environments, you u will have to account for missing or unkn nown values, w which will require you to exte end your understandin ng of predicates from two possible outcom mes (true or fa alse) to three: t true, false or unk known. The use of NULLs as a mark for missing data will w be further discussed in t the next topic, as well as in mod dule8. nformation More informa ation on predic cate logic and its application n to SQL For More In Server quer ries can be fou und in chapter 1 of Itzik Ben-Gans Inside M Microsoft SQ QL Server 2008: T-SQL Querying (Microsoft Press 2009) 2 and chap pter 2 of Itzik Ben-Gans Mic crosoft SQL : T-SQL Fundam mentals (Micro osoft Press 200 08). Server 2008:

MCT USE ONLY. STUDENT USE PROHIBITED


3-27

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Predicate P Logic L Applied to SQL L Server Queries

As you have bee en learning, th he ability to us se predicates to o express com mparisons in terms of true, fa alse, or un nknown is vita al to writing eff fective queries s in SQL Server r. Although we e have been discussing them m se eparately, pred dicates do not stand alone, syntactically s sp peaking. You w will typically us se predicates in n any of th he following ro oles within you ur queries: Filtering da ata (in WHERE and HAVING clauses) Providing conditional c log gic to CASE exp pressions Joining tables (in the ON filter) Defining su ubqueries (in EXISTS tests, for example)

Additionally, predicates have uses outside SELECT S statem ents, such as i n CHECK cons straints to limit t values pe such as an IF s ermitted in a column, c and in n controlof-flo ow elements, s statement.

In n mathematics, we only need d to consider values v that are e present, so pr redicates can r result only in t true or fa alse values. (Th his is known in predicate logic as the law o of the excluded d middle.) Yet in databases, y you will lik kely have to ac ccount for mis ssing values, an nd the interact tion of T-SQL predicates with missing valu ues re esults in an unknown. Ensure e that you have e accounted fo or all three po ossible outcom mestrue, false e or un nknownwhe en you are designing your qu uery logic. You u will learn how w to use three e-valued logic in WHERE W clauses later in this co ourse. he purpose of this t lesson is to o introduce m any elements of the T-SQL l language, Note Th which will be presented here at a high h conceptual le evel. Subseque ent modules in n this course de more detaile ed explanation ns. will provid

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-28

Introductio on to T-SQL Querying

Lesson 4

Understandin ng the Logical L Order O o of Opera ations in SELEC CT Statem ments

T-SQ QL is unusual as a a programm ming language e in one key as spect: the orde er in which you u write a statement is no ot necessarily the order in which w the datab base engine w will evaluate an nd process it. D Database engin nes may y optimize their execution of f a query, as lo ong as the corr rectness of the e result (as det termined by th he logical order) is re etained. As a re esult, unless yo ou learn the lo ogical order of f operations, you may find b both conceptual and practical obstac cles to writing your queries. T This lesson wil ll introduce the elements of a SELE ECT statement t, delineate the e order in whic ch the elemen nts are evaluate ed, and then a apply this und derstanding to a practical approach to writ ting queries.

Les sson Objecti ives


Afte er completing this lesson, yo ou will be able to: Describe the elements of a SELECT statem ment. Understand the order in wh hich clauses in a SELECT stat tement are eva aluated. Apply your understanding of o the logical order o of opera ations to writin ng SELECT stat tements.

MCT USE ONLY. STUDENT USE PROHIBITED


3-29

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Elements of o a SELECT T Statemen nt

In n order to acco omplish our go oal of understa anding the log gical order of o operations, we e need to look at a SE ELECT stateme ent as a whole, , including a number of opti ional elements s. However, this lesson is not t de esigned to pro ovide detailed information about these ele ements. Each p part of a SELEC CT statement w will be tr reated in subse equent module es. However, understanding u the details of a WHERE clau use, for examp ple, is no ot required in order to unde erstand its plac ce in the seque ence of events s.

A SELECT statem ment is made up u of a combination of man ndatory and op ptional elemen nts. Strictly spe eaking, SQ QL Server only y requires a SELECT clause in n order to exec cute without error. A SELECT T without a FRO OM clause operates as though you were selectin ng from an im maginary table containing on ne row. (You w will see th his behavior lat ter in this cour rse when you test t variables.) ) However, sin ce a SELECT cl lause without a FROM clause cannot re etrieve data fro om a table, we e will treat stan ndalone SELEC CT clauses as a special case t that is no ot directly rele evant to this le esson. Let's exa amine the elem ments, their hig gh-level role in n a SELECT sta atement, an nd the order in n which they are a evaluated by b SQL Server.

Not all element ts will be prese ent in every SELECT query. H However, when n an element is s present, it will always be e evaluated in the same order with respec ct to the other elements pres sent. For exam mple, a WHERE clause will w always be evaluated after r the FROM cla ause and befor re a GROUP BY Y clause, if one e exists. Le et's move on to the discussio on of the order of these ope erations in the next topic. or the purposes s of this lesson n, additional op STINCT, Note Fo ptional elemen nts such as DIS OVER and TOP are omit tted. They will be introduced d and their ord der discussed in later modules.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-30

Introductio on to T-SQL Querying

Log gical Quer ry Processi ing

The order in which a SELECT sta atement is writ tten is not the order in which ver database e engine h the SQL Serv evaluates and pro ocesses the statement. Consider the follow wing query:
US SE TSQL2012; SE ELECT empid, YEAR(orderda ate) AS order ryear FR ROM Sales.Ord ders WH HERE custid =71 = GR ROUP BY empid d, YEAR(order rdate) HA AVING COUNT(* *) > 1 OR RDER BY empid d, orderyear;

Befo ore we examin ne the runtime e order of oper rations, let's br riefly examine what the query does, althou ugh dule. The first line ensures w deta ails on many of o the clauses will w need to wa ait until the ap ppropriate mod we're connected to the correct databa ase for the query. This line is s not being ex xamined for its s runtime orde er. We need this to comp plete (if necess sary) before the main SELECT T query executes:
US SE TSQL2012; -- change co onnection con ntext to samp ple database

The next line is th he start of the SELECT S statem ment as we wro ote it, but as w we'll see, it will not be the firs st line evaluated. The SELECT clause re eturns the emp pid column an d extracts just t the year from m the orderdate colu umn:
SE ELECT empid, YEAR(orderda ate) AS order ryear

The FROM clause identifies whic ch table is the source of the rows for the q query:
FR ROM Sales.Ord ders

The WHERE clause e filters the row ws out of the Sales.Orders ta able, keeping only those tha at satisfy the pred dicate:
WH HERE custid =71 =

MCT USE ONLY. STUDENT USE PROHIBITED


3-31

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

The GROUP BY clause groups together the remaining rows by empid and then by the year of the order:
GROUP BY empid, YEAR(orderdate)

After the groups are established, the HAVING clause filters the groups based on its predicate. Only employees with more than one sale per customer in a given year will pass this filter:
HAVING COUNT(*) > 1

The final clause, for the purposes of previewing this query, is the ORDER BY, which sorts the output by empid and then by year:
ORDER BY empid, orderyear;

Now that we've established what each clause does, let's look at the order in which SQL Server must evaluate them: 1.

The FROM clause is evaluated first, to provide the source rows for the rest of the statement. (Later in the course we'll see how to join multiple tables together in a FROM clause.) A virtual table is created and passed to the next step. The WHERE clause is next to be evaluated, filtering those rows from the source table that match a predicate. The filtered virtual table is passed to the next step.

2. 3.

GROUP BY is next, organizing the rows in the virtual table according to unique values found in the group by list. A new virtual table is created, containing the list of groups, and passed to the next step. Note From this point in the flow of operations, only columns in the GROUP BY list or aggregate functions may be referenced by other elements. This will have a significant impact on the SELECT list.

4. 5.

The HAVING clause is evaluated next, filtering out entire groups based on its predicate. The virtual table created in step 3 is filtered and passed to the next step. The SELECT clause finally executes, determining which columns will appear in the query results. Note Because the SELECT clause is evaluated after the other steps, any column aliases created in the SELECT clause cannot be used in clauses processed in steps 1-4. (See module 4 for more information about column aliases.)

6.

The last clause to execute in our example is the ORDER BY clause, sorting the rows as determined in its column list.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-32

Introduction to T-SQL Querying

To apply this to our example query, here is the logical order at runtime, with the USE statement omitted for clarity:
5. SELECT empid, YEAR(orderdate) AS orderyear 1. FROM Sales.Orders 2. WHERE custid =71 3. GROUP BY empid, YEAR(orderdate) 4. HAVING COUNT(*) > 1 6. ORDER BY empid, orderyear;

As we have seen, in T-SQL we do not write queries in the same order in which they are logically evaluated. Since the runtime order of evaluation determines what data is available to clauses downstream from one another, it's important to understand the true logical order when writing your queries.

MCT USE ONLY. STUDENT USE PROHIBITED


3-33

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Applying A th he Logical Order of Operation ns to Writing SELECT T Statemen nts

Now that you have h learned th he logical orde er of operation ns when a SELE ECT query is ev valuated and processed, keep p in mind the following f cons siderations wh en writing a q uery. Note tha at some of the ese may re efer to details you y will learn in subsequent modules: Decide which tables you will query first t, as well as an y table aliases s you will apply y. This will determine your FROM M clause. Decide which set or subse et of rows will be retrieved f from the table e(s) in the FROM M clause, and how you will exp press your predicate. This will determine y your WHERE clause.

If you will be b grouping ro ows, decide wh hich columns w will be groupe ed on. Rememb ber that only c columns in the GROUP BY clause, as well as aggregate functio ons such as CO OUNT, may ulti imately be included in the SELECT clause. If you need d to filter out groups, g decide on your pred icate and build d your HAVING clause. It's the results of th his phase that become the in nput to the SE LECT clause.

umns from the If you are not n using GROUP BY, determ mine which colu e source table(s) you wish to o display, and d use any table e aliases you created c to refe r to them. This s will become the core of yo our SELECT clau use. If you hav ve used a GROUP BY clause, select from the columns in t the GROUP BY Y clause, and add an ny additional aggregates to the t SELECT list t. Finally, rem member that se ets do not inclu ude any order ing, and as a r result, you will need to add a an ORDER BY clause to guar rantee a sort order o if it's desi ired.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-34

Introductio on to T-SQL Querying

De emonstration: Logica al Query Processing

Dem monstration n Steps


1.

On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, and cl lick SQL Server Management M Studio. In the e Connect to S Server window w, type Prosew ware in the Ser rver name text bo ox and click Co onnect. From the t File menu , click Open, c click Project/S Solution, navig gate to F:\10774A_ _Labs\10774A_ _03_PRJ\10774 4A_03_PRJ.ssm mssln, and click k Open. From the View menu, click Solution Exp plorer. Open a nd execute the 00 Setup.sql script file from within Solutio on Explorer. Open the 21 Demonstrati ion B.sql script t file. Follow the ins file. structions cont tained within the t comments s of the script f

2. 3. 4.

MCT USE ONLY. STUDENT USE PROHIBITED


3-35

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lab: Introduction to o T-SQL L Querying

La ab Setup

Fo or this lab, you u will use the available a virtua al machine env vironment. Bef fore you begin n the lab, you must co omplete the fo ollowing steps: : 1. . 2. . 3. . On the host computer, click Start, poin nt to Administ trative Tools, and click Hyp per-V Manage er. Maximize the Hyper-V Manager M window. If the virtua al machine 107 774A-MIA-DC C1 is not starte ed: 4. . -MIA-DC1 an d click Start. In the Virtual V Machi ines list, right-click 10774ARight-c click 10774A-MIA-DC1 and d click Connec ct.

In the Virtual V Machi ine Connectio on window, wa ait until the P Press CTRL+ALT T+DELETE to log on messag ge appears, an nd then close the Virtual Ma achine Conne ection window w.

If the virtua al machine 107 774A-MIA-SQ QL1 is not start ted: -MIA-SQL1 an In the Virtual V Machi ines list, right-click 10774And click Start. Right-c click 10774A-MIA-SQL1 and click Conne ect.

In the Virtual V Machi ine Connectio on window, wa ait until the P Press CTRL+ALT T+DELETE to log on messag ge appears, an nd then close the Virtual Ma achine Conne ection window w.

5. . 6. .

In Virtual Machine M Conn nection windo ow, click the R Revert toolbar icon. If you are prompted p to co onfirm that yo ou want to reve ert, click Reve ert. Wait for the revert action n to complete.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-36

Introduction to T-SQL Querying

7.

If you are not already logged on:

In the Virtual Machine Connection window, click the Ctrl-Alt-Delete menu item on the Action menu. Click Switch User, and then click Other User. Log on using the following credentials: User name: AdventureWorks\Administrator Password: Pa$$w0rd

8. 9.

In the Virtual Machine Connection window, click Full Screen Mode on the View menu. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.

Lab Scenario

You are a business analyst for Adventure Works who will be writing reports against corporate databases stored in SQL Server 2012. In order for you to become more comfortable with SQL Server querying, the Adventure Works IT department has provided you with a selection of common queries to run against their databases. You will review and execute these queries.

MCT USE ONLY. STUDENT USE PROHIBITED


3-37

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 1: Executing Basic SELECT Statements


Scenario

The T-SQL script provided by the IT department includes a SELECT statement that retrieves all rows from the HR.Employees table, which includes the firstname, lastname, city, and country columns. You will execute the T-SQL script against the TSQL2012 database. The main tasks for this exercise are as follows: 1. 2. Open the T-SQL script using Microsoft SQL Server Management Studio. Execute the T-SQL script.

X Task 1: Open the T-SQL script using Microsoft SQL Server Management Studio

Using SQL Server Management Studio (SSMS), connect to Proseware using Windows authentication (if you are connecting to an on-premises instance of SQL Server) or SQL Server authentication (if you are using SQL Azure). Open the project file F:\10774A_Labs\10774A_03_PRJ\10774A_03_PRJ.ssmssln and the T-SQL script 51 - Lab Exercise 1.sql.

X Task 2: Execute the T-SQL script


Execute the script by clicking Execute on the toolbar (or press F5 on the keyboard). This will execute the whole script. Observe the result and the database context. Which database is selected in the Available Databases box?

X Task 3: Execute a part of the T-SQL script


Observe the result. You should get the same result as in task 2. Tip: One way to highlight a portion of code is to hold down the Alt key while drawing a rectangle around it with your mouse. The code inside the drawn rectangle will be selected. Try it.

Highlight the SELECT statement in the T-SQL script under the task 2 description and click Execute.

Results: After this exercise, you should know how to open the T-SQL script and execute the whole script or just a specific statement inside the script.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-38

Introduction to T-SQL Querying

Exercise 2: Executing Queries That Filter Data Using Predicates


Scenario

The next T-SQL script is very similar to the first one. The SELECT statement retrieves the same columns from the HR.Employees table, but it uses a predicate in the WHERE clause to retrieve only rows that have the value USA in the country column. The main tasks for this exercise are as follows: 1. 2. Execute the T-SQL script. Apply the needed changes and execute the T-SQL script.

X Task 1: Execute the T-SQL script


Close all open script files.

Open the project file F:\10774A_Labs\10774A_03_PRJ\10774A_03_PRJ.ssmssln and the T-SQL script 61 - Lab Exercise 2.sql. Execute the whole script. You get an error. What is the error message? Why do you think you got this error?

X Task 2: Apply needed changes and execute the T-SQL script


Apply the needed changes to the script so that it will run without an error. (Hint: The SELECT statement is not the problem. Look at what is selected in the Available Databases box.) Test the changes by executing the whole script. Observe the result. Notice that the result has fewer rows than the result in exercise 1, task 2.

X Task 3: Uncomment the USE statement

As you learned in Module 2, comments in T-SQL scripts can be written inside the line by specifying --. The text after the two hyphens will be ignored by SQL Server. You can also specify a comment as a block starting with /* and ending with */. The text in between is treated as a block comment and is ignored by SQL Server. Uncomment the USE TSQL2012; statement. Save and close the T-SQL script. Open the T-SQL script 61 - Lab Exercise 2.sql again. Execute the whole script. Why did the script execute with no errors? Observe the result and notice the database context in the Available Databases box.

Results: After this exercise, you should have a basic understanding of database context and how to change it.

MCT USE ONLY. STUDENT USE PROHIBITED


3-39

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 3: Executing Queries That Sort Data Using ORDER BY


Scenario

The last T-SQL script provided by the IT department has a comment: This SELECT statement returns first name, last name, city and country information for all employees from the USA, ordered by last name. The main tasks for this exercise are as follows: 1. 2. Execute the T-SQL script. Uncomment the needed T-SQL statements and execute them.

X Task 1: Execute the T-SQL script


Open the project file F:\10774A_Labs\10774A_03_PRJ\10774A_03_PRJ.ssmssln and the T-SQL script 71 - Lab Exercise 3.sql. Execute the whole script. Observe the results. Why is the result window empty?

X Task 2: Uncomment the needed T-SQL statements and execute them

Observe that before the USE statement there are the characters -- which means that the USE statement is treated as a comment. There is also a block comment around the whole T-SQL SELECT statement. Uncomment both statements. First execute the USE statement and then execute the statement starting with the SELECT clause.

Observe the results. Notice that the results have the same rows as in exercise 1, task 2, but they are sorted by the lastname column.

Results: After this exercise, you should have an understanding how comments can be specified inside TSQL scripts.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

3-40

Introductio on to T-SQL Querying

Modul le Revie ew

Rev view Questi ions


1. 2. 3. Which ca ategory of T-SQ QL statements s concerns que erying and mo odifying data? What are e some examples of aggrega ate functions s upported by T T-SQL? Which SE ELECT stateme ent element will be processed d before a WH HERE clause?

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-1

Module 4
Writing SELECT Queries
Contents:
Lesson 1: Writing Simple SELECT Statements Lesson 2: Eliminating Duplicates with DISTINCT Lesson 3: Using Column and Table Aliases Lesson 4: Writing Simple CASE Expressions Lab: Writing Basic SELECT Statements 4-3 4-10 4-18 4-25 4-30

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-2 Writing SELECT Queries

Module Over rview

The SELECT statem ment is used to o query tables and views. Yo ou may also pe erform some m manipulation o of the data a with SELECT before returni ing the results s. It is likely tha at you will use the SELECT st tatement more e than any other single statement in T-SQL. This mod dule introduce es you to the f fundamentals of the SELECT statement, focusin ng on queries against a single table.

Obj jectives
Afte er completing this module, you y will be able to: Write simple SELECT statem ments. Eliminate dup plicates using the t DISTINCT clause. Use column and a table aliase es. Write simple CASE expressions.

MCT USE ONLY. STUDENT USE PROHIBITED


4-3

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Lesson n1

Writin ng Simp ple SELE ECT Statement ts

In n this lesson, yo ou will learn th he structure an nd format of th he SELECT stat tement, as wel ll as enhancem ments th hat will add fun nctionality and d readability to o your queries s.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Understand d the elements s of the SELECT T statement. Write simple single-table e SELECT querie es. Eliminate duplicate rows using the DIST TINCT clause. Add calcula ated columns to t a SELECT cla ause.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-4 Writing SELECT Queries

Ele ements of the SELECT Stateme ent

The SELECT and FROM F clauses are a the primar ry focus of this s module. You will learn mor re about the o other clau uses in later mo odules of this course. Howev ver, your unde erstanding of t the order of op perations in lo ogical que ery processing, from earlier in n the course, will w remain imp portant to und derstanding th he proper way to writ te SELECT quer ries. Rem member that th he FROM, WHERE, GROUP BY, B and HAVIN NG clauses will have been eva aluated before e the contents of the SE ELECT clause are a processed. Therefore, ele ements you write in the SELE ECT clause, espe ecially calculat ted columns and aliases, will not be visible e to the other c clauses. For More In nformation Additional inf formation on S SELECT elemen nts can be found at http://msdn n.microsoft.com m/en-us/librar ry/ms189499(v v=SQL.110).aspx.

MCT USE ONLY. STUDENT USE PROHIBITED


4-5

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Retrieving R Columns from f a Tab ble or View w

Th he SELECT clau use specifies th he columns fro om the source table(s) or vie ew(s) that you want to return n as the re esult set of the e query. In add dition to colum mns from the so ource table, yo ou may add co olumns in the form of ca alculated expre essions. Th he FROM claus se specifies the e name of the table or view that is the sou urce of the columns in the SELECT clause. To avoid d errors in nam me resolution, it i is a best pra ctice to specify fy both the sch hema and obje ect na ame of the tab ble, in the form m SCHEMA.OB BJECT, such as s Sales.Cust tomers.

If the table or view name contains irregular r characters, su uch as spaces o or other specia al characters, y you will ne eed to delimit, or enclose, th he name. T-SQ QL supports the e use of the A NSI standard d double quotes s "Sales Order r Details" and the SQL Server-specific S c square bracke ets [Sales O Order Detai ils].

En nd all statements with a sem micolon (;) char racter. In the c urrent version n of SQL Server r 2012, semico olons are an n optional term minator for mo ost statements s. However, fut ture versions w will require its use. For those e current us sages when a semicolon is re equired, such as some comm mon table exp ressions (CTEs) ) and some Se ervice Br roker statemen nts, the error messages m returned for a mis sing semicolon n are often cry yptic. Therefor re, you sh hould adopt th he practice of terminating t all statements w with a semicolo on. Note CT TEs will be cove ered later in th his course. For information o on Service Brok ker, see Course 10776 or Books Online.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-6 Writing SELECT Queries

Dis splaying Columns C

To display d column ns in a query, you y need to cr reate a comma a-delimited co olumn list. The order of the colu umns in your li ist will determine their displa ay in the outp ut, regardless of the order in n which they a are defi ined in the sou urce table. This s gives your qu ueries the abil ity to absorb c changes that o others may ma ake to the structure of th he table, such as adding or reordering r the columns.

T-SQ QL supports th he use of the asterisk, a or sta ar character (* *) to substitute e for an explicit column list. T This will retrieve all columns from th he source table e. While suitab ble for a quick test, avoid using the * in prod duction work, as changes made to the tab ble will cause t he query to re etrieve all curre ent columns in n the tabl les current defined order. Th his could cause e bugs or othe er failures in re eports or appli ications expecting a kno own number of f columns retu urned in a defined order. By using u an explic cit column list in your SELECT T clause, you w will always get t the desired re esults, as long as the columns exist in the table. If f a column is dropped, d you w will receive an error that will help you iden ntify the problem and fix your query.

MCT USE ONLY. STUDENT USE PROHIBITED


4-7

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Using U Calcu ulations in n the SELEC CT Clause

In n addition to re etrieving colum mns stored in the t source tab ble, a SELECT s statement can perform calcu ulations ce column dat an nd manipulatio ons. Calculatio ons can manipulate the sourc ta, and can als so use built-in T-SQL fu unctions, which h you will learn n about in module 8.

Si ince the results will appear in n a new colum mn, repeated o once per row o of the result set t, calculated ex xpressions in a SELECT clause e must be scal lar: they must return only a s single value. C Calculated expressions may m operate on n other column ns in the same e row, on built-in functions, o or a combination of the two o:
SELECT unitprice, qty, (unitprice ( * qty) FROM Sales.OrderDetails;

Th he results appe ear as follows:


unitprice --------------------14.00 9.80 34.80 18.60 qt ty -----12 10 0 5 9 --------------------168.00 98.00 174.00 167.40

Note that the new calculated column does not have a na me returned w with the results. To provide a name, yo ou will use a co olumn alias, which w you will learn about lat ter in this mod dule. To o use a built-in n T-SQL function on a colum mn in the SELEC CT list, you pa ss the name o of the column t to the fu unction as an input:
SELECT empid, lastname, hiredate, YE EAR(hiredate) ) FROM HR.Employees;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-8 Writing SELECT Queries

The results:
empid ----------1 2 3 lastname -------------------Davis Funk Lew hiredate ----------------------2002-05-01 00:00:00.000 2002-08-14 00:00:00.000 2002-04-01 00:00:00.000 ------2002 2002 2002

You will learn more about date functions, as well as others, later in this course. The use of YEAR in this example is provided only to illustrate calculated columns. Note Not all calculations will be recalculated for each row. SQL Server may calculate a functions result once at the time of query execution, and reuse the value for each row. This will be discussed later in the course.

MCT USE ONLY. STUDENT USE PROHIBITED


4-9

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Demonstra D ation: Writing Simple SELECT Statements

Demonstrati D ion Setup


1. .

On the virtu ual machine, click c Start, click All Program ms, click Micro osoft SQL Serv ver 2012, and click SQL Server r Managemen nt Studio. In the Connect to o Server wind dow, type Prose eware in the S Server name text box and click Connect. From m the File men nu, click Open, click Project/ /Solution, nav vigate to F:\10774 4A_Labs\10774 4A_04_PRJ\107 774A_04_PRJ.ss smssln, and cli ick Open. On the View w menu, click Solution Expl lorer. Open an nd execute the e 00 Setup.sq ql script file fro om within Solution Explorer. Open the 11 1 Demonstration A.sql script file. Follow the instructions co ontained within the commen nts of the scrip pt file.

2. . 3. . 4. .

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-10 Writing SE ELECT Queries

Lesson 2

Elimina ating Duplicat D es with DISTIN NCT

SQL L queries may display d duplica ate rows, even n if the source table has a ke ey column enfo orcing uniquen ness. Typically this is the case when you y retrieve on nly a few of the e columns in a table. In this lesson, you wi ill lear rn how to eliminate duplicates using the DISTINCT D claus e.

Les sson Objecti ives


In th his lesson, you u will learn to: Understand how h SQL query y results are no ot true sets an d may include e duplicates. Understand how h DISTINCT may be used to remove dup plicate rows fr rom the SELECT results. Write SELECT T DISTINCT clauses.

MCT USE ONLY. STUDENT USE PROHIBITED


4-11

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

SQL Sets an nd Duplica ate Rows

While W the theor ry of relational l databases cal lls for unique r rows in a table e, in practice SQL query resu ults are no ot true sets. Th he rows retriev ved by a query y are not guara anteed to be u unique, even w when they com me from a source table that uses a prim mary key to differentiate eac ch row. Nor ar re the rows guaranteed to be e re eturned in any particular ord der, which you will learn how w to address w with ORDER BY in module 6. Add to this the fact that the default d behavio or of a SELECT T statement is t to include the keyword ALL, , and yo ou can begin to t see why dup plicate values might be retur rned by a query, especially w when you inclu ude on nly some of th he columns in a table (and omit the unique e columns). Fo or example, co onsider a query y that retrieves s country nam mes from the Sa ales.Customers table:
SELECT country FROM Sales.Customers;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-12 Writing SELECT Queries

A partial result shows many duplicate country names, which at best is too long to be easy to interpret. At worst, it gives a wrong answer to the question How many countries are represented among our customers?
country ------Germany Mexico Mexico UK Sweden Germany Germany France UK Austria Brazil Spain France Sweden ... Germany France Finland Poland (91 row(s) affected)

The reason for this output is that, by default, a SELECT clause contains a hidden default ALL statement:
SELECT ALL country FROM Sales.Customers;

In the absence of further instruction, the query will return one result for each row in the customers table, but since only the country column is specified, you will see only that column for all 91 rows.

MCT USE ONLY. STUDENT USE PROHIBITED


4-13

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Understand U ding DISTINCT

Re eplacing the default d SELECT ALL clause with SELECT DIS STINCT will filte er out duplicat tes in the result set. SE ELECT DISTINC CT specifies tha at the result se et must contai n only unique e rows. Howeve er, it is importa ant to un nderstand that t the DISTINCT T option opera ates only on th he set of colum mns returned b by the SELECT clause. It does not take e into account any other uniq que columns i n the source t table. DISTINCT also operate es on all of f the columns in the SELECT list, not just th he first column n. Th he logical orde er of operation ns also ensures s that the DIST TINCT operato or will remove rows that may y have already been pr rocessed by WHERE, W HAVING G, and GROUP P BY clauses.

Continuing the previous exam mple of countr ries from the S ales.Customer rs table, to elim minate the dup plicate va alues, replace the t silent ALL default with DISTINCT: D
SELECT DISTINCT country FROM Sales.Customers;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-14 Writing SELECT Queries

This will yield the desired results. Note that while the results appear to be sorted, this is not guaranteed by SQL Server. The result set now contains only one instance of each unique output row:
Country --------Argentina Austria Belgium Brazil Canada Denmark Finland France Germany Ireland Italy Mexico Norway Poland Portugal Spain Sweden Switzerland UK USA Venezuela (21 row(s) affected)

Note You will learn additional methods for filtering out duplicate values in module 6. Once you have learned them, you may wish to consider the relative performance costs of filtering with SELECT DISTINCT versus those other means.

MCT USE ONLY. STUDENT USE PROHIBITED


4-15

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

SELECT DIS STINCT Syn ntax

Re emember that t DISTINCT loo oks at rows in the t output set,, created by th he SELECT clau use. Therefore only un nique combin nations of colu umn values wil ll be returned by a SELECT D DISTINCT claus se. For example, if you qu uery a table with w the following data in it, you y might obs serve that ther re are only fou ur unique first n names an nd four unique e last names:
SELECT firstname, lastna ame FROM Sales.Customers;

Th he result:
firstname ---------Sara Don Sara Don Judy Judy Yael Y lastname -------------------Davis Funk Lew Davis Lew Funk Peled

However, a SELECT DISTINCT query against t both column s will retrieve a all unique com mbinations of t the two co olumns, which in this case, is s the same seven employees s. For a list of u unique first names only, exec cute a SE ELECT DISTINC CT only against the firstname e column:
SELECT DISTINCT firstnam me FROM Sales.Customers;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-16 Writing SELECT Queries

The result:
firstname ---------Don Judy Sara Yael (4 row(s) affected)

A challenge in designing such queries is that while you may need to retrieve a distinct list of values from one column, you might need to see additional attributes (columns) from other columns. Later in this course, you will see how to combine DISTINCT with the GROUP BY clause as a way of further processing and displaying information about distinct lists of values.

MCT USE ONLY. STUDENT USE PROHIBITED


4-17

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Demonstra D ation: Elimi inating Du uplicates w with DISTIN NCT

In n this demonst tration, you will see how to eliminate e dupl icate rows wit h DISTINCT.

Demonstrati D ion Setup


1. .

On the virtu ual machine, click c Start, click All Program ms, click Micro osoft SQL Serv ver 2012, and click SQL Server r Managemen nt Studio. In the Connect to o Server wind dow, type Prose eware in the S Server name text box and click Connect. From m the File men nu, click Open n, click Project t/Solution, navigate to F:\10774 4A_Labs\10774 4A_04_PRJ\107 774A_04_PRJ.ss smssln and clic ck Open. From the View V menu, clic ck Solution Ex xplorer. Open the 21 2 Demonstration B.sql script file. Follow the instructions co ontained within the commen nts of the scrip pt file.

2. . 3. . 4. .

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-18 Writing SE ELECT Queries

Lesson 3

Using Column n and Table Ali iases

Whe en retrieving data d from a tab ble or view, a SQL S query will l name each co olumn after its s source. If des sired, colu umns may be relabeled r by th he use of aliase es in the SELEC CT clause. How wever, column ns created with h expressions will no ot be named automatically. a Column aliase es may be used d to provide custom column n headers. At the ta able level, alias ses may be use ed in the FROM M clause to pro ovide a convenient way of refe erring to a table elsewhere in n the query, en nhancing reada ability.

Les sson Objecti ives


In th his lesson you will learn how w to: Use aliases to o refer to colum mns in a SELEC CT list. Use aliases to o refer to colum mns in a FROM M clause. Understand the impact of the t logical order of query pr rocessing on a liases.

MCT USE ONLY. STUDENT USE PROHIBITED


4-19

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Using U Alias ses to Refe er to Colum mns

Column aliases can be used to o relabel colum mns when retu urning the resu ults of a query y. For example, , cryptic na ames of colum mns in a table such s as qty ma ay be replaced d with quantity y.

Ex xpressions that t are not based d on a source column in the e table will not t have a name provided in th he result se et. This include es calculated expressions e and d function call s. While T-SQL L doesnt requ uire that a colu umn in a re esult set have a name, its a good g idea to provide p one. In n T-SQL, there are multiple methods m of cre eating a colum mn alias, with id dentical outpu ut results. One method is to use the AS keyword to se eparate the co olumn or expre ession from the e alias:
SELECT orderid, unitpric ce, qty AS qu uantity FROM Sales.OrderDetails;

Another method is to assign the t alias befor re the column or expression using the equ uals sign as the e se eparator:
SELECT orderid, unitpric ce, quantity = qty FROM Sales.OrderDetails;

Finally, you can simply assign the alias immediately follow wing the colum mn name, altho ough this is no ot a re ecommended method:
SELECT orderid, unitpric ce, qty quant tity FROM Sales.OrderDetails;

While W there is no n difference in n performance e or execution,, a difference i in readability m may cause you u to ch hoose one or the t other as a convention.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-20 Writing SELECT Queries

Warning Column aliases can also be accidentally created, by omitting a comma between two column names in the SELECT list. For example the following creates an alias for the unitprice column deceptively labeled quantity:
SELECT orderid, unitprice quantity FROM Sales.OrderDetails;

The result:
orderid ----------10248 10248 10248 10249 quantity --------------------14.00 9.80 34.80 18.60

As you can see, this could be difficult to identify and fix in a client application. The only way to avoid this problem is to carefully list your columns, separating them properly with commas and adopting the AS style of aliases to make it easier to spot mistakes. Question: Which style of column aliases do you prefer? Why?

MCT USE ONLY. STUDENT USE PROHIBITED


4-21

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Using U Alias ses to Refe er to Table es

Aliases may also o be used in th he FROM claus se to refer to a table, which c d save can improve readability and re edundancy when referencing g the table else ewhere in the query. While t this module ha as focused on singleta able queries, which w dont nec cessarily benef fit from table a aliases, this tec chnique will pr rove useful as you le earn more com mplex queries in subsequent modules.

To o create a table alias in a FRO OM clause, yo ou will use synt tax similar to s several of the c column alias te echniques. You u may use the keyword AS to o separate the e table name fr rom the alias. T This style is preferred:
SELECT orderid, unitpric ce, qty FROM Sales.OrderDetails AS OD;

Yo ou may omit the t keyword AS and simply follow f the tabl le name with t the alias:
SELECT orderid, unitpric ce, qty FROM Sales.OrderDetails OD;

To o combine tab ble and column n aliases in the e same SELECT T statement, us se the followin ng approach:
SELECT OD.orderid, OD.un nitprice, OD.qty FROM Sales.OrderDetails AS OD;

Note

Th here is no table e alias equivale ent of the use of the equals sign (=) in a co olumn alias.

ight not yet se Si ince this modu ule focuses on single-table queries, q you mi ee a benefit to o using table al liases. In th he next module, you will lear rn how to retri ieve data from m multiple tabl es in a single S SELECT statem ment. In th hose queries, the use of table e aliases to rep present table n names will bec come quite use eful.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-22 Writing SE ELECT Queries

The Impact of o Logical Processing g Order on n Aliases

An issue i may arise e in the use of f column aliase es: aliases crea ted in the SELECT clause ma ay not be refer rred to in n other clauses in the query, , such as a WH HERE or HAVIN NG clause. This s is due to the logical order q query proc cessing. The WHERE W and HA AVING clauses are processed d before the SE ELECT clause and its aliases a are evaluated. An exc ception to this is the ORDER BY clause. An example is pro ovided here fo or illustration a and will run without error:
SE ELECT orderid d, unitprice, qty as quan ntity FR ROM Sales.Ord derDetails OR RDER BY quant tity;

How wever, the follo owing example e will return an n error, as the WHERE clause e has been pro ocessed before e the SELE ECT clause def fines the alias:
SE ELECT orderid d, unitprice, qty as quan ntity FR ROM Sales.Ord derDetails WH HERE quantity y > 10;

The resulting erro or message:


Msg 207, Level 16, State 1, 1 Line 1 Invalid column n name 'quant tity'.

As a result, you will often need to repeat an expression e mor re than once: i in the SELECT clause, where you may y create an alia as to name the e column, and in the WHERE E or HAVING c clause.
SE ELECT orderid d, YEAR(order rdate) as ord deryear FR ROM Sales.Ord ders WH HERE YEAR(ord derdate) = '2 2008'

MCT USE ONLY. STUDENT USE PROHIBITED


4-23

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Additionally, within the SELECT clause, you may not refer to a column alias that was defined in the same SELECT statement, regardless of column order. The following statement will return an error:
SELECT productid, unitprice as price, price * qty as total FROM Sales.OrderDetails;

The resulting error:


Msg 207, Level 16, State 1, Line 1 Invalid column name 'price'.

To correct the error, refer to the source column in the calculated column:
SELECT productid, unitprice as price, unitprice * qty as total FROM Sales.OrderDetails

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-24 Writing SE ELECT Queries

De emonstration: Using Column and a Table A Aliases

Dem monstration n Setup


1.

On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, and cl lick SQL Server Management M Studio. In the e Connect to S Server window w, type Prosew ware in the Ser rver name text bo ox and click Co onnect. From the t File menu , click Open, c click Project/S Solution, navig gate to F:\10774A_ _Labs\10774A_ _04_PRJ\10774 4A_04_PRJ.ssm mssln, and click k Open. From the View menu, click Solution Exp plorer. Open a nd execute the 00 Setup.sql script file from within Solutio on Explorer. Open the 31 Demonstrati ion C.sql script t file. Follow the ins file. structions cont tained within the t comments s of the script f

2. 3. 4.

MCT USE ONLY. STUDENT USE PROHIBITED


4-25

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n4

Writin ng Simp ple CAS SE Expre essions

A CASE expression extends th he ability of a SELECT S clause to manipulate e data as it is retrieved. Often when writing w a query, , you need to substitute s a va alue from a co lumn of a tabl le with anothe er value. While you will w learn how to perform this s kind of looku up from anothe er table later in this course, you can also p perform ba asic substitutio ons using simp ple CASE expre essions in the S SELECT clause.. In real-world environments s, CASE is often used to help make cry yptic data held d in a column more meaning gful. A CASE expression returns a scalar s (single-v valued) value b based on cond ditional logic, o often with mul ltiple co onditions. As a scalar value, it i may be used d wherever sin gle values can n be used. Besi ides the SELEC CT st tatement, CASE expressions can c be used in n WHERE, HAV VING, and ORD DER BY clauses s.

Le esson Objec ctives


In n this lesson yo ou will learn ho ow to: Understand d the use of CA ASE expression ns in SELECT cl lauses. Understand d the simple fo orm of a CASE expression. Write a sim mple CASE expr ression in a SELECT clause.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-26 Writing SE ELECT Queries

Using CASE Expression E ns in SELEC CT Clauses s

In T-SQL, T CASE ex xpressions retu urn a single, or r scalar, value. Unlike some o other program mming languag ges, CAS SE expressions are not statem ments, nor do they specify th he control of p programmatic flow. Instead, they are used in SELECT clauses (and d other clauses s) to return the e result of an e expression. The e results appea ar as a calc culated column n and should be b aliased for clarity. c

In T-SQL T queries, CASE expressions are often used to provid de an alternati ive value for o one stored in th he source table. For example, e a CA ASE expression might be used d to provide a friendly text n name for some ething stor red as a compa act numeric co ode.

MCT USE ONLY. STUDENT USE PROHIBITED


4-27

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Forms of CA ASE Expre essions

In n T-SQL, CASE expressions may m take one of o two forms: si imple CASE or r searched (Boolean) CASE.

Si imple CASE ex xpressions, the subject of this s lesson, comp pare an input v value to a list o of possible ma atching va alues. 1. . 2. . 3. .

If a match is found, the first matching value v is returne ed as the resu lt of the CASE expression. M Multiple matches are not permitte ed. If no match h is found, a CA ASE expression n returns the v value found in an ELSE clause e, if one exists. If no match h is found and no ELSE clause is present, th he CASE expre ession returns a NULL.

Fo or example, the following CA ASE expression n substitutes a descriptive ca ategory name for the catego oryid va alue stored in the Production n.Categories ta able. Note tha at is not a JOIN N operation, ju ust a simple su ubstitution using a single tab ble:
SELECT T productid, productname, , categoryid CASE categoryid c WHEN 1 THEN N Beverages WHEN 2 THEN N Condiments WHEN 2 THEN N Confections ELSE Unkno own Category END AS S categorynam me FROM Production.Ca P ategories

Th he result:
productid --------101 102 103 productname -----------Tea Mustard Dinner Rolls categoryid c ---------1 2 9 categoryname c --------------------Be everages Co ondiments Un nknown Catego ory

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-28 Writing SELECT Queries

Note The preceding example is presented for illustration only and will not run against the sample databases provided with the course.

Searched (Boolean) CASE expressions compare an input value to a set of logical predicates or expressions. The expression can contain a range of values to match against. Like a simple CASE expression, the return value is found in the THEN clause of the matching value. Note Due to their dependence on predicate expressions, which will not be covered until later in this course, further discussion of searched CASE expressions are beyond the scope of this lesson. See "CASE (Transact-SQL)" in Books Online at http://msdn.microsoft.com/enus/library/ms181765(v=SQL.110).aspx

MCT USE ONLY. STUDENT USE PROHIBITED


4-29

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Demonstra D ation: Simp ple CASE Expressions s

Demonstrati D ion Setup


1. .

On the virtu ual machine, click c Start, click All Program ms, click Micro osoft SQL Serv ver 2012, and click SQL Server r Managemen nt Studio. In the Connect to o Server wind dow, type Prose eware in the S Server name text box and click Connect. From m the File men nu, click Open n, click Project t/Solution, navigate to F:\10774 4A_Labs\10774 4A_04_PRJ\107 774A_04_PRJ.ss smssln, and cli ick Open. From the View V menu, clic ck Solution Ex xplorer. Open n and execute the 00 Setup p.sql script file from within Solution Explorer. Open the 41 4 Demonstration D.sql scr ript file. Follow the instructions co ontained within the commen nts of the scrip pt file.

2. . 3. . 4. .

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-30 Writing SE ELECT Queries

Lab: Writing W Basic B SE ELECT St tatements

Lab b Setup
For this lab, you will w use the ava ailable virtual machine m enviro onment. Befor re you begin the lab, you mu ust mplete the follo owing steps: com 1. 2. 3. On the host computer, c click k Start, point to t Administra ative Tools, an nd click Hyper r-V Manager. Maximize the e Hyper-V Ma anager window w. If the virtual machine m 1077 74A-MIA-DC1 1 is not started : 4. In the Virtual Machine es list, right-click 10774A-M MIA-DC1 and c click Start. Right-clic ck 10774A-MIA-DC1 and click Connect.

In the Virtual Machine e Connection window, wait until the Press CTRL+ALT+ +DELETE to log g on message appears, and then close the e Virtual Mach hine Connect tion window.

If the virtual machine m 1077 74A-MIA-SQL1 is not started d: In the Virtual Machine es list, right-click 10774A-M MIA-SQL1 and d click Start. Right-clic ck 10774A-MIA-SQL1 and click c Connect .

In the Virtual Machine e Connection window, wait until the Press CTRL+ALT+ +DELETE to log g on message appears, and then close the e Virtual Mach hine Connect tion window.

5. 6.

In Virtual Ma achine Conne ection window w, click the Rev vert toolbar ico on. If you are pro ompted to con nfirm that you want to revert t, click Revert. Wait for the r revert action to complete.

MCT USE ONLY. STUDENT USE PROHIBITED


4-31

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

7.

If you are not already logged on:

In the Virtual Machine Connection window, click the Ctrl-Alt-Delete menu item on the Action menu. Click Switch User, and then click Other User. Log on using the following credentials: User name: AdventureWorks\Administrator Password: Pa$$w0rd

8. 9.

In the Virtual Machine Connection window, click Full Screen Mode on the View menu.

If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.

Lab Scenario

You are a business analyst for Adventure Works who will be writing reports using corporate databases stored in SQL Server 2012. You have been provided with a set of business requirements for data and will write basic T-SQL queries to retrieve the specified data from the databases. Important When comparing your results with the provided sample outputs, the column ordering and total number of affected rows should always match. However, remember that the order of the rows in the output of a query without an ORDER BY clause is not guaranteed. Therefore, the order of the rows in the sample outputs may be different than yours. Also, the answer outputs include abbreviated results.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-32 Writing SELECT Queries

Exercise 1: Writing Simple SELECT Statements


Scenario

As a business analyst, you want to get a better understanding of your corporate data. Usually the best approach for an initial project is to get an overview of the main tables and columns involved so that you can better understand different business requirements. After the initial overview of the tables, you will have to provide a report for the marketing department because the marketing staff would like to send invitation letters for a new campaign. You will use the TSQL2012 sample database. The main tasks for this exercise are as follows: 1. 2. 3. Write a query to display all rows and all columns from the Sales.Customers table.

Write a query against the Sales.Customers table, retrieving the contactname, address, postalcode, city, and country columns. Use SQL Server Management Studio (SSMS) to identify the total number of rows in the Sales.Customers table.

X Task 1: View all the tables in the TSQL2012 database in Object Explorer
Using SSMS, connect to Proseware using Windows authentication (if you are connecting to an onpremises instance of SQL Server) or SQL Server authentication (if you are using SQL Azure). In Object Explorer, expand the TSQL2012 database and expand the Tables folder. Take a look at the names of the tables in the Sales schema.

X Task 2: Write a simple SELECT statement

Open the project file F:\10774A_Labs\10774A_04_PRJ\10774A_04_PRJ.ssmssln and the T-SQL script 51 - Lab Exercise 1.sql. To set your database context to that of the TSQL2012 database, highlight the statement USE TSQL2012; and execute the highlighted code. After executing this statement, the TSQL2012 database should be selected in the Available Databases box. In subsequent exercises, you will simply be instructed to ensure that you are connected to the TSQL2012 database. Write a SELECT statement that will return all rows and all columns from the Sales.Customers table. Tip You can use drag-and-drop functionality to drag items like table and column names from Object Explorer to the query window. Write the same SELECT statement using the drag-and-drop functionality.

Execute the written statement and compare the results that you got with the desired results shown in the file 52 - Lab Exercise 1 - Task 2 Result.txt.

MCT USE ONLY. STUDENT USE PROHIBITED


4-33

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

X Task 3: Write a SELECT statement that includes specific columns


Expand the Sales.Customers table in Object Explorer and expand the Columns folder. Observe all columns in the table.

Write a SELECT statement to return the contactname, address, postalcode, city, and country columns.

Execute the written statement and compare the results that you got with the desired results shown in the file 53 - Lab Exercise 1 - Task 3 Result.txt. What is the number of rows affected by the last query? (Tip: Because you are issuing a SELECT statement against the whole table, the number of rows will be the same as number of rows for the whole Sales.Customer table.)

Results: After this exercise, you should know how to create simple SELECT statements to analyze existing tables.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-34 Writing SELECT Queries

Exercise 2: Eliminating Duplicates Using DISTINCT


Scenario

After supplying marketing department with a list of all customers for a new campaign, you get a request to provide a list of all the different countries that the customers come from. The main tasks for this exercise are as follows: 1. 2. 3. Write a SELECT statement showing only the country column from the Sales.Customers table. Write a SELECT statement showing only distinct countries. Identify how many different countries there are in the Sales.Customers table.

X Task 1: Write a SELECT statement that includes a specific column


Open the project file F:\10774A_Labs\10774A_04_PRJ\10774A_04_PRJ.ssmssln and T-SQL script 61 Lab Exercise 2.sql. Ensure that you are connected to the TSQL2012 database. Write a SELECT statement against the Sales.Customers table showing only the country column.

Execute the written statement and compare the results that you got with the desired results shown in the file 62 - Lab Exercise 2 - Task 1 Result.txt.

X Task 2: Write a SELECT statement that uses the DISTINCT clause


Copy the SELECT statement in Task 1 and modify it to return only distinct values.

Execute the written statement and compare the results that you got with the desired results shown in file 63 - Lab Exercise 2 - Task 2 Result.txt. How many rows did the query in Task 1 return? How many rows did the query in Task 2 return? Under which circumstances do the following queries against the Sales.Customers table return the same result?
SELECT city, region FROM Sales.Customers; SELECT DISTINCT city, region FROM Sales.Customers;

Is the DISTINCT clause being applied to all columns specified in the query or just the first column?

Results: After this exercise, you should have an understanding of how to return only the different (distinct) rows in the result set of a query.

MCT USE ONLY. STUDENT USE PROHIBITED


4-35

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 3: Using Table and Column Aliases


Scenario
After getting the initial list of customers, the marketing department would like to have more readable titles for the columns and a list of all products in the TSQL2012 database. The main tasks for this exercise are as follows: 1. 2. 3. Write a select statement to return the contactname and contacttitle columns from the Sales.Customers table using an alias for the table. Write a query to return the contactname, contacttitle, and companyname columns from the Sales.Customers table using table and column aliases. Write a query to return all product names.

X Task 1: Write a SELECT statement that uses a table alias


Open the project file F:\10774A_Labs\10774A_04_PRJ\10774A_04_PRJ.ssmssln and T-SQL script 71 Lab Exercise 3.sql. Ensure that you are connected to the TSQL2012 database.

Write a SELECT statement to return the contactname and contacttitle columns from the Sales.Customers table, assigning C as the table alias. Use the table alias C to prefix the names of the two needed columns in the SELECT list. The benefit of using table aliases will become clearer in future modules when topics such as joins and subqueries will be introduced. Execute the written statement and compare the result that you got with the recommended result shown in the file 72 - Lab Exercise 3 - Task 1 Result.txt.

X Task 2: Write a SELECT statement that uses column aliases


Write a SELECT statement to return the contactname, contacttitle, and companyname columns. Assign these columns with the aliases Name, Title, and Company Name, respectively, in order to return more human-friendly column titles for reporting purposes.

Execute the written statement and compare the results that you got with the desired results shown in the file 73 - Lab Exercise 3 - Task 2 Result.txt. Notice specifically the titles of the columns in the desired output.

X Task 3: Write a SELECT statement that uses a table alias and a column alias

Write a query to display the productname column from the Production.Products table using P as the table alias and Product Name as the column alias.

Execute the written statement and compare the results that you got with the desired results shown in the file 74 - Lab Exercise 3 - Task 3 Result.txt.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-36 Writing SELECT Queries

X Task 4: Analyze and correct the query


A developer has written a query to retrieve two columns (city and region) from the Sales.Customers table. When the query is executed, it returns only one column. Your task is to analyze the query, correct it to return two columns, and explain why the query returned only one column.
SELECT city country FROM Sales.Customers;

Execute the query exactly as written inside a query window and observe the result. Correct the query to return the city and country columns from the Sales.Customers table.

Why did the query return only one column? What was the title of the column in the output? What is the best practice when using aliases for columns to avoid such errors?

Results: After this exercise, you know how to use aliases for table and column names.

MCT USE ONLY. STUDENT USE PROHIBITED


4-37

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 4: Using a Simple CASE Expression


Scenario

Your company produces a long list of products, and the members of the marketing department would like to have product category information in their reports. They have supplied you with a document containing the following mapping between the product category IDs and the product category names: categoryid 1 2 3 4 5 6 7 8 Categoryname Beverages Condiments Confections Dairy Products Grains/Cereals Meat/Poultry Produce Seafood

Because of an active marketing campaign, they would like to include product category information in their reports. The main tasks for this exercise are as follows: 1. 2. Write a SELECT statement to retrieve the productname and categoryid columns from the Production.Products table. Modify an existing query to include a simple CASE expression based on the mapping information supplied by the marketing department to list the category name for each product.

X Task 1: Write a SELECT statement


Open the project file F:\10774A_Labs\10774A_04_PRJ\10774A_04_PRJ.ssmssln and T-SQL script 81 Lab Exercise 4.sql. Ensure that you are connected to the TSQL2012 database. Write a SELECT statement to display the categoryid and productname columns from the Production.Products table.

Execute the written statement and compare the results that you got with the desired results shown in the file 82 - Lab Exercise 4 - Task 1 Result.txt.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

4-38 Writing SELECT Queries

X Task 2: Write a SELECT statement that uses a CASE expression

Enhance the SELECT statement in task 1 by adding a CASE expression that generates a result column named categoryname. The new column should hold the translation of the category ID to its respective category name based on the mapping table supplied earlier. Use the value Other for any category IDs not found in the mapping table. Execute the written statement and compare the result that you got with the desired output shown in the file 83 - Lab Exercise 4 - Task 2 Result.txt.

X Task 3: Write a SELECT statement that uses a CASE expression to differentiate campaign-focused products

Modify the SELECT statement in task 2 by adding a new column named iscampaign. This column will show the description Campaign Products for the categories Beverages, Produce, and Seafood and the description Non-Campaign Products for all other categories.

Execute the written statement and compare the results that you got with the desired results shown in the file 84 - Lab Exercise 4 - Task 3 Result.txt.

Results: After this exercise, you should know how to use CASE expressions to write simple conditional logic.

MCT USE ONLY. STUDENT USE PROHIBITED


4-39

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Modu ule Revi iew and d Takeaw ways

Review R Ques stions


1. 2. 3. Why is the use of SEL LECT * not a re ecommended practice? What will w happen if you y omit a com mma between n column name es in a SELECT clause? What kind k of result does d a simple CASE C statemen nt return?

Best B Practice es
1.

Termin nate all SQL sta atements with a semicolon. T This will make your code mo ore readable, a avoid certain parsing errors s, and will prot tect your code e against changes in future v versions of SQL Server.

2.

Consider standardizing your code on the AS key yword for label ling column an nd table aliase es. This will ma ake your code easier to read and avoids ac ccidental aliase es.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-1

Module 5
Querying Multiple Tables
Contents:
Lesson 1: Understanding Joins Lesson 2: Querying with Inner Joins Lesson 3: Querying with Outer Joins Lesson 4: Querying with Cross Joins and Self-Joins Lab: Querying Multiple Tables 5-3 5-11 5-17 5-23 5-33

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-2 Querying Multiple M Tables

Module Over rview

In re eal-world environments, it is s likely that the e data you nee ed to query is stored in mult tiple locations. . Earlier, you learne ed how to write basic single-table queries. In this module, you will lear rn how to writ te rver 2012. You que eries that comb bine data from m multiple sour rces in SQL Ser u will do so by writing querie es containing joins, which w allow yo ou to retrieve data d from two o (or more) tab bles based on d data relationsh hips betw ween the table es.

Obj jectives
Afte er completing this module, you y will be able to: Describe how w multiple tables may be que eried in a SELE ECT statement using joins. Write queries s that use inner joins. Write queries s that use oute er joins. Write queries s that use self-j joins and cross s joins.

MCT USE ONLY. STUDENT USE PROHIBITED


5-3

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Lesson n1

Unde erstanding Join ns

In n this lesson, yo ou will learn th he fundamenta als of joins in S SQL Server 201 arn how the FROM 12. You will lea clause in a T-SQ QL SELECT statement creates s intermediate virtual tables that will be co onsumed by su ubsequent pha ases of the que ery. You will le earn how an un nrestricted com mbination of r rows from two tables yields a Cartesia an product. Yo ou will also learn about the c common join t types in T-SQL L multi-table queries.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe th he relationship between the FROM Clause and virtual tab bles in a SELEC CT statement Describe a Cartesian prod duct and how it may be crea ated by a join Describe th he common joi in types in SQL L queries Understand d the differenc ce between AN NSI SQL-89 and d SQL-92 join syntax

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-4 Querying Multiple M Tables

The FROM Clause C and Virtual Ta ables

Earlier, you learne ed about the lo ogical order of f operations pe erformed whe en SQL Server 2 2012 processe es a que ery. You will rec call that the FR ROM clause of f a SELECT stat tement is the f first phase to b be processed. This clau use determines s which table or o tables will be b the source o of rows for the e query. As you u will see in this mod dule, this will hold h true whet ther you are querying a sing gle table or bri nging togethe er multiple tab bles as the source of your query. In order o to learn about a the additional capabilities of the FR OM clause, it w will be useful t to think of the e func ction of the cla ause as creatin ng and populating a virtual t table. This virtu ual table will h hold the outpu ut of the FROM clause and will be used subsequently by other ph hases of the SE ELECT stateme ent, such as the WHERE clause. As s you add addi itional function nality, such as join operators s, to a FROM c clause, it will be help pful to think of f the purpose of the FROM clause c elemen ts as either to add rows to, o or remove row ws from m, the virtual table. v table cr reated by a FR ROM clause is a logical entity y only. In SQL Server Note The virtual 2012, no phy ysical table is created, c wheth her persistent o or temporary, to hold the re esults of the FROM cl lause, as it is passed p to the WHERE W clause or other subse equent phases s. The syntax for the e SELECT statement clause th hat you have u used in earlier queries in this s course has app peared as follow ws:
SE ELECT ... FR ROM <table> AS A <alias>;

MCT USE ONLY. STUDENT USE PROHIBITED


5-5

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

You learned earlier that the FROM clause is processed first, and as a result, any table aliases you create there may be referenced in the SELECT clause. You will see numerous examples of table aliases in this module. While they are optional, except in the case of self-join queries, you will quickly see how they can be a convenient tool when writing your queries. Compare the following two queries, which have the same output, but which differ in their use of aliases. (Note that the examples use a JOIN clause, which will be covered later in this module.) The first query uses no table aliases:
USE TSQL2012 ; GO SELECT Sales.Orders.orderid, Sales.Orders.orderdate, Sales.OrderDetails.productid,Sales.OrderDetails.unitprice, Sales.OrderDetails.qty FROM Sales.Orders JOIN Sales.OrderDetails ON Sales.Orders.orderid = Sales.OrderDetails.orderid ;

The second example retrieves the same data but uses table aliases:
USE TSQL2012 ; GO SELECT o.orderid, o.orderdate, od.productid, od.unitprice, od.qty FROM Sales.Orders AS o JOIN Sales.OrderDetails AS od ON o.orderid = od.orderid ;

As you can see, the use of table aliases improves the readability of the query, without affecting the performance. It is strongly recommended that you use table aliases in your multi-table queries. Note Once a table as been designated with an alias in the FROM clause, you must use the alias when referring to columns from that table in other clauses. Failure to do so will cause a syntax error.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-6 Querying Multiple M Tables

Joi in Termino ology: Cart tesian Product

Whe en learning ab bout writing multi-table m queries in T-SQL, it is important t to understand d the concept of Cart tesian product ts. In mathema atics, a Cartesia an product is t the product of f two sets. The e product of a set of 2 ite ems and a set of 6 items is a set of 12 item ms, or 6 x 2. In databases, a C Cartesian product is the result of joining every row of one input table t to every row of anothe er input table. The product o of a table with 10 row ws and a table with w 100 rows is a result set with 1000 row ws. red outcome. Typically, a Ca For most T-SQL queries, a Carte esian product is i not the desir artesian product occu urs when two input tables are joined witho out considerin ng any logical relationships b between them. In the absence of an ny information about relation nships, the SQ QL Server query y processor will output all possible combinations of rows.

While this can hav ve some practical application ns, such as cre eating a table o of numbers or r generating te est data a, it is not typically useful an nd can have sev vere performa ance effects. Yo ou will learn a useful applica ation of Cartesian C joins later in this module. m Note In th he next topic, you y will compa are two differe ent methods fo or specifying the syntax of a join. You will see that one method may m lead you t toward writing g accidental Ca artesian eries. product que

MCT USE ONLY. STUDENT USE PROHIBITED


5-7

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Overview O of o Join Typ pes

To o populate the e virtual table produced by the t FROM clau use in a SELECT T statement, SQL Server uses join op perators. These operators ad dd or remove rows r from the virtual table, before it is han nded off to su ubsequent logical phases of the SELECT sta atement:

A cross join n operator (CROSS JOIN) add ds all possible combinations of the two inp put tables' row ws to the virtual table e. Any filtering g of the rows will w happen in a WHERE clau use. For most q querying purpo oses, this operato or is to be avo oided. An inner join operator (IN NNER JOIN, or r just JOIN) firs st creates a Cartesian produc ct, and then fil lters the results using the predicat te supplied in the t ON clause e, removing an ny rows from th he virtual table e that do not satis sfy the predica ate. The inner join j type is a v very common type of join fo or retrieving ro ows with attributes that match acro oss tables, such as matching g Customers to o Orders by a c common custid.

An outer jo oin operator (LEFT OUTER JO OIN, RIGHT OU UTER JOIN, FUL LL OUTER JOIN N) first creates sa Cartesian product, p and lik ke an inner join, filters the re esults to find r rows that matc ch in each table. However, all rows from one o table are preserved, p adde ed back to the e virtual table after the initia al filter is applied. NU ULLs are placed d on attributes s where no ma atching values s are found. Note Un nless otherwise e qualified with h CROSS or OU UTER, the JOIN N operator def faults to an INNER join n.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-8 Querying Multiple M Tables

T-S SQL Syntax x Choices

Thro ough the histo ory of versions of SQL Server r, the product has changed t to keep pace w with changes in the ANS SI standards fo or the SQL lang guage. One of f the most nota able places wh here these cha anges are visible is in the syntax for the join operator in a FROM cla ause: In ANSI A SQL-89, no n ON operato or was defined. Joins were re epresented in a comma-sepa arated list of ta ables, and any filtering, such as for an inner join, wa as performed i n the WHERE clause. This sy yntax is still supported by SQL L Server 2012, but due to the e complexity o of representing g the filters for r an outer join n in the WHERE clause e, as well as an ny other filterin ng, it is not rec commended to o use this. Add ditionally, if a WHERE clause is accidentally a om mitted, ANSI SQL-89-style jo oins can easily become Carte esian products, with the resulting perfo ormance prob blems they cause. The follow wing queries illu ustrate this syn ntax, and this pote ential problem m:
US SE TSQL2012; GO O /* This is ANSI SQL-89 S syntax x for an inne er join, with h the filteri ing performed in the WHE ERE clause. */ / SE ELECT c.compa anyname, o.or rderdate FR ROM Sales.Cus stomers AS c, Sales.Order rs AS o WH HERE c.custid d = o.custid; .... (8 830 row(s) af ffected) /* This is ANSI SQL-89 S syntax x for an inne er join, omit tting the WHERE clause and causing a an inadvertent Ca artesian join n. */ / SE ELECT c.compa anyname, o.or rderdate FR ROM Sales.Cus stomers AS c, Sales.Order rs AS o; ... (7 75530 row(s) affected)

MCT USE ONLY. STUDENT USE PROHIBITED


5-9

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

With the advent of the ANSI SQL-92 standard, support for the ON clause was added. T-SQL also supports this syntax. Joins are represented in the FROM clause by using the appropriate JOIN operator, and the logical relationship between the tables, which becomes a filter predicate, is represented with the ON clause. The following example restates the previous query with the newer syntax:
SELECT c.companyname, o.orderdate FROM Sales.Customers AS c JOIN Sales.Orders AS o ON c.custid = o.custid;

Note The ANSI SQL-92 syntax makes it more difficult to create accidental Cartesian joins. Once the keyword JOIN has been added, a syntax error will be raised if an ON clause is missing.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-10 Querying Multiple Tables

De emonstration: Under rstanding Joins J

In th his demonstration, you will see: s A comparison n of ANSI SQL-89 and SQL-9 92 syntaxes for r joining tables s. How to create e Cartesian pro oducts.

MCT USE ONLY. STUDENT USE PROHIBITED


5-11

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n2

Query ying Wi ith Inne er Joins

In n this lesson, yo ou will learn how to write inner join querie es, the most co ommon type o of multi-table query in a business envir ronment. By ex xpressing a log gical relationsh hip between th he tables, you will retrieve o only th hose rows with h matching attributes presen nt in both table es.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe inner joins. Write queri ies using inner r joins. Describe th he syntax of an n inner join.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-12 Querying Multiple Tables

Un nderstanding Inner Joins

T-SQ QL queries tha at use inner joins are the most common ty ypes of queries s to solve many business problems, especia ally in highly normalized database environ nments. To retr rieve data that t has been stored acro oss multiple tables, you will often o need to reassemble it via inner join queries.

ical processing As you y have previ iously learned, , an inner join begins its logi g phase as a Cartesian produ uct, which is then filtered to remove e any rows that don't match the predicate. In SQL-89 syntax, that pred dicate is in n the WHERE clause. In SQL-9 92 syntax, that t predicate is w within the FRO OM clause in th he ON clause:
--ANSI SQL-89 syntax SE ELECT c.compa anyname, o.or rderdate FR ROM Sales.Cus stomers AS c, Sales.Order rs AS o WH HERE c.custid d = o.custid; --ANSI SQL-92 syntax SE ELECT c.compa anyname, o.or rderdate FR ROM Sales.Cus stomers AS c JOIN Sales.O Orders AS o ON N c.custid = o.custid;

From m a performan nce standpoint t, you will find that the quer ry optimizer in n SQL Server 20 012 does not f favor one e syntax over th he other. How wever, as you le earn about add ditional types of joins, espec cially outer join ns, tax and filter in the ON clau you will likely dec cide that you prefer p to use th he SQL-92 synt use. Keeping th he join filte er logic in the ON O clause and d leaving other r data filtering in the WHERE E clause will m make your quer ries easi ier to read and d easier to test t. Usin ng the ANSI SQ QL-92 syntax, examine e the st teps by which SQL Server 20 012 will logically process this s que ery. (Line numb bers are added d for clarity, bu ut are not subm mitted to the q query engine f for execution.) )
1) 2) 3) 4) SELECT c.companyname, o.orderdate FROM Sales.Customers AS A c JOIN Sales.Orders AS o ON c.custid = o.custid;

MCT USE ONLY. STUDENT USE PROHIBITED


5-13

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

As you learned earlier, the FROM clause will be processed before the SELECT clause. Therefore, lets track the processing beginning with line 2:

The FROM clause designates the Sales.Customers table as one of the input tables, giving it the alias of 'c'. The JOIN operator in line 3 reflects the use of an INNER join (the default type in T-SQL) and designates the Sales.Orders table as the other input table, which has an alias of 'o'.

SQL Server will perform a logical Cartesian join on these tables and pass the results to the next phase in the virtual table. (Note that the physical processing of the query may not actually perform the Cartesian product operation, depending on the optimizer's decisions.) Using the ON clause, SQL Server will filter the virtual table, retaining only those rows where a custid value from the c table (Sales.Customers has been replaced by the alias) matches a custid from the p table (Sales.Orders has been replaced by an alias). The remaining rows are left in the virtual table and handed off to the next phase in the SELECT statement. In this example, the virtual table is next processed by the SELECT clause, and only two columns are returned to the client application.

The result? A list of customers that have placed orders. Any customers that have never placed an order have been filtered out by the ON clause, as have any orders that happen to have a customer ID that doesn't correspond to an entry in the customer list.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-14 Querying Multiple Tables

Inn ner Join Sy yntax

Whe en writing que eries using inner joins, consid der the followi ing guidelines s: As you have seen, s table alia ases are prefer rred, not only f for the SELECT T list, but for expressing the ON clause.

Inner joins may be perform med on a single e matching att tribute, such as s an orderid, o or they may be e performed on n multiple mat tching attribut tes, such as the e combination n of orderid an nd productid. J Joins that match multiple m attributes are called composite join ns.

The order in which w tables are listed and jo oined in the F ROM clause d oes not matte er to the SQL Server optimizer. (Th his will not be the case for OUTER O JOIN qu ueries in the ne ext topic.) Con nceptually, join ns will be evaluated from left to right. Use the JOIN keyword once e for each two o tables in the FROM list. For r a two-table q query, specify o one join. For a thr ree-table query, you will use e JOIN twice: o once between t the first two ta ables, and once again betwee en the output of o the first two o and the third d table.

MCT USE ONLY. STUDENT USE PROHIBITED


5-15

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

In nner Join Examples E

Fo ollowing are so ome examples s of inner joins s:

A join on a sing gle matching attribute, relating the catego oryid from the Production.Ca ategories table e to the ca ategoryid from m the Productio on.Products ta able:
SELECT c.categoryid, cat tegoryname, p.productid, p p.productnam me FROM Production.Categories AS c JOIN Production.Products s AS p ON c.categoryid = p.cate egoryid;

A composite joi in on two matching attribute es, relating city y and country attributes from m Sales.Custom mers to HR.Employees. Note the use of o the DISTINC CT operator to o filter out dup plicate occurrences of city, co ountry:
SELECT DISTINCT e.city, e.country FROM Sales.Customers AS c JOIN HR.Employees AS e ON c.city = e.city AND c.country c = e.country; e

Note Th he demonstrati ion code for th his lesson also uses the DIST TINCT operator r to filter duplicates s.

Th his next examp ple shows how w an inner join may be exten nded to include e more than tw wo tables. Not te that th he Sales.OrderDetails table is s joined not to o the Sales.Ord ders table, but to the output of the JOIN b between Sa ales.Customers s and Sales.Ord ders. Each inst tance of JOIN....ON performs s its own population and filte ering of th he virtual outp put table. It is up u to the SQL Server query o optimizer to de ecide in which h order the join ns and fil ltering will be performed.
SELECT c.custid, c.compa anyname, o.or rderid, o.ord derdate, od.p productid, od d.qty FROM Sales.Customers AS c JOIN Sales.Orders AS o ON c.custid = o.custid JOIN Sales.OrderDetails AS od ON o.orderid = od.orderid;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-16 Querying Multiple Tables

Demonst tration: Qu uerying with Inner Jo oins

In th his demonstration, you will see s how to que ery multiple ta ables using inn ner joins.

MCT USE ONLY. STUDENT USE PROHIBITED


5-17

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n3

Query ying Wi ith Oute er Joins s

In n this lesson, yo ou will learn how to write qu ueries which u se outer joins.. While not as common as in nner jo oins, the use of f outer joins in n a multi-table query can pro ovide you with h an alternative e view of your r bu usiness data. As A with inner jo oins, you will express e a logic cal relationship p between the tables. Howev ver, you will w retrieve not t only rows wit th matching at ttributes, but a all rows presen nt in one of the e tables, wheth her or no ot there is a match m in the other table.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Understand d the purpose and function of o outer joins. Be able to write w queries using u outer joins. Be able to combine c an OUTER JOIN op perator in a FRO OM clause wit th a nullability y test in a WHE ERE clause in or rder to reveal non-matching n g rows.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-18 Querying Multiple Tables

Un nderstanding Outer Joins J

In th he previous les sson, you learn ned how to use inner joins to o match rows in separate tables. As you sa aw, SQL L Server built the results of an inner join qu uery by filterin ng out rows th at failed to me eet the conditions bles were disp expressed in the ON O clause pred dicate. The res sult: only rows that matched d from both tab played. With an outer join n, you may cho oose to display y all the rows f from one table e as well as tho ose that match h from m the second table. t Let's loo ok at an examp ple, then explo ore the process s. First t, examine the e following que ery, written as an inner join:
US SE AdventureW Works2008R2; GO O SE ELECT c.Custo omerID, soh.S SalesOrderID FR ROM Sales.Cus stomer AS c JOIN J Sales.Sa alesOrderHead der AS soh ON N c.CustomerI ID = soh.Cust tomerID --(31465 row(s s) affected)

Not te that this exa ample uses the e AdventureWo orks2008R2 da atabase for the ese samples. W When written a as an inne er join, the que ery returns 31, ,465 rows. The ese rows repres sent a match b between custo omers and orde ers. Only those Custom merIDs that ap ppear in both tables t will app pear in the resu ults. Only custo omers that have plac ced orders will be returned.
US SE AdventureW Works2008R2; GO O SE ELECT c.Custo omerID, soh.S SalesOrderID FR ROM Sales.Cus stomer AS c LEFT L OUTER JO OIN Sales.Sal lesOrderHeade er AS soh ON N c.CustomerI ID = soh.Cust tomerID --(32166 row(s s) affected)

MCT USE ONLY. STUDENT USE PROHIBITED


5-19

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

This example uses a LEFT OUTER JOIN operator, which as you will learn, directs the query processor to preserve all rows from the table on the left (Sales.Customer) and display the SalesOrderID values for matching rows in Sales.SalesOrderHeader. However, there are more rows returned in this example. All customers are returned, whether or not they have placed an order. As you will see in this lesson, an outer join will display all the rows from one side of the join or another, whether they match or not. What does an outer join query display in columns where there was no match? In the above example, for 701 customers, there are no matching orders. In the place of the SalesOrderID column, SQL Server will output NULL where values are otherwise missing.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-20 Querying Multiple Tables

Ou uter Join Sy yntax

Whe en writing que eries using inner joins, consid der the followi ing guidelines s: As you have seen, s table alia ases are prefer rred, not only f for the SELECT T list, but for expressing the ON clause. Outer Joins are expressed using u the keyw words LEFT, RIG GHT, or FULL p preceding OUT TER JOIN. The purpose of th he keyword is to t indicate which table (on w which side of t the keyword JO OIN) should be e preserved and d have all its ro ows displayed, match or no match.

As with inner joins, outer jo oins may be pe erformed on a single matching attribute, s such as an orderid, or they may be b performed on multiple matching m attrib bute, such as orderid and pro oductid. Unlike inner joins, the order in which tables are listed a and joined in the FROM clause does matte er, as it will determine whether yo ou choose LEF FT or RIGHT fo or your join.

Multi-table jo oins are more complex c when n an OUTER JO OIN is present. The presence of NULLs in th he results of an outer o join may y cause issues if the intermed diate results ar re then joined via an inner jo oin to a third table. Rows with NU ULLs may be filtered out by t the second join n's predicate. To display on nly rows where e no match exis sts, add a test for NULL in a WHERE clause e following an OUTER JOIN predicate.

MCT USE ONLY. STUDENT USE PROHIBITED


5-21

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Outer O Join Examples

Fo ollowing are so ome examples s of outer joins s: Display all custo omers and pro ovide information about each h customer's o orders if any ex xist:
USE TSQL2012; GO SELECT c.custid, c.compa anyname, o.or rderid, o.ord derdate FROM Sales.Customers AS c LEFT OUTER JOIN Sales.Or rders AS o ON c.custid =o.custid;

Display only cus stomers that have h never plac ced an order:
SELECT c.custid, c.compa anyname, o.or rderid, o.ord derdate FROM Sales.Customers AS c LEFT OUTER JOIN Sales.Or rders AS o ON c.custid =o.custid WHERE W o.orderid IS NULL;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-22 Querying Multiple Tables

Demonst tration: Qu uerying with Outer Joins J

In th his demonstration, you will see s how to com mbine data fro om multiple ta ables with an outer join.

MCT USE ONLY. STUDENT USE PROHIBITED


5-23

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n4

Query ying with Cross Joins and Sel lf-Joins

In n this lesson, yo ou will learn so ome additiona al types of join ns, which are u seful in some more specializ zed sc cenarios.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe a use for a cross s join. Write queri ies that use self joins. Describe a use for a self-j join. Write queri ies that use self-joins.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-24 Querying Multiple Tables

Un nderstanding Cross Joins J

Cross join queries s create a Carte esian product. So far in this m module, you h have learned th hat Cartesian prod ducts are to be e avoided. Alth hough you hav ve seen a mea ans to create o one with ANSI SQL-89 syntax x, you haven't seen how or why to create one with ANSI A SQL-92. T This topic will revisit cross jo oins and Cartes sian prod ducts. To explicitly e create a Cartesian product, p you would w use the CROSS JOIN o operator. This will create a re esult set with w all possib ble combinations of input row ws:
SE ELECT ... FR ROM table1 AS S t1 CROSS JO OIN table2 AS S t2;

While this is not ty ypically a desired output, there are a few p practical appli cations for writing an explic cit cros ss join: Creating a tab ble of number rs, with a row for f each possib ble value in a r range. Generating la arge volumes of o data for test ting. When cro oss joined to it tself, a table w with as few as 1 100 rows can read dily generate 10,000 1 output rows with very y little work on n your part.

MCT USE ONLY. STUDENT USE PROHIBITED


5-25

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Cross C Join Syntax S

When W writing queries with CR ROSS JOIN, con nsider the follo owing: There is no matching of rows r performe ed, and therefo ore no ON clau use is required d. To use ANS SI SQL-92 syntax, separate th he input table names with th he CROSS JOIN N operator.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-26 Querying Multiple Tables

Cro oss Join Ex xamples

Following is an ex xample of using CROSS JOIN N to create all c combinations of two input s sets. Using the TSQ QL2012 sample e, this will take 9 employee first names and d 9 employee last names to generate 81 com mbinations:
SE ELECT e1.firs stname, e2.la astname FR ROM HR.Employ yees e1 CROSS S JOIN HR.Emp ployees e2;

MCT USE ONLY. STUDENT USE PROHIBITED


5-27

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Understand U ding Self-J Joins

Th he joins you ha ave learned ab bout to this po oint have invol lved separate m be multiple tables. There may b sc cenarios in which you need to t compare an nd retrieve dat ta store in the same table. Fo or example, in a classic human re esources appli ication, an Employees table might include e information a about the supe ervisor of f each employ yee in the emp ployee's own ro ow. Each super rvisor is also lis sted as an employee. To retr rieve th he employee in nformation and match it up to the related supervisor, yo ou can use the e table twice in n your qu uery, joining it t to itself for th he purposes of f the query.

Th here are other r scenarios in which w you will want to comp pare rows with in a table with h one another. As you ha ave seen, it's fa airly easy to co ompare colum mns within the same row usin ng T-SQL, but it is less obvious how to o compare valu ues from differ rent rows (such as a row whi ich stores a sta arting time wit th another row w in the sa ame table that t stores a corre esponding stop p time). Self-jo oins are a usefu ul technique fo or these types of qu ueries. In n order to acco omplish tasks like this, you will w want to con nsider the follo owing guidelin nes:

Create two instances of the same table in the FROM clause, and jo in them as nee eded, using inner or outer joins. Use table aliases to create e two separate e aliases for th e same table. At least one ta able must have e an alias. Use the ON N clause to pro ovide a filter us sing separate c columns from the same tabl le.

Th he following example, which h you will exam mine closely in the next topic c, illustrates th hese guidelines s. This qu uery retrieves employees and their matchi ing manager i nformation fro om the Employ yees table join ned to its self:
SELECT e.empid ,e.lastna ame as empnam me,e.title,e. .mgrid, m.las stname as mgrname FROM HR.Employees AS e JOIN HR.Employees AS m ON e.mgrid=m.empid;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-28 Querying Multiple Tables

This yields a result like the following:


empid ----2 3 4 5 6 7 8 9 empname -----------Funk Lew Peled Buck Suurs King Cameron Dolgopyatova title --------------------Vice President, Sales Sales Manager Sales Representative Sales Manager Sales Representative Sales Representative Sales Representative Sales Representative mgrid ----1 2 3 2 5 5 3 5 mgrname ------Davis Funk Lew Funk Buck Buck Lew Buck

MCT USE ONLY. STUDENT USE PROHIBITED


5-29

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Self-Join Sy yntax

Yo ou write self-jo oin queries mu uch like you write inner or o uter joins. The e primary difference is that the ta ables on both sides s of the JO OIN operator will w actually be references to the same tabl le. Pay particular at ttention to you ur aliasing and d which columns you use in t the ON clause e in order to en nsure that you u are jo oining the table to itself prop perly. Try using g the terms in the business p problem (such as employee and manager) m to help keep it clear which table you y need to re efer to.

All of the querie es you have se een in this mod dule so far hav ve been writte n using an equ uality operator to ever, there are match m rows. In fact, f we refer to t joins which use equality o operators as eq qui joins. Howe e nu umerous scena arios in which the use of an inequality ope erator in a self f-join can open n up opportun nities for in nteresting quer ries. When W a join con ndition uses ot ther operators s, such as <, >,, <>, the join i is called a non n-equijoin. When jo oining a table to t itself, using an inequality operator (<, > >, <>) will filte er out those ro ows where the is will create unique pairs of co olumns being compared in the t ON clause are equal to e each other. Thi f values in n the column being b compare ed. Fo or example, co onsider a table e of numbers with w only one c column, n, and d only three ro ows:
SELECT n FROM T;

Th he result:
n -1 2 3

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-30 Querying Multiple Tables

A cross-join query that created a Cartesian product would produce all combinations of the values:
SELECT T1.n, T2.n FROM T AS T1 CROSS JOIN T AS T2; The result: n n - 1 1 2 1 3 1 1 2 2 2 3 2 1 3 2 3 3 3 (9 row(s) affected)

To create only unique combinations of the pairs, create a predicate T1.n < T2.n in the JOIN clause to produce three rows:
SELECT T1.n, T2.n FROM T AS T1 JOIN T AS T2 ON T1.n < T2.n; The results: n n - 1 2 1 3 2 3 (3 row(s) affected)

MCT USE ONLY. STUDENT USE PROHIBITED


5-31

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Self-Join Ex xamples

Re eturn all emplo oyees with the e name of each h employees m manager wher re manager ex xists (inner join n). Note th hat a manager appears who is not also liste ed an employe ee:
SELECT e.empid ,e.lastna ame as empnam me,e.title,e. .mgrid, m.las stname as mgrname FROM HR.Employees AS e JOIN HR.Employees AS m ON e.mgrid=m.empid;

Re eturn all emplo oyees with the e name of each h manager (ou uter join). This restores the m missing employ yee, who w turns out to be CEO with h no manager:
SELECT e.empid ,e.lastna ame as empnam me,e.title,e. .mgrid, m.las stname as mgrname FROM HR.Employees AS e LEFT OUTER JOIN HR.Emp ployees AS m ON e.mgrid=m.empid;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-32 Querying Multiple Tables

De emonstration: Query ying with Cross C Joins s and Self-Joins

In th his demonstration, you will see s how to join n a table to its self and how to o create a Cart tesian product t with a cross join.

MCT USE ONLY. STUDENT USE PROHIBITED


5-33

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lab: Queryin Q ng Multiple Tab bles

La ab Setup

Fo or this lab, you u will use the available a virtua al machine env vironment. Bef fore you begin n the lab, you must co omplete the fo ollowing steps: : 1. . 2. . 3. . On the host computer, click Start, poin nt to Administ trative Tools, and click Hyp per-V Manage er. Maximize the Hyper-V Manager M window. If the virtua al machine 107 774A-MIA-DC C1 is not starte ed: 4. . -MIA-DC1 an d click Start. In the Virtual V Machi ines list, right-click 10774ARight-c click 10774A-MIA-DC1 and d click Connec ct.

In the Virtual V Machi ine Connectio on window, wa ait until the P Press CTRL+ALT T+DELETE to log on messag ge appears, an nd then close the Virtual Ma achine Conne ection window w.

If the virtua al machine 107 774A-MIA-SQ QL1 is not start ted: -MIA-SQL1 an In the Virtual V Machi ines list, right-click 10774And click Start. Right-c click 10774A-MIA-SQL1 and click Conne ect.

In the Virtual V Machi ine Connectio on window, wa ait until the P Press CTRL+ALT T+DELETE to log on messag ge appears, an nd then close the Virtual Ma achine Conne ection window w.

5. . 6. .

In Virtual Machine M Conn nection windo ow, click the R Revert toolbar icon. If you are prompted p to co onfirm that yo ou want to reve ert, click Reve ert. Wait for the revert action n to complete.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-34 Querying Multiple Tables

7.

If you are not already logged on:

In the Virtual Machine Connection window, click the Ctrl-Alt-Delete menu item on the Action menu. Click Switch User, and then click Other User. Log on using the following credentials: User name: AdventureWorks\Administrator Password: Pa$$w0rd

8. 9.

In the Virtual Machine Connection window, click Full Screen Mode on the View menu. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.

10. On the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, and click SQL Server Management Studio. 11. In the Connect to Server window, type Proseware in the Server name text box.

12. Click the Options button. Under Connection Properties, select <Browse server> in the Connect to database list. Choose Yes when prompted for the connection to the database. Under User Databases, select the TSQL2012 database. 13. Choose the authentication type, depending on the type of deployment: For an on-premises Microsoft SQL Server instance, click the Login tab, select Windows Authentication in the Authentication list, and click Connect. For Microsoft SQL Azure, click the Login tab, select SQL Server Authentication in the Authentication list, type your login name in the Login text box and the password in the Password text box, and click Connect.

Lab Scenario

You are a business analyst for Adventure Works who will be writing reports using corporate databases stored in SQL Server 2012. You have been provided with a set of business requirements for data and you will write T-SQL queries to retrieve the specified data from the databases. You notice that the data is stored in separate tables, so you will need to write queries using various join operations.

MCT USE ONLY. STUDENT USE PROHIBITED


5-35

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 1: Writing Queries That Use Inner Joins


Scenario

You no longer need the mapping information between categoryid and categoryname that was supplied in module 3 because you now have the Production.Categories table with the needed mapping rows. Write a SELECT statement using an inner join to retrieve the productname column from the Production.Products table and the categoryname column from the Production.Categories table. The main tasks for this exercise are as follows: 1. 2. Write a SELECT statement using an inner join. Answer questions.

X Task 1: Write a SELECT statement that uses an inner join

Open the project file F:\10774A_Labs\10774A_05_PRJ\10774A_05_PRJ.ssmssln and the T-SQL script 51 - Lab Exercise 1.sql. To set your database context to that of the TSQL2012 database, highlight the statement USE TSQL2012; and execute the highlighted code. After executing this statement, the TSQL2012 database should be selected in the Available Databases box. In subsequent exercises, you will simply be instructed to ensure that you are connected to the TSQL2012 database. Write a SELECT statement that will return the productname column from the Production.Products table (use table alias p) and the categoryname column from the Production.Categories table (use table alias c) using an inner join.

Execute the written statement and compare the results that you got with the desired results shown in the file 52 - Lab Exercise 1 - Task 1 Result.txt. Which column did you specify as a predicate in the ON clause of the join? Why?

Let us say that there is a new row in the Production.Categories table and this new product category does not have any products associated with it in the Production.Products table. Would this row be included in the result of the SELECT statement written in task 1? Please explain.

Results: After this exercise, you should know how to use an inner join between two tables.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-36 Querying Multiple Tables

Exercise 2: Writing Queries That Use Multiple-Table Inner Joins


Scenario

The sales department would like a report of all customers that placed at least one order, with detailed information about each order. A developer prepared an initial SELECT statement that retrieves the custid and contactname columns from the Sales.Customers table and the orderid column from the Sales.Orders table. You should observe the supplied statement and add additional information from the Sales.OrderDetails table. The main tasks for this exercise are as follows: 1. 2. Analyze and correct the query. Add the productid, qty, and unitprice columns from the Sales.OrderDetails table.

X Task 1: Execute the T-SQL statement


Open the project file F:\10774A_Labs\10774A_05_PRJ\10774A_05_PRJ.ssmssln and the T-SQL script 61 - Lab Exercise 2.sql. Ensure that you are connected to the TSQL2012 database. The developer has written this query:
SELECT custid, contactname, orderid FROM Sales.Customers INNER join Sales.Orders ON Customers.custid = Orders.custid;

Execute the query exactly as written inside a query window and observe the result. You get an error. What is the error message? Why do you think you got this error?

X Task 2: Apply the needed changes and execute the T-SQL statement
Notice that there are full source table names written as table aliases. Apply the needed changes to the SELECT statement so that it will run without an error. Test the changes by executing the T-SQL statement. Observe and compare the results that you got with the recommended result shown in the file 62 Lab Exercise 2 - Task 2 Result.txt.

X Task 3: Change the table aliases


Copy the T-SQL statement from task 2 and modify it to use the table aliases C for the Sales.Custumers table and O for the Sales.Orders table. Execute the written statement and compare the results with the results in task 2. Change the prefix of the columns in the SELECT statement with full source table names and execute the statement. You get an error. Why? Change the SELECT statement to use the table aliases written at the beginning of the task.

MCT USE ONLY. STUDENT USE PROHIBITED


5-37

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

X Task 4: Add an additional table and columns


Copy the T-SQL statement from task 3 and modify it to include three additional columns from the Sales.OrderDetails table: productid, qty, and unitprice.

Execute the written statement and compare the results that you got with the recommended result shown in the file 63 - Lab Exercise 2 - Task 4 Result.txt.

Results: After this exercise, you should have a better understanding of why aliases are important and how to do a multiple-table join.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-38 Querying Multiple Tables

Exercise 3: Writing Queries That Use Self-Joins


Scenario

The HR department would like a report showing employees and their managers. They would like to see the lastname, firstname, and title columns from the HR.Employees table for each employee and the same columns for the employees manager. The main tasks for this exercise are as follows: 1. 2. Write a SELECT statement using a self-join to retrieve the needed columns. Answer the questions.

X Task 1: Write a basic SELECT statement


Open the project file F:\10774A_Labs\10774A_05_PRJ\10774A_05_PRJ.ssmssln and the T-SQL script 71 - Lab Exercise 3.sql. Ensure that you are connected to the TSQL2012 database. In order to better understand the needed tasks, you will first write a SELECT statement against the HR.Employees table showing the empid, lastname, firstname, title, and mgrid columns. Execute the written statement and compare the results that you got with the recommended result shown in the file 72 - Lab Exercise 3 - Task 1 Result.txt. Notice the values in the mgrid column. The mgrid column is in a relationship with empid column. This is called a self-referencing relationship.

X Task 2: Write a query that uses a self-join

Copy the SELECT statement from task 1 and modify it to include additional columns for the manager information (lastname, firstname) using a self-join. Assign the aliases mgrlastname and mgrfirstname, respectively, to distinguish the manager names from the employee names. Execute the written statement and compare the results that you got with the recommended result shown in the file 73 - Lab Exercise 3 - Task 2 Result.txt. Notice the number of rows returned. Is it mandatory to use table aliases when writing a statement with a self-join? Can you use a full source table name as alias? Please explain. Why did you get fewer rows in the T-SQL statement under task 2 compared to task 1?

Results: After this exercise, you should have an understanding of how to write T-SQL statements that use self-joins.

MCT USE ONLY. STUDENT USE PROHIBITED


5-39

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 4: Writing Queries That Use Outer Joins


Scenario

The sales department was satisfied with the report you produced in exercise 2. Now the sales staff would like to change the report to show all customers, even if they did not have any orders, and still include the information about the orders for the customers that did place orders. You need to write a SELECT statement to retrieve all rows from Sales.Customers (columns custid and contactname) and the orderid column from the table Sales.Orders. Write a SELECT statement using an outer join to retrieve the needed columns.

X Task 1: Write the SELECT statement that uses an outer join


Open the project file F:\10774A_Labs\10774A_05_PRJ\10774A_05_PRJ.ssmssln and the T-SQL script 81 - Lab Exercise 4.sql. Ensure that you are connected to the TSQL2012 database.

Write a SELECT statement to retrieve the custid and contactname columns from the Sales.Customers table and the orderid column from the Sales.Orders table. The statement should retrieve all rows from the Sales.Customers table. Execute the written statement and compare the results that you got with the recommended result shown in the file 82 - Lab Exercise 4 - Task 1 Result.txt. Notice the values in the column orderid. Are there any missing values (marked as NULL)? Why?

Results: After this exercise, you should have a basic understanding of how to write T-SQL statements that use outer joins.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

5-40 Querying Multiple Tables

Exercise 5: Writing Queries That Use Cross Joins


Scenario

The HR department would like to prepare a personalized calendar for each employee. The IT department supplied you with T-SQL code that will generate a table with all dates for the current year. Your job is to write a SELECT statement that would return for each row in HR.Employees table all rows in this new calendar date table. 1. 2. Execute the provided T-SQL statement to generate the HR.Calendar table, which includes the calendardate column, and to populate the table with date information. Write a SELECT statement that uses a cross join to retrieve the needed columns.

X Task 1: Execute the T-SQL statement


Open the project file F:\10774A_Labs\10774A_05_PRJ\10774A_05_PRJ.ssmssln and the T-SQL script 91 - Lab Exercise 5.sql. Ensure that you are connected to the TSQL2012 database. Execute the T-SQL code under Task 1. Do not worry if you do not understand the provided T-SQL code, as it is used here to provide a more realistic example for a cross join in the next task.

X Task 2: Write a SELECT statement that uses a cross join


Write a SELECT statement to retrieve the empid, firstname, and lastname columns from the HR.Employees table and the calendardate column from the HR.Calendar table. Execute the written statement and compare the results that you got with the recommended result shown in the file 92 - Lab Exercise 5 - Task 2 Result.txt. What is the number of rows returned by the query? There are nine rows in the HR.Employees table. Try to calculate the total number of rows in the HR.Calendar table.

X Task 3: Drop the HR.Calendar table


Execute the provided T-SQL statement to remove the HR.Calendar table.

Results: After this exercise, you should have an understanding of how to write T-SQL statements that use cross joins.

MCT USE ONLY. STUDENT USE PROHIBITED


5-41

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2012

Modu ule Revi iew and d Takeaw ways

Review R Ques stions


1. . 2. . 3. . How does an a inner join differ d from an outer o join? Which join types include a logical Carte esian product? ? Can a table e be joined to itself?

Best B Practice es
1. . 2. . Table aliase es should always be defined when joining tables. Joins should d be expressed d using SQL-92 syntax, with JOIN and ON keywords.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-1

Module 6
Sorting and Filtering Data
Contents:
Lesson 1: Sorting Data Lesson 2: Filtering Data with Predicates Lesson 3: Filtering Data with TOP and OFFSET-FETCH Lesson 4: Working with Unknown Values Lab: Filtering and Sorting Data 6-3 6-10 6-17 6-24 6-29

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-2 Sorting and Filtering Data

Module Over rview

In th his module, yo ou will learn ho ow to enhance e your queries to limit the ro ows they return n and to contr rol the orde er in which the e rows are disp played. Earlier in this cour rse, you learne ed that according to relation nal theory, sets s of data do no ot include any defi inition of a sor rt order. As a result, if you re equire the outp put of a query y to be displaye ed in a certain n orde er, you will need to add an ORDER O BY clau use to your SE LECT statemen nt. In this mod dule, you will le earn how w to write quer ries using ORD DER by to cont trol the display y order.

M clause to re In a previous mod dule, you also learned how to build a FROM eturn rows from m one or more e tabl les. It is unlikel ly that you will always want to return all ro ows from the s source: for per rformance reas sons as well w as the needs of your clie ent application n or report, you u will want to limit which row ws are returne ed. As ERE clause bas you will learn in th his module, yo ou can limit row ws with a WHE sed on a predi icate, or you ca an limit rows with TO OP and OFFSET T-FETCH based d on number o of rows and or rdering.

As you y work with real-world data in your que eries, you may encounter situ uations where values are mis ssing. It is important to write queries which w can han ndle missing va alues correctly y. In this module you will lear rn abo out handling missing m and unknown results. .

MCT USE ONLY. STUDENT USE PROHIBITED


6-3

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Lesson n1

Sortin ng Data a

In n this lesson, yo ou will learn how to add an ORDER BY clause to your qu ueries to contr rol the order o of rows di isplayed in you ur query's outp put.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-4 Sorting and Filtering Data

Using the OR RDER BY Clause C

In th he logical orde er of query pro ocessing, ORDER BY is the la ast phase of a S SELECT statem ment to execute. ORD DER BY provides you with th he ability to control the sortin ng of rows as they are outpu ut from the qu uery to the client application. Withou ut an ORDER BY B clause, SQL L Server does n not guarantee the order of rows, in keeping with re elational theor ry. To sort s the output of your quer ry, you will add d an ORDER BY Y clause to you ur query in thi is form:
SE ELECT <select t_list> FR ROM <table_ _source> OR RDER BY <orde er_by_list> ASC|DESC; A

ORD DER BY can tak ke several type es of elements in its list:

Columns by name. n (Additio onal columns beyond b the firs st specified in the list will be e used as tiebre eakers for non-uniqu ue values in th he first column n.) Column aliase es. (Remember that ORDER BY is processe ed after the SE LECT clause, and therefore h has access to aliases defined in the SELECT lis st.) Columns by position p in the SELECT clause e. (This is not r recommended d due to diminished readabil lity and due to th he extra care re equired to kee ep the ORDER BY list up to d date with any c changes made e to the column order o in the SELECT list.)

Columns not listed in the SELECT list, but t part of tables s listed in the F FROM clause. ( (If the query uses a DISTINCT opt tion, then any columns in the ORDER BY li ist must be fou und in the SEL LECT list.) Note ORD DER BY may als so include a CO OLLATE clause e, which provid des a way to so ort by a specific char racter collation n, and not the collation of th he column in the table. Colla ations will be further discussed later in this course.

MCT USE ONLY. STUDENT USE PROHIBITED


6-5

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

In addition to specifying which columns should be used to determine the sort order, you may also control the direction of the sort through the use of ASC for an ascending sort (A-Z, 0-9) or DESC for descending (Z-A, 9-0). Ascending sorts are the default. Each column may be provided with a separate order, as in the following example. Employees will be listed from most recent hire to least recent, with employees hired on the same date listed alphabetically by last name:
USE TSQL2012; GO SELECT hiredate, firstname, lastname FROM HR.Employees ORDER BY hiredate DESC, lastname ASC;

For More Information Additional documentation on the ORDER BY clause can be found in Books Online at http://msdn.microsoft.com/en-us/library/ms188385(v=SQL.110).aspx.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-6 Sorting and Filtering Data

OR RDER BY Clause Synt tax

The syntax of the ORDER BY cla ause appears as follows:


OR RDER BY <orde er_by_list> OF FFSET <offset t_value> ROW|ROWS FETCH FIRST|NEXT F <f fetch_value> ROW|ROWS ONLY

Note The use of the OFF FSET-FETCH op ption in the O RDER BY claus se will be cove ered later in this module. . Mos st variations of f ORDER BY will occur in the e order by list. To specify columns by name with the def fault asce ending order, use the follow wing syntax:
OR RDER BY <colu umn_name_1>, <column_name e_2>;

A fragment of cod de using colum mns from the TSQL2012 T Sale es.Customers t table would loo ok like this:
OR RDER BY count try, region, city;

To specify s column ns by aliases de efined in the SELECT S clause, use the follow wing syntax:
SE ELECT <column n_name_1> AS alias1, <col lumn_name_2> AS alias2 FR ROM <table so ource> OR RDER BY alias s1;

MCT USE ONLY. STUDENT USE PROHIBITED


6-7

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

A query for the TSQL2012 Sales.Orders table using column aliases would look like this:
SELECT orderid, custid, YEAR(orderdate) AS orderyear FROM Sales.Orders ORDER BY orderyear;

Note See the previous topic for the syntax and usage of ASC or DESC to control sort order.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-8 Sorting and Filtering Data

OR RDER BY Clause Exam mples

Following are examples of common queries using u ORDER B BY to sort the o output for disp play. All querie es use the TSQL2012 sam mple database. A query against th he Sales.Order rs table, sorting g the results b by the orderdat te column, spe ecified by nam me:
SE ELECT orderid d, custid, or rderdate FR ROM Sales.Ord ders OR RDER BY order rdate;

A query against th he Sales.Order rs table, which defines an alia as in the SELEC CT clause, and d sorts by that colu umn's alias:
SE ELECT orderid d, custid, YE EAR(orderdate e) AS orderye ear FR ROM Sales.Ord ders OR RDER BY order ryear DESC;

A query against th he Sales.Order rs table, which sorts the outp put in descend ding order of o orderdate, from m mos st recent to old dest:
SE ELECT orderid d, custid, or rderdate FR ROM Sales.Ord ders OR RDER BY order rdate DESC;

A query against th he HR.Employe ees table, whic ch sorts the em mployees in de escending orde er of hiredate, from mos st recent to earliest, using lastname to diff ferentiate emp ployees hired o on the same da ate:
SE ELECT hiredat te, firstname e, lastname FR ROM HR.Employ yees OR RDER BY hired date DESC, la astname ASC;

MCT USE ONLY. STUDENT USE PROHIBITED


6-9

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Demonstra D ation: Sorti ing Data

Demonstrati D ion Setup


1. .

On the virtu ual machine, click c Start, click All Program ms, click Micro osoft SQL Serv ver 2012, and click SQL Server r Managemen nt Studio. In the Connect to o Server wind dow, type Prose eware in the S Server name text box and click Connect. From m the File men nu, click Open n, click Project t/Solution, navigate to F:\10774 4A_Labs\10774 4A_06_PRJ\107 774A_06_PRJ.ss smssln, and cli ick Open. Open the 11 1 Demonstration A.sql script file. Follow the instructions co ontained within the commen nts of the scrip pt file. Question: Does the physical order of rows r in a SQL Server table, s such as determ mined by an index, guar rantee any sort t order in quer ries using the t table?

2. . 3. .

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-10 Sorting an nd Filtering Data

Lesson 2

Filterin ng Data a with Predicat P es

Mos st of the time when w querying g SQL Server 2012, 2 often yo u will want to retrieve a only y subset of all the row ws stored in the e table listed in n the FROM clause. This is es specially true a as data volume es grow. In ord der to limit which rows are a returned, you y typically will w use the WH HERE clause in the SELECT sta atement. In this lesson you will lea arn how to con nstruct WHERE E clauses to filt ter out rows w which do not m match the pred dicate.

MCT USE ONLY. STUDENT USE PROHIBITED


6-11

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Filtering Da ata in the WHERE W Cl lause with Predicate es

In n order to limit t the rows that t are returned by your query y, you will need d to add a WH HERE clause to o your SE ELECT stateme ent, following the t FROM clau use. WHERE cla auses are cons structed from a search condition, cal filter which w in turn is written as a predicate p expre ession. The pur rpose of the p predicate is to provide a logic th hrough which each row must pass. Only ro ows returning T TRUE in the pr redicate will be e output to the next lo ogical phase of f the query. When W writing a WHERE clause e, keep the following consid derations in mi ind: Your predic cate must be expressed e as a logical condit tion, evaluating g to TRUE or F FALSE. (This will change when working with missing values or NULL. S See Lesson 4 fo or more inform mation.) Only rows for f which the predicate p evalu uates as TRUE will be passed d through the filter. Values of FA ALSE or UNKN NOWN will be filtered out.

Column alia ases declared in the query's SELECT clause e cannot be us sed in the WHE ERE clause pre edicate.

Re emember that t the WHERE clause is logically the next ph hase in query e execution after FROM, and w will be processed before other clause es such as SELE ECT. A conseq uence of this i is that your WHERE clause w will be un nable to refer to column alia ases created in n the SELECT c lause. If you have created ex xpressions in the SE ELECT list, you will need to repeat the expressions in ord der to use them m in the WHER RE clause.

Fo or example, the following qu uery, which use es a simple ca lculated expre ession in the SE ELECT list, will execute properly:
SELECT orderid, custid, YEAR(orderda ate) AS ordye ear FROM Sales.Orders WHERE W YEAR(orderdate) = 2006;

Th he following query q will fail due d to the use of column alia ases in the WH HERE clause:
SELECT orderid, custid, YEAR(orderda ate) AS ordye ear FROM Sales.Orders WHERE W ordyear = 2006;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-12 Sorting and Filtering Data

The error message points to the use of the column alias in line 3 of the batch:
Msg 207, Level 16, State 1, Line 3 Invalid column name 'ordyear'.

From the perspective of query performance, the use of effective WHERE clauses can provide a significant impact upon SQL Server. Rather than return all rows to the client for post-processing, a WHERE clause causes SQL Server to filter data on the server-side. This can reduce network traffic as well as memory usage on the client. Additionally, SQL Server developers and administrators can create indexes to support commonly-used predicates, furthering improving performance.

MCT USE ONLY. STUDENT USE PROHIBITED


6-13

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

WHERE W Cla ause Syntax x

In n Books Online e, the syntax of f the WHERE clause c appears s as follows:


WHERE W <search_condition> >

Th he most comm mon form of a WHERE clause e is as follows:


WHERE W <column> <operator r> <expressio on>

Fo or example, the following co ode fragment shows s a WHER RE clause whic h will filter only Customers f from Sp pain:
SELECT contactname, coun ntry FROM Sales.Customers WHERE W country = N'Spain';

Any of the logic cal operators introduced in the t T-SQL lang guage module e earlier in this course may b be used in n a WHERE clau use predicate. This example filters Orders placed after a specified date e:
SELECT orderid, orderdat te FROM Sales.Orders WHERE W orderdate > '20070 0101';

Note Th he representation of dates as s strings delim ited by quotat tion marks will l be covered in the next t module.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-14 Sorting and Filtering Data

In addition to using logical operators, literals or constants in a WHERE clause, you may also make use of several T-SQL options in your predicate: Predicates and Operators IN Description

Determines whether a specified value matches any value in a subquery or a list. Specifies an inclusive range to test. Determines whether a specific character string matches a specified pattern. Combines two Boolean expressions and returns TRUE only when both expressions are TRUE. Combines two Boolean expressions and returns TRUE if either expression is TRUE. Reverses the result of a search condition.

BETWEEN LIKE AND OR NOT

Note The use of LIKE to match patterns in character-based data will be covered in the next module. The following example shows the use of the OR operator to combine conditions in a WHERE clause:
SELECT custid, companyname, country FROM Sales.Customers WHERE country = N'UK' OR country = N'Spain';

The following example modifies the previous query to use the IN operator for the same results:
SELECT custid, companyname, country FROM Sales.Customers WHERE country IN (N'UK',N'Spain');

The following example uses the NOT operator to reverse the previous condition:
SELECT custid, companyname, country FROM Sales.Customers WHERE country NOT IN (N'UK',N'Spain');

The following example uses logical operators to search within a range of dates:
SELECT orderid, custid, orderdate FROM Sales.Orders WHERE orderdate >= '20070101' AND orderdate < '20080101';

MCT USE ONLY. STUDENT USE PROHIBITED


6-15

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

The following example accomplishes the same results using the BETWEEN operator:
SELECT orderid, custid, orderdate FROM Sales.Orders WHERE orderdate BETWEEN '20061231' AND '20080101';

Note The use of comparison operators with date and time data types requires special consideration. For more information, see the next module.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-16 Sorting an nd Filtering Data

De emonstration: Filterin ng Data with w Predic ates

Dem monstration n Setup


1.

On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, click S SQL Server Mana agement Stud dio. In the Con nnect to Serve er window, typ pe Proseware in the Server n name text box and click Connect t. From the File e menu, click O Open, click Pr roject/Solutio on, navigate to o F:\10774A_La abs\10774A_06 6_PRJ\10774A_ _06_PRJ.ssmssl ln, and click O Open. Open the 21 Demonstrati ion B.sql script t file. file. Follow the ins structions cont tained within the t comments s of the script f

2. 3.

MCT USE ONLY. STUDENT USE PROHIBITED


6-17

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n3

Filtering Dat ta with TOP T and OFFSET-FETC CH

In n addition to filtering rows based b upon dat ta stored with in them, you c can also write queries that filter ra anges of rows, either based upon u a specific c number to re etrieve, or one e range of row ws at a time. In this le esson you will learn l how to li imit ranges of rows in the SE ELECT clause u using a TOP op ption, and how w to lim mit ranges of rows r at a time using the OFF FSET-FETCH op ption of an OR RDER BY clause e.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-18 Sorting an nd Filtering Data

Filt tering in the SELECT T Clause Us sing the TO OP Option n

Whe en returning ro ows from a qu uery, you may need to limit t the total numb ber of rows ret turned, as well as filte ering with a WHERE clause. The T TOP option n, a Microsoft-proprietary ex xtension of the SELECT claus se, will let you specify y a number of f rows to return n, either as an ordinal numb ber or as a perc centage of all candidate rows. The simplified syn ntax of the TOP P option is as follows: f
SE ELECT TOP (N) <column_lis st> FR ROM <table_s source> WH HERE <search_ _condition>;

For example, to re etrieve only the five most rec cent orders fro om the Sales.O Orders table in the TSQL 201 12 data abase, use the following que ery:
SE ELECT TOP (5) orderid, cu ustid, orderd date FR ROM Sales.Ord ders OR RDER BY order rdate DESC;

Not te that the TOP P operator dep pends upon an n ORDER BY to o provide mea aningful preced dence to the rows sele ected. In the ab bsence of an ORDER O BY, there is no guaran ntee which row ws will be retu urned. In the prev vious example e, any five orde ers might be re eturned if ther re wasnt an O RDER BY claus se.

In addition to spe ecifying a fixed d number of ro ows to be retur rned, the TOP keyword also accepts the W WITH TIES S option, which h will retrieve any a rows with values that m ight be found in the selecte ed top N rows. For exam mple, the follo owing query will w return five rows r with the most recent o rderdate:
SE ELECT TOP (5) orderid, cu ustid, orderd date FR ROM Sales.Ord ders OR RDER BY order rdate DESC;

MCT USE ONLY. STUDENT USE PROHIBITED


6-19

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

The results show five rows with two distinct orderdate values:
orderid ----------11077 11076 11075 11074 11073 custid ----------65 9 68 73 58 orderdate ----------------------2008-05-06 00:00:00.000 2008-05-06 00:00:00.000 2008-05-06 00:00:00.000 2008-05-06 00:00:00.000 2008-05-05 00:00:00.000

(5 row(s) affected)

However, by adding the WITH TIES option to the TOP clause, you will see that more rows qualify for the second-oldest order date:
SELECT TOP (5) WITH TIES orderid, custid, orderdate FROM Sales.Orders ORDER BY orderdate DESC;

This modified query returns the following results:


orderid ----------11077 11076 11075 11074 11073 11072 11071 11070 custid ----------65 9 68 73 58 20 46 44 orderdate ----------------------2008-05-06 00:00:00.000 2008-05-06 00:00:00.000 2008-05-06 00:00:00.000 2008-05-06 00:00:00.000 2008-05-05 00:00:00.000 2008-05-05 00:00:00.000 2008-05-05 00:00:00.000 2008-05-05 00:00:00.000

(8 row(s) affected)

As you can see, whether to include WITH TIES will depend on your knowledge of the source data and its potential for unique values.

To return a percentage of the row count, instead of a fixed number, use the PERCENT option with TOP, as follows. For example, with a Sales.Orders table which contains 830 orders, the following query will return 83 rows:
SELECT TOP (10) PERCENT orderid, custid, orderdate FROM Sales.Orders ORDER BY orderdate DESC;

TOP (N) PERCENT may also be used with the WITH TIES option. Note TOP (N) PERCENT will round up to the nearest integer for purposes of row counts. For More Information See "Top (Transact-SQL)" in Books Online: http://msdn.microsoft.com/en-us/library/ms189463(v=SQL.110).aspx

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-20 Sorting an nd Filtering Data

Filt tering in the ORDER R BY Clause e Using OF FFSET-FET TCH

While the TOP op ption is used by y many SQL Se erver professio onals as a meth hod for retriev ving only a cer rtain rang ge of rows, it has h its disadvantages as well: TOP is proprietary to T-SQL L and SQL Serv ver TOP does not t support skipp ping a range of o rows Since TOP de epends upon an ORDER BY clause, c you can nnot use one s sort order to es stablish the ro ows play of the output. filters by TOP P, and another sort order to determine disp

To address a a num mber of these concerns, Micro osoft has adde ed a new optio on to SQL Serv ver 2012: the OFF FSET-FETCH ex xtension to the e ORDER BY cla ause.

Like e TOP, OFFSET-FETCH allows s you to return n only a range of the rows se elected by you ur query. Howe ever it add ds the functionality to supply y a starting poi int (an offset) and a value to o specify how m many rows you wou uld like to retu urn (a fetch value). This will provide p a more e convenient t echnique than n previous vers sions of SQL S Server sup pported for pag ging through results. r Whe en paging, you u will need to consider that each query wi th an OFFSET-FETCH clause runs inde ependently of any previous or o subsequent t query: there i is no server-sid de state maint tained. You will need to track you ur position thro ough a result set s via client-si ide code. As you y will see in the next topic c, OFFSET-FETC CH has been w written to allow w a more natural Englishlang guage syntax. nformation See the sectio on "Using OFFS SET and FETCH H to limit the r rows For More In returned" in n Books Online e: http://msdn.microsoft.com m/enus/library/m ms188385%28v v=SQL.110%29 9.aspx

MCT USE ONLY. STUDENT USE PROHIBITED


6-21

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

OFFSET-FET O TCH Synta ax

Th he syntax for the t OFFSET-FETCH clause ap ppears as follow ws:


OFFSET { integer_constan nt | offset_r row_count_exp pression } { ROW | ROWS } [FETCH { FIRST | NEX XT } {integer r_constant | fetch_row_co ount_expressi ion } { ROW | ROWS } ONLY ]

To o use OFFSET-FETCH, you will supply a sta arting OFFSET v value (which m may be zero), a and then an optional nu umber of rows s to return, as in the followin ng example. Th his example will skip the first t 10 rows, and then re eturn then nex xt 10 rows, as determined d by y the orderdate e:
SELECT orderid, custid, orderdate FROM Sales.Orders ORDER BY orderdate, orde erid DESC OFFSET 10 ROWS FETCH NEX XT 10 ROWS;

As you can see in the syntax definition, d the OFFSET clause e is required, b but the FETCH clause is not. If the FE ETCH clause is omitted, all ro ows following the OFFSET w will be returned d. Additionally, , you will find that the ke eywords ROW and ROWS ar re interchangeable, as are FIR RST and NEXT T, which allows s a more natural sy yntax. To o ensure the accuracy of you ur results, espe ecially as you move from p page to page o of data, it is im mportant to o construct an ORDER BY cla ause that will provide p unique e ordering and d yield a determ ministic result. . Th hough it is unl likely due to SQL Servers qu uery optimizer,, it is technical lly possible for r a row to appear on more m than one page unless th he range of rows is determin nistic. o use OFFSET-F FETCH for paging, you may s supply the OF FSET value as well as row Note To count expressions in the e form of variables or param eters. You will learn more ab bout a stored pro ocedure param meters in later m modules of this course. variables and

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-22 Sorting and Filtering Data

Following are some examples of using OFFSET-FETCH in T-SQL queries. All queries use the TSQL2010 sample database: To retrieve the 50 most recent rows as determined by orderdate, this query starts with an offset of zero. This will return a result similar to a SELECT TOP(50) query:
SELECT orderid, custid, empid, orderdate FROM Sales.Orders ORDER BY orderdate DESC OFFSET 0 ROWS FETCH FIRST 50 ROWS ONLY;

The following query will retrieve rows 51-100 of a result set:


SELECT orderid, custid, empid, orderdate FROM Sales.Orders ORDER BY orderdate DESC OFFSET 50 ROWS FETCH NEXT 50 ROWS ONLY;

Note Unlike examples 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.

MCT USE ONLY. STUDENT USE PROHIBITED


6-23

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Demonstra D ation: Filter ring Data with TOP and OFFSE ET-FETCH

Demonstrati D ion Setup


1. .

In the virtual machine, cli ick Start, click All Programs, click Microsof ft SQL Server 2 2012, click SQL L Server Manageme ent Studio. In the t Connect to o Server windo ow, type Prosew ware in the Se erver name tex xt box and click Co onnect. From the t File menu, , click Open, cl lick Project/So olution, navigate to F:\10774A_ _Labs\10774A_ _06_PRJ\10774 4A_06_PRJ.ssm ssln and click Open. Open the 31 3 Demonstration C.sql script file. Follow the instructions co ontained within the commen nts of the scrip pt file.

2. . 3. .

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-24 Sorting an nd Filtering Data

Lesson 4

Workin ng with h Unkno own Val lues

Unli ike traditional Boolean logic c, predicate log gic in SQL Serv ver needs to ac ccount for mis ssing values, an nd to deal with cases wh here the result t of a predicate is unknown. In this lesson, you will learn n how three-va alued logic accounts for r unknown and d missing values, how SQL S erver uses NULL to mark missing values, a and how w to test for NU ULL in your qu ueries.

MCT USE ONLY. STUDENT USE PROHIBITED


6-25

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Three-Valu T ed Logic

Ea arlier in this co ourse, you learned that SQL Server S uses pre edicate logic a as a framework for logical te ests that re eturn TRUE or FALSE. This is true for logica al expressions w where all value es being tested d are present. If you kn now the value of both X and d Y, you can sa afely determine e whether X>Y Y is TRUE or FA ALSE.

However in SQL L Server, not all data being compared c may y be present. Y You need to plan for, and act on the po ossibility that some s data is missing m or unknown. Values in SQL Server may be missin ng but applicable, su uch as the valu ue of a middle initial that has s not been sup pplied for an e employee. It m may also be mis ssing bu ut inapplicable e, such as the value v of a mid ddle initial for a an employee w who has no middle name. In n both ca ases, SQL Serve er will mark th he missing valu ue as NULL. A NULL is neithe er TRUE nor FA ALSE. It is a ma ark for UNKNOWN, wh hich represents s the third valu ue in three-val lue logic. While W as discuss sed above, X>Y is either TRU UE or FALSE fo or known value es of X and Y, w what if Y is mis ssing? What W does SQL Server return for the expres ssion X>Y whe en Y is missing? SQL Server w will return an UNKNOWN, ma arked as NULL L. You will need d to account fo or the possible e presence of NULL in your predicate logic, as well as the values stored in columns m marked with NU ULL. You will n need to write q queries which w use three e-valued logic to account for r three possibl e outcomes: T TRUE, FALSE an nd UNKNOWN N.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-26 Sorting an nd Filtering Data

Ha andling NU ULL in Que eries

Onc ce you have ac cquired a conc ceptual unders standing of thr ree-valued log gic and NULL, y you will also n need to understand u the e several differ rent mechanism ms SQL Server r uses for hand dling NULLs. Keep in mind th he follo owing guidelin nes:

Query filters, such as ON, WHERE, W and the HAVING cla use, treat NUL LL like a FALSE E result. A WHE ERE clause that te ests for a <colu umn_value> = N will not ret turn rows wher re the compar rison is FALSE. Nor will it return rows r where eit ther the colum mn value or the e value of N is NULL. Note th he output of the following que eries:
SE ELECT empid, lastname, re egion FR ROM HR.Employ yees OR RDER BY regio on ASC; --Asc cending sort order explic citly include ed for clarity

This s returns the fo ollowing, with all employees whose region n is missing (m marked as NULL L) sorted first:
em mpid ----------5 6 7 9 8 1 2 3 4 la astname -------------------Bu uck Su uurs King Do olgopyatova Ca ameron Da avis Fu unk Le ew Pe eled regio on --------------NULL NULL NULL NULL WA WA WA WA WA

Note A common questio on about controlling the dis play of NULL i in queries is w whether NULLs can be b forced to th he end of a result set. As you u can see, the O ORDER BY sort ts the NULLs toget ther and first, and a you canno ot override thi s behavior.

MCT USE ONLY. STUDENT USE PROHIBITED


6-27

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

ORDER BY treats NULLs as if they were the same value, and always sorts NULLs first in a column together. Make sure you test the results of any queries where the column being used for sort order contains NULLs, and understand the impact of ascending and descending sorts upon NULLs.

In ANSI-compliant queries, a NULL is never equivalent to another value, even another NULL. Queries written to test NULL with an equality will fail to return correct results. Note the following example:
SELECT empid, lastname, region FROM HR.Employees WHERE region = NULL;

This returns inaccurate results:


empid lastname region ----------- -------------------- --------------(0 row(s) affected)

Use the IS NULL (or IS NOT NULL) operator rather than equals (not equals), as in the following example:
SELECT empid, lastname, region FROM HR.Employees WHERE region IS NULL;

This returns correct results:


empid ----------5 6 7 9 lastname -------------------Buck Suurs King Dolgopyatova region --------------NULL NULL NULL NULL

(4 row(s) affected)

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-28 Sorting an nd Filtering Data

De emonstration: Working with NULL N

Dem monstration n Setup


1.

On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, and cl lick SQL Server Management M Studio. In the e Connect to S Server window w, type Prosew ware in the Ser rver name text bo ox and click Co onnect. From the t File menu , click Open, c click Project/S Solution, navig gate to F:\10774A_ _Labs\10774A_ _06_PRJ\10774 4A_06_PRJ.ssm mssln, and click k Open. Open the 11 Demonstrati ion D.sql script file. file. Follow the ins structions cont tained within the t comments s of the script f

2. 3.

MCT USE ONLY. STUDENT USE PROHIBITED


6-29

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lab: Filtering F g and So orting Data D

La ab Setup

Fo or this lab, you u will use the available a virtua al machine env vironment. Bef fore you begin n the lab, you must co omplete the fo ollowing steps: : 1. . 2. . 3. . On the host computer, click Start, poin nt to Administ trative Tools, and click Hyp per-V Manage er. Maximize the Hyper-V Manager M window. If the virtua al machine 107 774A-MIA-DC C1 is not starte ed: 4. . -MIA-DC1 an d click Start. In the Virtual V Machi ines list, right-click 10774ARight-c click 10774A-MIA-DC1 and d click Connec ct.

In the Virtual V Machi ine Connectio on window, wa ait until the P Press CTRL+ALT T+DELETE to log on messag ge appears, an nd then close the Virtual Ma achine Conne ection window w.

If the virtua al machine 107 774A-MIA-SQ QL1 is not start ted: -MIA-SQL1 an In the Virtual V Machi ines list, right-click 10774And click Start. Right-c click 10774A-MIA-SQL1 and click Conne ect.

In the Virtual V Machi ine Connectio on window, wa ait until the P Press CTRL+ALT T+DELETE to log on messag ge appears, an nd then close the Virtual Ma achine Conne ection window w.

5. . 6. .

In Virtual Machine M Conn nection windo ow, click the R Revert toolbar icon. If you are prompted p to co onfirm that yo ou want to reve ert, click Reve ert. Wait for the revert action n to complete.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-30 Sorting and Filtering Data

7.

If you are not already logged on:

In the Virtual Machine Connection window, click the Ctrl-Alt-Delete menu item on the Action menu. Click Switch User, and then click Other User. Log on using the following credentials: User name: AdventureWorks\Administrator

8. 9.

Password: Pa$$w0rd

In the Virtual Machine Connection window, click Full Screen Mode on the View menu. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.

10. On the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, and click SQL Server Management Studio. 11. In the Connect to Server window, type Proseware in the Server name text box.

12. Click the Options button. Under Connection Properties, select <Browse server> in the Connect to database list. Choose Yes when prompted for the connection to the database. Under User Databases, select the TSQL2012 database. 13. Choose the authentication type, depending on the type of deployment: For an on-premises Microsoft SQL Server instance, click the Login tab, select Windows Authentication in the Authentication list, and click Connect. For Microsoft SQL Azure, click the Login tab, select SQL Server Authentication in the Authentication list, type your login name in the Login text box and the password in the Password text box, and click Connect.

Lab Scenario

You are a business analyst for Adventure Works who will be writing reports using corporate databases stored in SQL Server 2012. You have been provided with a set of business requirements for data and you will write T-SQL queries to retrieve the specified data from the databases. You will need to retrieve only some of the available data, and return it to your reports in a specified order. Important When comparing your results with the provided sample outputs, the column ordering and total number of affected rows should always match. However, remember that the order of the rows in the output of a query without an ORDER BY clause is not guaranteed. Therefore, the order of the rows in the sample outputs may be different than yours. Also, the answer outputs include abbreviated results.

MCT USE ONLY. STUDENT USE PROHIBITED


6-31

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 1: Writing Queries That Filter Data Using a WHERE Clause


Scenario

The marketing department is working on several campaigns for existing customers. The marketing staff needs to get different lists of customers, depending on several business rules. Based on these rules, you will write the SELECT statements to retrieve the needed rows from the Sales.Customers table. The main tasks for this exercise are as follows: 1. 2. 3. Write a couple of SELECT statements that use different predicates in the WHERE clause. Correct the query supplied by the IT department. Answer questions.

X Task 1: Write a SELECT statement that uses a WHERE clause

Open the project file F:\10774A_Labs\10774A_06_PRJ\10774A_06_PRJ.ssmssln and the T-SQL script 51 - Lab Exercise 1.sql. To set your database context to that of the TSQL2012 database, highlight the statement USE TSQL2012; and execute the highlighted code. After executing this statement, the TSQL2012 database should be selected in the Available Databases box. In subsequent exercises, you will simply be instructed to ensure that you are connected to the TSQL2012 database. Write a SELECT statement that will return the custid, companyname, contactname, address, city, country, and phone columns from the Sales.Customers table. Filter the results to include only the customers from the country Brazil.

Execute the written statement and compare the results that you got with the desired results shown in the file 52 - Lab Exercise 1 - Task 1 Result.txt.

X Task 2: Write a SELECT statement that uses an IN predicate in the WHERE clause
Write a SELECT statement that will return the custid, companyname, contactname, address, city, country, and phone columns from the Sales.Customers table. Filter the results to include only customers from the countries Brazil, UK, and USA.

Execute the written statement and compare the results that you got with the desired results shown in the file 53 - Lab Exercise 1 - Task 2 Result.txt.

X Task 3: Write a SELECT statement that uses a LIKE predicate in the WHERE clause
Write a SELECT statement that will return the custid, companyname, contactname, address, city, country, and phone columns from the Sales.Customers table. Filter the results to include only the customers with a contact name starting with the letter A.

Execute the written statement and compare the results that you got with the desired results shown in the file 54 - Lab Exercise 1 - Task 3 Result.txt.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-32 Sorting and Filtering Data

X Task 4: Observe the T-SQL statement provided by the IT department


The IT department has written a T-SQL statement that retrieves the custid and companyname columns from the Sales.Customers table and the orderid column from the Sales.Orders table:
SELECT c.custid, c.companyname, o.orderid FROM Sales.Customers AS c LEFT OUTER JOIN Sales.Orders AS o ON c.custid = o.custid AND c.city = 'Paris';

Execute the query. Notice two things. First, the query retrieves all the rows from the Sales.Customers table. Second, there is a comparison operator in the ON clause specifying that the city column should be equal to the value Paris. Copy the provided T-SQL statement and modify it to have a comparison operator for the city column in the WHERE clause. Execute the query.

Compare the results that you got with the desired results shown in the file 55 - Lab Exercise 1 - Task 4 Result.txt.

Is the result the same as in the first T-SQL statement? Why? What is the difference between specifying the predicate in the ON clause and in the WHERE clause?

X Task 5: Write a SELECT statement to retrieve those customers without orders

Write a T-SQL statement to retrieve customers from the Sales.Customers table that do not have matching orders in the Sales.Orders table. Matching customers with orders is based on a comparison between the customers custid value and the orders custid value. Retrieve the custid and companyname columns from the Sales.Customers table. (Hint: Use a T-SQL statement that is similar to the one in the previous task.) Execute the written statement and compare the results that you got with the desired results shown in the file 56 - Lab Exercise 1 - Task 5 Result.txt.

Results: After this exercise, you should be able to filter rows of data from one or more tables by using WHERE predicates with logical operators.

MCT USE ONLY. STUDENT USE PROHIBITED


6-33

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 2: Writing Queries That Sort Data Using an ORDER BY Clause


Scenario

The sales department would like to have a report showing all the orders with some customer information. An additional request is that the result be sorted by the order dates and the customer IDs. Remember from the previous modules that the order of the rows in the output of a query without an ORDER BY clause is not guaranteed. Because of this, you will have to write a SELECT statement that uses an ORDER BY clause. The main tasks for this exercise are as follows: 1. 2. Write a SELECT statement that uses an ORDER BY clause. Analyze and correct the query.

X Task 1: Write a SELECT statement that uses an ORDER BY clause


Open the project file F:\10774A_Labs\10774A_06_PRJ\10774A_06_PRJ.ssmssln and the T-SQL script 61 - Lab Exercise 2.sql. Ensure that you are connected to the TSQL2012 database. Write a SELECT statement to retrieve the custid and contactname columns from the Sales.Customers table and the orderid and orderdate columns from the Sales.Orders table. Filter the results to include only orders placed on or after April, 1 2008 (filter the orderdate column). Then sort the result by orderdate in descending order and custid in ascending order.

Execute the written statement and compare the results that you got with the desired results shown in the file 62 - Lab Exercise 2 - Task 1 Result.txt.

X Task 2: Apply the needed changes and execute the T-SQL statement
Someone took your T-SQL statement from lab 4 and added the following WHERE clause:
SELECT e.empid, e.lastname, e.firstname, e.title, e.mgrid, m.lastname AS mgrlastname, m.firstname AS mgrfirstname FROM HR.Employees AS e INNER JOIN HR.Employees AS m ON e.mgrid = m.empid WHERE mgrlastname = 'Buck';

Execute the query exactly as written inside a query window and observe the result.

You get an error. What is the error message? Why do you think you got this error? (Tip: Remember the logical processing order of the query.) Apply the needed changes to the SELECT statement so that it will run without an error. Test the changes by executing the T-SQL statement.

Observe and compare the results that you got with the recommended result shown in the file 63 Lab Exercise 2 - Task 2 Result.txt.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-34 Sorting and Filtering Data

X Task 3: Order the result by the firstname column

Copy the existing T-SQL statement from task 2 and modify it so that the result will return all employees and be ordered by the managers first name. Try first to use the source column name, and then try to use the alias column name. Execute the written statement and compare the results that you got with the recommended result shown in the file 64 - Lab Exercise 2 - Task 3 Result.txt. Why were you able to use a source column name or an alias column name?

Results: After this exercise, you should know how to use an ORDER BY clause.

MCT USE ONLY. STUDENT USE PROHIBITED


6-35

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 3: Writing Queries That Filter Data Using the TOP Option
Scenario

The Sales department would like to have some additional reports that show the last invoiced orders and the top 10 percent of most expensive products being sold. The main tasks for this exercise are as follows: 1. 2. Write a SELECT statement that will return the last 20 orders based on order date. Write a SELECT statement that will return the top 10 percent of products based on unit price.

X Task 1: Write a SELECT statement to retrieve the last 20 orders


Open the project file F:\10774A_Labs\10774A_06_PRJ\10774A_06_PRJ.ssmssln and the SQL script 71 Lab Exercise 3.sql. Ensure that you are connected to the TSQL2012 database. Write a SELECT statement against the Sales.Orders table and retrieve the orderid and orderdate columns. Retrieve the last 20 orders, based on orderdate ordering.

Execute the written statement and compare the results that you got with the recommended result shown in the file 72 - Lab Exercise 3 - Task 1 Result.txt.

X Task 2: Use the OFFSET-FETCH clause to implement the same task


Execute the written statement and compare the results that you got with the results from task 1.

Write a SELECT statement to retrieve the same result as in task 1, but use the OFFSET-FETCH clause.

X Task 3: Write a SELECT statement to retrieve the most expensive products


Write a SELECT statement to retrieve the productname and unitprice columns from the Production.Products table. Execute the T-SQL statement and notice the number of the rows returned. Modify the SELECT statement to include only the top 10 percent of products based on unitprice ordering.

Execute the written statement and compare the results that you got with the recommended result shown in the file 73 - Lab Exercise 3 - Task 2 Result.txt. Notice the number of rows returned. Is it possible to implement this task with the OFFSET-FETCH clause?

Results: After this exercise, you should have an understanding of how to apply a TOP option in the SELECT clause of a T-SQL statement.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

6-36 Sorting and Filtering Data

Exercise 4: Writing Queries That Filter Data Using the OFFSET-FETCH Clause
Scenario
In this exercise you will implement a paging solution for displaying rows from the Sales.Orders table because the total number of rows is high. In each page of a report, the user should only see 20 rows. Write a SELECT statement using the OFFSET-FETCH clause.

X Task 1: Use the OFFSET-FETCH clause to fetch the first 20 rows


Open the project file F:\10774A_Labs\10774A_06_PRJ\10774A_06_PRJ.ssmssln and the T-SQL script 81 - Lab Exercise 4.sql. Ensure that you are connected to the TSQL2012 database. Write a SELECT statement to retrieve the custid, orderid, and orderdate columns from the Sales.Orders table. Order the rows by orderdate and orderid. Retrieve the first 20 rows. Execute the written statement and compare the results that you got with the recommended result shown in the file 82 - Lab Exercise 4 - Task 1 Result.txt.

X Task 2: Use the OFFSET-FETCH clause to skip the first 20 rows


Copy the SELECT statement in task 1 and modify the OFFSET-FETCH clause to skip the first 20 rows and fetch the next 20 rows. Execute the written statement and compare the results that you got with the recommended result shown in the file 83 - Lab Exercise 4 - Task 2 Result.txt.

X Task 3: Write a generic form of the OFFSET-FETCH clause for paging

You are given the parameters @pagenum for requested page number and @pagesize for requested page size. Can you figure out how to write a generic form of the OFFSET-FETCH clause using those parameters? (Do not worry about not being familiar with those parameters yet.)

Results: After this exercise, you should have a basic understanding of how to use the OFFSET-FETCH clause.

MCT USE ONLY. STUDENT USE PROHIBITED


6-37

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Modu ule Revi iew

Review R Ques stions

List the module e review questions here. Note e that the num mbers in the nu umbered list a are not auto ge enerated. You will need to enter e the numb bers manually.. Refer to the t template instru uctions for further he elp. 1. . 2. . 3. . Is the use of o ordinal colum mn positions in an ORDER B BY clause recom mmended? Why or why not? Can column n aliases defined in a SELECT T clause be use ed in an ORDE ER BY clause? W Why or why no ot? What is the e relationship between b the ORDER O BY clau se and an OFF FSET-FETCH clause?

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-1

Module 7
Working with SQL Server 2012 Data Types
Contents:
Lesson 1: Introducing SQL Server 2012 Data Types Lesson 2: Working with Character Data Lesson 3: Working with Date and Time Data Lab: Working with SQL Server 2012 Data Types 7-3 7-15 7-25 7-34

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-2 Working Wi ith SQL Server 2012 Data D Types

Module Over rview

In order o to write effective e queries in T-SQL, yo ou will need to o understand h how SQL Serve er stores differ rent type es of data. This s will be espec cially importan nt if your queri es do more th han simply retr rieve data from m tabl les, but also pe erform comparisons, manipu ulate data, and d other operat tions.

In th his module, yo ou will learn ab bout the data types t SQL Serv ver uses to sto ore data. In the e first lesson, y you will be introduced d to many type es of numeric and a special-us se data types. Y You will learn about convers sions betw ween data types, and the im mportance of data type prece edence. You w will learn how t to work with character-based data d types, including functions which can b be used to ma anipulate the d data. You will a also lear rn how to work k with tempora al data, or date and time da ta, including f functions to re etrieve and man nipulate all or portions of a stored s date.

Obj jectives
Afte er completing this module, you y will be able to: Describe num meric data type es, type preced dence and type e conversions.. Write queries s using charact ter data types. Write queries s using date an nd time data ty ypes.

MCT USE ONLY. STUDENT USE PROHIBITED


7-3

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Lesson n1

Introd ducing SQL Server 2012 Data a Types

In n this lesson, yo ou will explore e many of the data types SQ QL Server uses t to store data a and how data types ar re converted between b types. . Note Ch haracter and date/time data types are excl uded from thi is lesson and w will be covered la ater in this mod dule.

If your focus is on o writing que eries for report ts, you may wi ish to take not te of which data types are us sed in yo our environme ent and plan your reports an nd client applic cations with en nough capacit ty to display th he range of f values the SQ QL server data types hold. Yo ou may also ne eed to plan for conversions in your querie es in or rder to display y SQL Server data in other en nvironments. If your focus in taking this cou urse is to continue into data abase developm ment and adm ministration, yo ou may wish w to take not te of the simila arities and diff ferences within n categories of f data types, and plan your s storage ac ccordingly as you y create types and design parameters fo or stored proc edures.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe ho ow SQL Server r uses data types. Describe th he attributes of f numeric data a types, as wel l as binary strings and other r specialized da ata types. Describe da ata type precedence and its use in convert ting data betw ween different data types. Describe th he difference between b implic cit and explicit t data type con nversion.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-4 Working Wi ith SQL Server 2012 Data D Types

SQ QL Server Data D Types s

SQL L Server 2012 defines d a set of system data types for stori ing data in columns, for hold ding values tem mporarily in var riables, for ope erating on data a in expression n, and for pass sing as parame eters in stored proc cedures. Data types specify the t type, lengt th, precision a nd the scale o of data. Unders standing the b basic type es of data in SQ QL Server is fu undamental to writing querie es in T-SQL, as s well as design ning tables and crea ating other obj jects in SQL Se erver.

SQL L Server supplies built-in data types of vari ious categorie s, and develop pers may also e extend the sup pplied set via v aliases to built-in b types, and a even by creating new us ser-defined ty ypes using the .NET Framewo ork. This s lesson will focus on the bui ilt-in system data types. Oth her than charac cter and date/time types, wh hich will be cov vered later in t SQL Server data this module, S type es can be grou uped into the following f categories:

Exact numer ric. These data a types store data with precis sion, either as integers with varying degre ees of capacity, or as decimals which allow you to specify how w many total d digits should be stored, and how many of those digits should d be to the right of the decim mal place. As y you learn abou ut these types, , take note of the re elationship bet tween capacity y and storage requirements.. Approximate e numeric. Th hese data types allow inexact t values to be stored, typically for use in scientific calculations. Binary string gs. These data types allow binary data to b be stored, such h as bytestream ms or hashes, t to support custo om application ns.

Other data types. This catc ch-all category y includes spe ecial types such h as uniqueide entifiers and XM ML, which are som metimes used as column dat ta types (and t therefore accessible to queri ies), to data types that are not used u for storag ge, but for special operation s such as curso or manipulatio ons or creating g output tables s for further pr rocessing. If yo ou are a report t writer, it is lik kely you may o only ever enco ounter the uniqueide entifier and XM ML data types.

MCT USE ONLY. STUDENT USE PROHIBITED


7-5

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Numeric N Data Types

When W working with w exact num meric data, you will see that there are thre ee basic subcat tegories of dat ta types in n SQL Server: exact e numeric, decimal nume eric and appro oximate numer ric. Each SQL S Server data typ pe falls in nto one of thes se categories. Ex xact numeric types include:

Integers, where w the distinction betwee en types relate s to capacity a and storage re equirements. N Note that the tin nyint, for exam mple, can only hold values be etween 0 to 25 55, for the storage cost of one byte. At the othe er end of the spectrum, the bigint b can hol d plus or minu us 9 quintillion n(a very large v value) at the cost of 8 bytes. You will need to decide which integer data t type offers the e best fit for capacity versus stora age. Often you u will see that an a int has bee en selected for r use, providing the best trad deoff between a capacity of plu us or minus 2 billion, for 4 b ytes.

Decimal an nd numeric, which w allow you to specify th he total numbe er of digits to be stored (pre ecision), h integers, the and the number of digits s to the right of o the decimal (scale). As with e greater the ra ange, the higher the storage co numeric ost. Note that while w decimal is ISO standar rds-compliant, decimal and n are equivalent to one ano other. Numeric c is kept for co ompatibility w ith earlier vers sions of SQL Se erver. Money and ld monetary values with a m d smallmoney y, which are de esigned to hol maximum of fo our places. You may find that t your organiza ation uses the decimal type instead of mo oney for its gre eater flexibility an nd precision. Bit, which is a single-bit value v used to store s Boolean values or flags. Storage for a bit column is dependent on how many y other bit colu umns there ma ay be in a tabl e, due to SQL Server optimiz zing their storag ge. For More e Information n See the following topics i n Books Onlin ne: "decimal an nd numeric (Transact SQL)" at http:/ //msdn.micros soft.com/en-u s/library/ms18 87746(v=SQL.1 110).aspx, , Scale, and Length (Transact t-SQL)" at http p://msdn.micro osoft.com/en"Precision, us/library/ /ms190476(v=SQL.110).aspx x and "Data Ty pes (Transact-SQL)" at http://msd dn.microsoft.co om/en-us/libra ary/ms187752 2(v=SQL.110).a aspx

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-6 Working With SQL Server 2012 Data Types

SQL Server also supplies data types for approximate numeric values with less accuracy, but more capacity, than the exact numerics. These store values in scientific notation, which loses accuracy because of a lack of precision. Float takes an optional parameter of the number of digits to be stored after the decimal. This parameter is called the mantissa, and the value of the mantissa determines the storage size of the float. If the mantissa is in the range 1 to 24, the float requires 4 bytes. If the mantissa is between 25 and 53, it will require 8 bytes. Real is an ISO synonym for float(24). For More Information See the topic "float and real (Transact-SQL)" in Books Online at http://msdn.microsoft.com/en-us/library/ms173773(v=SQL.110).aspx.

MCT USE ONLY. STUDENT USE PROHIBITED


7-7

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying M Microsoft SQL Server r 2012

Binary B Strin ng Data Ty ypes

Bi inary string typ pes allow a de eveloper to sto ore binary infor rmation, such as serialized fi iles, images, by ytestreams and d other specialized data. If you y are consid ering using a b binary data type, note the co omparative dif fferences in range and storag ge, as with int egers and (as you will see la ater in this mod dule) ch haracter string g data. You can n choose betw ween fixed-widt th and varying g width binary y strings. The di ifference betw ween these will be explained in the charact ter data type le esson later in t the module.

Th he following example shows s a number con nverted to a b binary data typ pe. (You will lea arn about the CAST fu unction in the next module). This query:
SELECT CAST(12345 AS BIN NARY(4)) AS Result; R

Re eturns the follo owing:


Result ---------0x00003039

For More e Information n See the top pic "binary and d varbinary (Tra ansact-SQL)" in Books Online at http://msdn.m microsoft.com/ /en-us/library/ /ms188362(v= =SQL.110).aspx x.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-8 Working Wi ith SQL Server 2012 Data D Types

Other Data Types T

In addition to num meric and bina ary types, SQL Server also su pplies some o other data type es, allowing yo ou to stor re and process XML, to gene erate globally unique u identifi iers, represent t hierarchies, and others. Som me of thes se have limited d use, others are a more generally useful:

Rowversion is a binary valu ue, auto-incrementing when n a row in a ta ble is inserted or updated. It t does not actually store s time data a in a form tha at will be usefu ul to you, and it has other lim mitations as we ell. Uniqueident tifier provides a mechanism for an automa atically-genera ated value tha at is unique acr ross multiple syste ems. It is stored d as a 16 byte value, and mu ust be generat ted either by c converting from ma string (reducing the guaran ntee of uniqueness) or by us ing the NEWID D() system fun nction:
SE ELECT NEWID() AS [GUID];

Retu urns:
GU UID -----------------------------------1C C0E3B5C-EA7A-41DC-8E1C-D0 0A302B5E58B

The XML data type allows the t storage an nd manipulatio on of eXtensible Markup Lan nguage data. T This data type stores up to 2GB of data per instance of the t type. nformation on XML data, see course 10 0776A: Implem menting a SQL Server For More In 2012 Datab base

Cursors are listed here for completeness. . A SQL Server r cursor is not a data type for storing data, , but rather for use e in variables or o stored proce edures that ref ference a curso or object. Disc cussions of cursors are beyond th he scope of this module.

MCT USE ONLY. STUDENT USE PROHIBITED


7-9

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

HierarchyID is a data type used to store hierarchical position data, such as levels of an organizational chart or bill of materials. SQL Server stores hierarchy data as binary data, and exposes it through builtin functions. For More Information Denali Database on hierarchyid, see course 10776A: Implementing a SQL Server

SQL_variant is a column data type that can store other common data types. Its use is not a best practice for typical data storage and may indicate design problems. It is listed here for completeness. Table data types can be used to store the results of T-SQL statements for further processing later, such as in a subsequent statement in a query. You will learn more about table types later in this course. Note: table types cannot be used as a data type for a column (such as to store nested tables). For More Information Information on all of SQL Server's data types can be found in Books Online starting at http://msdn.microsoft.com/enus/library/ms187752(v=SQL.110).aspx

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-10 Working With W SQL Server 2012 2 Data Types

Da ata Type Pr recedence e

Whe en combining or comparing g different data a types in your r queries, such h as in a WHER RE clause, SQL Serv ver will need to o convert one value from its s data type to t the data type of the other v value. Which da ata en the two typ type e is converted depends on data d type prece edence betwee pes.

SQL L Server define es a ranking of all its data typ pes by precede ence: between n any two data a types, one wi ill have a lower prec cedence and one will have a higher preced dence. When c converting, SQ QL Server will convert the lower r data type to the t higher. This typically will l happen implicitly, without need for special code. However, it is important for f you to have e a basic unde erstanding of t this precedenc ce arrangemen nt so you will know whe en you need to manually, or r explicitly con nvert data type es for the purp poses of combining or converting c them. For example, here e is a partial list of data types s, ranked acco ording to their precedence: 1. 2. 3. 4. 5. 6. 7. 8. 9. XML Datetime2 Date Time Decimal Int Tinyint Nvarchar Char

MCT USE ONLY. STUDENT USE PROHIBITED


7-11

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

When combining or comparing two expressions with different data types, the expression lower on this list will be converted to the type higher on the list. In this example, the variable of type tinyint will be implicitly converted to an int before being added to the int variable @myInt:
DECLARE @myTinyInt AS TINYINT = 25; DECLARE @myInt as INT = 9999; SELECT @myTinyInt + @myInt;

Note Implicit conversions are transparent to the user. If an implicit conversion fails (such as when your operation requires converting from a higher precedence to a lower precedence), you will need to explicitly convert the data type. You will learn how to use the CAST function for this purpose in the next module. For More Information For more information and a complete list of types and their precedence, see Books Online: http://msdn.microsoft.com/enus/library/ms190309(v=sql.110).aspx

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-12 Working With W SQL Server 2012 2 Data Types

Wh hen Are Da ata Types Converted d?

There are a numb ber of scenarios in which data types may b be converted w when querying SQL Server: When data is moved, comp pared or comb bined with othe er data During variab ble assignment t When using any a operator that involves tw wo operands o of different typ pes When T-SQL code explicitly y converts one e type to anoth her, using a CA AST or CONVE ERT function

In th he previous to opic's example, , you saw that conversion wo ould be necessary:


DE ECLARE @myTin nyInt AS TINY YINT = 25; DE ECLARE @myInt t as INT = 99 999; SE ELECT @myTiny yInt + @myInt t;

You u might also an nticipate that conversion c will be necessary y in the following example:
DE ECLARE @somec char CHAR(5) = '6'; DE ECLARE @someint INT = 1 SE ELECT @somech har + @somein nt;

Question: Which data type e will be conve erted? To whic h type?

As you y have learn ned, SQL Server will automat tically attempt to perform an n implicit conv version from a lower-precedence e data type to a higher-precedence. This is s transparent t to the user, un nless it fails, as in the follo owing example e:
DE ECLARE @somec char CHAR(3) = 'six'; DE ECLARE @someint INT = 1 SE ELECT @somech har + @somein nt;

MCT USE ONLY. STUDENT USE PROHIBITED


7-13

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Returns:
Msg 245, Level 16, State 1, Line 3 Conversion failed when converting the varchar value 'six' to data type int.

Question: Why does SQL Server attempt to convert the character variable to an integer and not the other way around?

In order to force SQL Server to convert the int data type to a character for the purposes of the query, you will need to explicitly convert it. You will learn how to do this in the next module. For More Information See Books Online: http://msdn.microsoft.com/enus/library/ms191530(v=SQL.110).aspx

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-14 Working With W SQL Server 2012 2 Data Types

De emonstration: SQL Se erver Data a Types

In th his demonstration, you will see s queries usi ing implicit an nd explicit conv versions.

Dem monstration n Steps


1.

On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, and cl lick SQL Server Management M Studio. In the e Connect to S Server window w, type Prosew ware in the Ser rver name text bo ox and click Co onnect. On the File menu, cli ck Open and c click Project/So olution. Navig gate to F:\10774A_La abs\10774A_07 7_PRJ\10774A_ _07_PRJ.ssmssl ln and click Op pen. On the View menu, click So olution Explor rer. Open the 11 Demonstrati ion A.sql script t file. Follow the ins structions cont tained within the t comments s of the script f file.

2. 3. 4.

MCT USE ONLY. STUDENT USE PROHIBITED


7-15

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n2

Work king wit th Chara acter Da ata

It is likely that much m of the da ata you will wo ork with in you ur T-SQL queri es will involve e character dat ta. As yo ou will learn in n this lesson, ch haracter data involves i not o nly choices of capacity and storage, but te extsp pecific issues such as languag ge, sort order collation. In th his lesson you will learn abou ut the SQL Ser rver ch haracter-based d data types, how h character comparisons w work, and som me common functions you m may find us seful in your queries.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe th he character da ata types supp plied by SQL Se erver. Describe th he impact of co ollation on cha aracter data. Concatenat te strings. Extract and manipulate character data using built-in functions. Write queri ies using the LIKE L predicate for matching p xt. patterns in tex

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-16 Working With W SQL Server 2012 2 Data Types

Character Da ata Types

Even though there are many nu umeric data typ pes in SQL Ser rver, working w with numbers is relatively straightforward: there are only so s many numb bers to work w with. By compa arison, character data in SQL L Serv ver is far more wide open, du ue to issues su uch as languag ge, character se ets, accented c characters, sor rt rule es, case-sensitiv vity as well as capacity and storage. s Each o of these issues s will have an impact on which character data typ pe you will enc counter when writing querie es.

One initial choice is that character types based b upon a simple ASCII s set versus Unic code, the doub blebyte characte er set. Regular r, or non-Unico ode characters s are limited to o a 256 charac cter set, and oc ccupy one byte per character. The ese include the e CHAR (fixed width), and VA ARCHAR (vary ying width) dat ta types. Charac cters using these data types are a delimited w with single qu uotes, such as 'SQL'. Unicode data a types include e NCHAR (fixed d width), and N NVARCHAR (v varying width). These may represent app proximately six xty-five thousa and different c characters, incl luding special characters fro om many languag ges, and consu ume 2 bytes per character. C Character strings using this t type have a N' prefix (for Na ational), such as a N'SQL'.

Character dat ta types also provide p for larg ger storage, in the form of re egular and Unicode varying width types declared with the MA AX option: VAR RCHAR(MAX) a and NVARCHA AR(MAX). Thes se can store up p to 2 GB (with each h Unicode character using 2 bytes) per inst tance, and rep place the deprecated TEXT and NTEXT data types respectiv vely.

MCT USE ONLY. STUDENT USE PROHIBITED


7-17

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Collation C

In n addition to si ize and charac cter set, SQL Se erver characte r data types ar ed a collation. This re also assigne as ssignment may y be at one of several levels: : the server ins stance, the dat tabase default, , a collation as ssigned to o a column in a table, or in an a expression. Collations are collections of f properties tha at govern seve eral as spects of chara acter data: Supported languages Sort order Case sensitivity Accent sens sitivity Note A default d collatio on is establishe ed during insta L Server, but c can be allation of SQL overridden n per-database e or per-colum mn. As you will l see, you may y also override the current collation for some chara acter data by explicitly e settin ng a different c collation in you ur query.

When W querying, it will be imp portant to be aware a of what the collation s settings are for your character data. Fo or example, is it case-sensitiv ve? The follow wing query will execute differ rently based o on whether the e co olumn being compared c is ca ase-sensitive or not. If the co olumn is case-s sensitive and t the desired val lue is Fu unk, then this will w succeed:
SELECT empid, lastname FROM HR.employees WHERE W lastname = N'Funk';

Fo or the same da ata, this would d return invalid d results if the column were case-sensitive: :
SELECT empid, lastname FROM HR.employees WHERE W lastname = N'funk';

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-18 Working With SQL Server 2012 Data Types

To control how your query is treating collation settings, you can add the optional COLLATE clause to the WHERE clause. This example will force a case-sensitive, accent-sensitive comparison using the Latin1_General character set:
SELECT empid, lastname FROM HR.employees WHERE lastname COLLATE Latin1_General_CS_AS = N'Funk';

MCT USE ONLY. STUDENT USE PROHIBITED


7-19

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

String Conc catenation n

To o concatenate, or join together, two string gs, SQL Server uses the + (plus) operator. T The following ex xample concat tenates a given n name, a spac ce and a family y name into a single string:
SELECT empid, lastname, firstna ame, firstnam me + N' ' + l lastname AS f fullname FROM HR.Employees;

Note Sin nce the plus sig gn is also used d for arithmeti c addition, be aware of whe ether any of your data is numeric wh hen concatenat ting. Characte rs have a lowe er precedence than er will attempt to convert an nd add mixed d data types rath her than numbers, and SQL Serve ating them. concatena SQ QL Server 2012 2 introduces a new CONCAT T() function, w which returns a string that is t the result of co oncatenating one o or more st tring values. Unlike the + op perator, CONC CAT() will conve ert any NULLs to em mpty strings before b concatenation. The sy yntax is as follo ows:
CONCAT(string_value1, st tring_value2, string_valu ueN)

An example of CONCAT() C follows:


SELECT custid, city, reg gion, country y, CONCAT T(city, ', ' + region, ', , ' + country y) AS locatio on FROM Sales.Customers;

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-20 Working With SQL Server 2012 Data Types

Returns the following partial results:


custid -----1 2 3 4 5 city ----------Berlin Mxico D.F. Mxico D.F. London Lule region -----NULL NULL NULL NULL NULL country -------Germany Mexico Mexico UK Sweden location ------------------Berlin, Germany Mxico D.F., Mexico Mxico D.F., Mexico London, UK Lule, Sweden

For More Information See the topic " CONCAT (Transact-SQL)" in Books Online http://msdn.microsoft.com/en-us/library/hh231515(v=SQL.110).aspx.

MCT USE ONLY. STUDENT USE PROHIBITED


7-21

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Character C String S Func ctions

In n addition to re etrieving chara acter data as-is from SQL Se rver, you may also need to e extract portion ns of te ext, or determine the location of character rs within a larg ger string. SQL Server provides a number o of builtin n functions to accomplish a the ese tasks. Som me of these fun nctions include e: FORMAT() new to SQL Server 2012 - allows you to o format an inp put value to a character strin ng based on a .NET format string, s with an optional cultu ure parameter::
SELECT top (3) orderid, FORMAT(order rdate,'d','en n-us') AS us, FORMAT(orde erdate,'d','deDE') as de FROM Sales.Orders;

Re eturns
Ordered ------10248 10249 10250 us -------7/4/2006 7/5/2006 7/8/2006 de ---------04.07.2006 05.07.2006 08.07.2006

SUBSTRING() for returni ing part of a character string g given a starti ing point and a number of characters to t return:
SELECT SUBST TRING('Micros soft SQL Serv ver',11,3) AS S Result;

Re eturns Result -----SQL

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-22 Working With SQL Server 2012 Data Types

LEFT() and RIGHT() for returning the leftmost or rightmost, respectively, characters up to a provided point in a string:
SELECT LEFT('Microsoft SQL Server',9) AS Result;

Returns
Result --------Microsoft

LEN() and DATALENGTH() for providing metadata about the number of characters or number of bytes stored in a string. Given a string padded with spaces:
SELECT LEN('Microsoft SQL Server ') SELECT DATALENGTH('Microsoft SQL Server Returns LEN ----------20 DATALEN ----------25 ') AS [LEN]; AS [DATALEN];

CHARINDEX() for returning a number representing the position of a string within another string:
SELECT CHARINDEX('SQL','Microsoft SQL Server') AS Result;

Returns
Result ----------11

REPLACE() for substituting one set of characters with another set within a string:
SELECT REPLACE('Microsoft SQL Server Denali','Denali','2012') AS Result;

Returns
Result -----Microsoft SQL Server 2012

UPPER(), LOWER() for performing case conversions:


SELECT UPPER('Microsoft SQL Server') AS [UP],LOWER('Microsoft SQL Server') AS [LOW]; Returns UP LOW -------------------- -------------------MICROSOFT SQL SERVER microsoft sql server

For More Information For reference on these and other string functions, see Books Online: http://msdn.microsoft.com/en-us/library/ms181984(v=SQL.110).aspx

MCT USE ONLY. STUDENT USE PROHIBITED


7-23

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

The T LIKE Pr redicate

Character-based d data in SQL Server provide es for more tha an exact matches in your qu ueries. Through h the us se of the LIKE predicate, you u can also perform pattern m matching in yo our WHERE clause. are expressed with Th he LIKE predicate allows you u to check a ch haracter string against a patt tern. Patterns a sy ymbols, which can be used alone a or in com mbinations to s search within y your strings: % (Percent t) represents a string of any length: LIKE N N'Sand%' will m match 'Sand', 'Sandwich', 'Sandwiche es', etc.

_ (Undersc core) represents a single cha aracter: LIKE N '_a' will match h any string wh hose second ch haracter is an 'a'. [<List of characters>] re epresents a sin ngle character within the sup pplied list: LIKE E N'[DEF]%' will find any string which w starts wi ith a 'D, an 'E' or an 'F'. [<Characte er> - <charac cter>] represents a single ch haracter within n the specified range: LIKE N N'[NZ]%' will match any string g with starts with w any letter o of the alphabe et between N a and Z, inclusiv ve. [^<Charac cter list or ran nge>] represents a single ch haracter not in the specified list or range: L LIKE N'^[A]% wi ill match a string beginning with anything g other than an n 'A'.

ESCAPE Ch haracter allows s you to search h for a charact er that is also a wildcard cha aracter: LIKE N N'10% off%' ESCAPE '%' will find d any string that starts with 1 10%, including g the literal character '%'.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-24 Working With W SQL Server 2012 2 Data Types

De emonstration: Working with Character D Data

In th his demonstration, you will see s how to que ery and manip pulate SQL Ser rver character data types.

Dem monstration n Steps


1.

On the virtual machine, clic ck Start, click All A Programs, click Microso oft SQL Server 2012, and cl lick SQL Server Management M Studio. In the e Connect to S Server window w, type Prosew ware in the Ser rver name text bo ox and click Co onnect. On the File menu, cli ck Open and c click Project/So olution. Navig gate to F:\10774A_La abs\10774A_07 7_PRJ\10774A_ _07_PRJ.ssmssl ln and click Op pen. On the View menu, click So olution Explor rer. Open the 21 Demonstrati ion B.sql script t file. Follow the ins structions cont tained within the t comments s of the script f file.

2. 3. 4.

MCT USE ONLY. STUDENT USE PROHIBITED


7-25

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Lesson n3

Work king wit th Data and Tim me Data a

Date and time data d is very common in work king with SQL Server data ty ypes. In this les sson you will le earn which w data type es are used to store tempora al data, how to o enter dates a and times so th hey will be pro operly pa arsed by SQL Server, S and ho ow to manipula ate dates and t times with bui ilt-in functions s.

Le esson Objec ctives


After completin ng this lesson, you y will be able to: Describe th he data types used u to store date d and time information Enter dates s and times as literal values for f SQL Server to convert to date/time typ pes Write queri ies comparing dates and tim mes Write queri ies using built-in functions to o manipulate dates and extr ract date parts s

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-26 Working With W SQL Server 2012 2 Data Types

Da ate and Tim me Data Ty ypes

There has been a progression in n SQL Server's handling of te emporal data a as newer versions of SQL Server are released. Since e you may nee ed to work wit th data created d for older ver rsions of SQL S Server even tho ough you're writing que eries for SQL Server S 2012, it will be useful to review past t support for d date/time data a:

Prior to SQL Server S 2008, th here were only y two data typ es for date and time data: D DATETIME and SMALLDATET TIME. Each of these t stored both date and t time in a singl e value: for ex xample, a DATE ETIME could store '2 20120212 08:30:00' to repres sent February 12 2012 at 8:3 30 AM. (Note: you will learn about using string s literals to o represent da ates later in thi is lesson.)

In SQL Server r 2008, Microso oft introduced d new data typ pes: DATETIME E2, DATE, TIME E, DATETIMEOFFSET. These addressed issues of precision, p capa acity, time zone e tracking and d separating da ates from time es. You will learn n more about these t in this le esson. In SQL Server r 2012, Microso oft introduced d new function ns for working with partial da ata from date and tes (such as time data typ pes (such as DA ATEFROMPART TS) and for pe rforming calcu ulations on dat EOMONTH). You Y will learn about these fu unctions in thi s lesson.

MCT USE ONLY. STUDENT USE PROHIBITED


7-27

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Date D and Time Data Types: T Lite erals

In n order to use date and time e data in your queries, q you w will need to be able to repres sent temporal data in T-SQL. SQL Serv ver doesn't off fer a specific option for ente ering dates and d times, so you u will use chara acter st trings called lit terals, delimite ed with single quotes, q and SQ QL Server will implicitly conv vert the charac cters to da ate/time value es. (You may also explicitly co onvert literals with the T-SQ QL CAST functio on, which you will le earn about in the next modu ule.) SQ QL Server can interpret a wid de variety of literal formats a as dates, but fo or consistency y and to avoid issues with w language or o nationality interpretation, i it is recomme ended that you u use a neutral format such as 'Y YYYYMMDD'. To T represent Fe ebruary 12, 20 012, you would d use the litera al '20120212'. To use literals s in a qu uery, see the following f exam mple:
SELECT orderid, custid, empid, order rdate FROM Sales.Orders WHERE W orderdate = '20070 0825;

Be esides 'YYYYM MMDD', other language-neut tral formats ar re available to you: Data type DATETIME Langua age-neutral Fo ormats 'YYYYM MMDD hh:mm m:ss.nnn' 'YYYY-MM-DDThh:m mm:ss.nnn' 'YYYYM MMDD' 'YYYYM MMDD hh:mm m' 'YYYY-MM-DDThh:m mm' 'YYYYM MMDD' 'YYYY-MM-DD' 'YYYYM MMDD hh:mm m:ss.nnnnnnn' 'YYYY-MM-DD hh:m mm:ss.nnnnnnn n' 'YYYY-MM-DDThh:m mm:ss.nnnnnn n' 'YYYYM MMDD' Examples '20120212 1 12:30:15.123' '2012-02-12 2T12:30:15.123 3' '20120212' '20120212 1 12:30' '2012-02-12 2T12:30' '20120212'

SMALLDATET TIME

DATETIME2

'20120212 1 12:30:15.12345 567' '2012-02-12 2 12:30:15.1234567' '2012-02-12 2T12:30:15.123 34567' '20120212' 2' '2012-02-12

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-28 Working With SQL Server 2012 Data Types

Data type

Language-neutral Formats 'YYYY-MM-DD'

Examples

DATE

'YYYYMMDD' 'YYYYMMDD' 'hh:mm:ss.nnnnnnn' 'YYYYMMDD hh:mm:ss.nnnnnnn [+|-]hh:mm' 'YYYY-MM-DD hh:mm:ss.nnnnnnn [+|-]hh:mm' 'YYYYMMDD' 'YYYY-MM-DD'

'20120212' '2012-02-12' '12:30:15.1234567' '20120212 12:30:15.1234567 +02:00' '2012-02-12 12:30:15.1234567 +02:00' '20120212' '2012-02-12'

TIME DATETIMEOFFSET

MCT USE ONLY. STUDENT USE PROHIBITED


7-29

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Working W with w Date and Time Separately S

As you have lea arned, some SQ QL Server temp poral data typ es store both date and time e together in o one va alue. DATETIM ME, DATETIME2 2 combine year, month, day,, hour, minute, sec and furth her; DATETIME EOFFSET ad dds time zone information to this as well. When using th hese data type es, you need to o be aware of how th hey behave wh hen only provid ded with partial data: If no time data d is provide ed, but only da ate, the time p ortion of the d data type is fill led with zeros, , and the time is considered to be at midnigh ht. Time data i s optional in t the combinatio on data types such as DATETIME2 2.
DECLARE @DateOnly @ AS DATETIME = '20120212'; SELECT @D DateOnly AS RESULT; R

Returns
RESULT ----------------------2012-02-1 12 00:00:00.0 000

If no date data d is available, and you need to store TIM ME data only in a combination data type, either you will nee ed to enter a "base" " date of January 1, 190 00, or you may y use the CAST T() function to o convert to a DATETIME (o or other comb bination) while entering just the time value e. SQL Server w will assume the e base date. Ex xplicit zeros for r the date port tion are not pe ermitted.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-30 Working With W SQL Server 2012 2 Data Types

Qu uerying Da ate and Tim me Values

Whe en querying data and time data d types, it is s important to o know whethe er your source data includes time valu ues other than zeros. If all yo our time values s are midnight t, then queries s such as the fo ollowing will w work as expected: e
SE ELECT orderid d, custid, em mpid, orderda ate FR ROM Sales.Ord ders WH HERE orderdat te= '20070825 5'

Retu urns:
or rderid ----------10 0643 10 0644 cu ustid ----------1 88 8 em mpid ----------6 3 or rderdate ----------------------20 007-08-25 00 :00:00.000 20 007-08-25 00 :00:00.000

Not te that the orderdate time va alues are all se et to zero. This matches the q query predicat te, which also omits time e, implicitly asking only for rows r at midnig ght. If yo our data does include time values v you will need to modi ify your logic t to catch time v values after mid dnight. For example, if the fo ollowing rows existed e in an o orders2 table,
or rderid ----------10 0643 10 0644 cu ustid ----------1 88 8 em mpid ----------6 3 or rderdate ----------------------20 007-08-29 08 :30:00.000 20 007-08-29 11 :55:00.000

Then the following query would d fail to select them:


SE ELECT orderid d, empid, cus stid, orderda ate FR ROM orders2 WH HERE orderdat te = '2007082 29'

MCT USE ONLY. STUDENT USE PROHIBITED


7-31

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

But this query would successfully retrieve the rows.


SELECT orderid, empid, custid, orderdate FROM orders2 WHERE orderdate >= '20070829'

Note The previous example is supplied for illustration only and cannot be run as written in the sample databases supplied with this course.

As a result, you will need to account for time past midnight for rows where there are values stored in the time portion of combination date/time data types. Consider the use of range operators instead:
SELECT orderid, custid, empid, orderdate FROM Sales.Orders WHERE orderdate >= '20070825' AND orderdate < '20070826';

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-32 Working With W SQL Server 2012 2 Data Types

Da ate and Tim me Functio ons

Ove er the years, SQ QL Server has supplied s a num mber of functio ons designed to manipulate e date and time data a. SQL Server 2012 2 introduce es new functio ons as well: Functions tha at return current date and tim me offer choic ces between va arious return types, as well a as whether to in nclude or exclu ude time zone information.

Functions tha at return part of o dates and time enable you u to extract on nly the portion n of a date or t time that your que ery requires. Note that DATE ENAME() and D DATEPART() of ffer functionality similar to o one another - the e difference be etween them is s the return typ pe.

New to SQL Server S 2012 are functions tha at return date and time type ed data from c components su uch as separately supplied year, month m and day. . Previous vers sions required parsing of stri ings to assemb ble a literal that loo oked like a dat te: these new functions f allow w you to pass in simple num meric inputs for r the functions to convert c to the corresponding g date/time va alue. Note tha t these functio ons require all their parameters. Functions tha at modify date and time valu ues include fun nctions to incre ement dates, t to calculate the last day of a mon nth, and to alte er time zone of ffset informati ion.

Functions tha at examine dat te and time values, return m etadata or cal culations abou ut intervals between input dates.

MCT USE ONLY. STUDENT USE PROHIBITED


7-33

BETA COURSEWARE EXPIRES 11/2012

1 10774A: Querying Microsoft SQL Server 2 2012

Demonstra D ation: Work king with Date and Time Data a

In n this demonst tration, you will see how to query q date and d time values, and how to us se built-in SQL L Server 20 012 functions to manipulate e date and time e data.

Demonstrati D ion Steps


1. .

On the virtu ual machine, click c Start, click All Program ms, click Micro osoft SQL Serv ver 2012, and click SQL Server r Managemen nt Studio. In the Connect to o Server wind dow, type Prose eware in the S Server click Open and name text box b and click Connect. C On th he File menu, c d click Project/ /Solution. Nav vigate to F:\10774A_ _Labs\10774A_ _07_PRJ\10774 4A_07_PRJ.ssm ssln and click Open. On the View w menu, click Solution Expl lorer. Open the 31 3 Demonstration C.sql script file. Follow the instructions co ontained within the commen nts of the scrip pt file.

2. . 3. . 4. .

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-34 Working With W SQL Server 2012 2 Data Types

Lab: Working W with SQ QL Serv ver 2012 2 Data T Types

Lab b Setup
For this lab, you will w use the ava ailable virtual machine m enviro onment. Befor re you begin the lab, you mu ust com mplete the follo owing steps: 1. 2. 3. On the host computer, c click k Start, point to t Administra ative Tools, an nd click Hyper r-V Manager. Maximize the e Hyper-V Ma anager window w. If the virtual machine m 1077 74A-MIA-DC1 1 is not started : 4. In the Virtual Machine es list, right-click 10774A-M MIA-DC1 and c click Start. Right-clic ck 10774A-MIA-DC1 and click Connect.

In the Virtual Machine e Connection window, wait until the Press CTRL+ALT+ +DELETE to log g on message appears, and then close the e Virtual Mach hine Connect tion window.

If the virtual machine m 1077 74A-MIA-SQL1 is not started d: In the Virtual Machine es list, right-click 10774A-M MIA-SQL1 and d click Start. Right-clic ck 10774A-MIA-SQL1 and click c Connect .

In the Virtual Machine e Connection window, wait until the Press CTRL+ALT+ +DELETE to log g on message appears, and then close the e Virtual Mach hine Connect tion window.

5. 6.

In Virtual Ma achine Conne ection window w, click the Rev vert toolbar ico on. If you are pro ompted to con nfirm that you want to revert t, click Revert. Wait for the r revert action to complete.

MCT USE ONLY. STUDENT USE PROHIBITED


7-35

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

7.

If you are not already logged on:

In the Virtual Machine Connection window, click the Ctrl-Alt-Delete menu item on the Action menu. Click Switch User, and then click Other User. Log on using the following credentials: User name: AdventureWorks\Administrator Password: Pa$$w0rd

8. 9.

In the Virtual Machine Connection window, click Full Screen Mode on the View menu.

If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.

10. On the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, and click SQL Server Management Studio. 11. In the Connect to Server window, type Proseware in the Server name text box.

12. Click the Options button. Under Connection Properties, select <Browse server> in the Connect to database list. Choose Yes when prompted for the connection to the database. Under User Databases, select the TSQL2012 database 13. Choose the authentication type, depending on the type of deployment: For an on-premises Microsoft SQL Server instance, click the Login tab, select Windows Authentication in the Authentication list, and click Connect. For Microsoft SQL Azure, click the Login tab, select SQL Server Authentication in the Authentication list, type your login name in the Login text box and the password in the Password text box, and click Connect.

Lab Scenario

You are a business analyst for Adventure Works who will be writing reports using corporate databases stored in SQL Server 2012. You have been provided with a set of business requirements for data and you will write T-SQL queries to retrieve the specified data from the databases. You will need to retrieve and convert character and temporal data into various formats. Important When comparing your results with the provided sample outputs, the column ordering and total number of affected rows should always match. However, remember that the order of the rows in the output of a query without an ORDER BY clause is not guaranteed. Therefore, the order of the rows in the sample outputs may be different than yours. Also, the answer outputs include abbreviated results.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-36 Working With SQL Server 2012 Data Types

Exercise 1: Writing Queries That Return Date and Time Data


Scenario
Before you start using different date and time functions in business scenarios, you have to practice on sample data. The main tasks for this exercise are as follows: 1. 2. Write a couple of SELECT statements using the date and time functions. Answer questions.

X Task 1: Write a SELECT statement to retrieve the current date and time

Open the project file F:\10774A_Labs\10774A_07_PRJ\10774A_07_PRJ.ssmssln and the T-SQL script 51 - Lab Exercise 1.sql. To set your database context to that of the TSQL2012 database, highlight the statement USE TSQL2012; and execute the highlighted code. After executing this statement, the TSQL2012 database should be selected in the Available Databases box. In subsequent exercises, you will simply be instructed to ensure that you are connected to the TSQL2012 database. Write a SELECT statement to return columns that contain: The current date and time. Use the alias currentdatetime. Just the current date. Use the alias currentdate. Just the current time. Use the alias currenttime. Just the current year. Use the alias currentyear. Just the current month number. Use the alias currentmonth. Just the current day of month number. Use the alias currentday. Just the current week number in the year. Use the alias currentweeknumber. The name of the current month based on the currentdatetime column. Use the alias currentmonthname.

Execute the written statement and compare the results that you got with the desired results shown in the file 52 - Lab Exercise 1 - Task 1 Result.txt. Your results will be different because of the current date and time value. Can you use the alias currentdatetime as the source in the second column calculation (currentdate)? Please explain.

X Task 2: Write a SELECT statement to return the data type date


Write December 11, 2011, as a column with a data type of date. Use the different possibilities inside the T-SQL language (cast, convert, specific function, etc.) and use the alias somedate.

MCT USE ONLY. STUDENT USE PROHIBITED


7-37

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

X Task 3: Write a SELECT statement that uses different date and time functions
Write a SELECT statement to return columns that contain: Three months from the current date and time. Use the alias threemonths. Number of days between the current date and the first column (threemonths). Use the alias diffdays. Number of weeks between April 4, 1992, and September 16, 2011. Use the alias diffweeks. First day in the current month based on the current date and time. Use the alias firstday.

Execute the written statement and compare the results that you got with the desired results shown in the file 53 - Lab Exercise 1 - Task 3 Result.txt. Some results will be different because of the current date and time value.

X Task 4: Observe the table provided by the IT department


The IT department has written a T-SQL statement that creates and populates a table named Sales.Somedates. Execute the provided T-SQL statement.

Write a SELECT statement against the Sales.Somedates table and retrieve the isitdate column. Add a new column named converteddate with a new date data type value based on the column isitdate. If the column isitdate cannot be converted to a date data type for a specific row, then return a NULL.

Execute the written statement and compare the results that you got with the desired results shown in the file 54 - Lab Exercise 1 - Task 4 Result.txt. What is the difference between the SYSDATETIME and CURRENT_TIMESTAMP functions? What is a language-neutral format for the DATE type?

Results: After this exercise, you should be able to retrieve date and time data using T-SQL.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-38 Working With SQL Server 2012 Data Types

Exercise 2: Writing Queries That Use Date and Time Functions


Scenario

The sales department would like to have different reports that focus on data during specific time frames. The sales staff would like to analyze distinct customers, distinct products, and orders placed near the end of the month. You will have to write the SELECT statements using the different date and time functions. The main tasks for this exercise are as follows: 1. 2. 3. 4. Write a SELECT statement to retrieve all distinct customers that placed an order in February 2008. Write a SELECT statement to retrieve all orders placed in last five days of the month. Write a SELECT statement to show all distinct products being sold in the first 10 weeks of the year 2007. Analyze and correct the query.

X Task 1: Write a SELECT statement to retrieve all distinct customers


Open the project file F:\10774A_Labs\10774A_07_PRJ\10774A_07_PRJ.ssmssln and the T-SQL script 61 - Lab Exercise 2.sql. Ensure that you are connected to the TSQL2012 database. Write a SELECT statement to retrieve distinct values for the custid column from the Sales.Orders table. Filter the results to include only orders placed in February 2008. Execute the written statement and compare the results that you got with the desired results shown in the file 62 - Lab Exercise 2 - Task 1 Result.txt.

X Task 2: Write a SELECT statement to calculate the first and last day of the month
Write a SELECT statement with these columns: Current date and time First date of the current month Last date of the current month

Execute the written statement and compare the results that you got with the recommended result shown in the file 63 - Lab Exercise 2 - Task 2 Result.txt.

X Task 3: Write a SELECT statement to retrieve the orders placed in the last five days of the ordered month
Write a SELECT statement against the Sales.Orders table and retrieve the orderid, custid, and orderdate columns. Filter the results to include only orders placed in the last five days of the order month. Execute the written statement and compare the results that you got with the recommended result shown in the file 64 - Lab Exercise 2 - Task 3 Result.txt.

MCT USE ONLY. STUDENT USE PROHIBITED


7-39

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

X Task 4: Write a SELECT statement to retrieve all distinct products sold in the first 10 weeks of the year 2007

Write a SELECT statement against the Sales.Orders and Sales.OrderDetails tables and retrieve all the distinct values for the productid column. Filter the results to include only orders placed in the first 10 weeks of the year 2007. Execute the written statement and compare the results that you got with the recommended result shown in the file 65 - Lab Exercise 2 - Task 4 Result.txt.

Results: After this exercise, you should know how to use the date and time functions.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-40 Working With SQL Server 2012 Data Types

Exercise 3: Writing Queries That Return Character Data


Scenario

The Marketing department would like to have a more condensed version of a report for when they talk with customers. The marketing staff wants the information that currently exists in two columns displayed in a single column. The main tasks for this exercise are as follows: 1. 2. Write a SELECT statement that concatenates values from different columns.

Write a SELECT statement that returns all the customers, where the first character in the contact name is A through G.

X Task 1: Write a SELECT statement to concatenate two columns


Open the project file F:\10774A_Labs\10774A_07_PRJ\10774A_07_PRJ.ssmssln and the T-SQL script 71 - Lab Exercise 3.sql. Ensure that you are connected to the TSQL2012 database. Write a SELECT statement against the Sales.Customers table and retrieve the contactname and city columns. Concatenate both columns so that the new column looks like this:

Allen, Michael (city: Berlin) Execute the written statement and compare the results that you got with the recommended result shown in the file 72 - Lab Exercise 3 - Task 1 Result.txt.

X Task 2: Add an additional column and treat NULL as an empty string


Copy the T-SQL statement in task 1 and modify it to extend the calculated column with new information from the region column. Treat a NULL in the region column as an empty string for concatenation purposes. When the region is NULL, the modified column should look like this:

Allen, Michael (city: Berlin, region: ) When the region is not NULL, the modified column should look like this Richardson, Shawn (city: Sao Paulo, region: SP) Execute the written statement and compare the results that you got with the recommended result shown in the file 73 - Lab Exercise 3 - Task 2 Result.txt.

X Task 3: Write a SELECT statement to retrieve all customers based on the first character in the contact name
Write a SELECT statement to retrieve the contactname and contacttitle columns from the Sales.Customers table. Return only rows where the first character in the contact name is A through G. Execute the written statement and compare the results that you got with the recommended result shown in the file 74 - Lab Exercise 3 - Task 3 Result.txt. Notice the number of rows returned.

Results: After this exercise, you should have an understanding of how to concatenate character data.

MCT USE ONLY. STUDENT USE PROHIBITED


7-41

BETA COURSEWARE EXPIRES 11/2012

10774A: Querying Microsoft SQL Server 2012

Exercise 4: Writing Queries That Use Character Functions


Scenario

The Marketing department would like to address customers by their first and last names. In the Sales.Customers table, there is only one column named contactname that has both elements separated by a comma. You will have to prepare a report to show the first and last names separately. 1. 2. Write a SELECT statement that uses the SUBSTRING function. Write a SELECT statement that uses the REPLICATE and REPLACE functions.

X Task 1: Write a SELECT statement that uses the SUBSTRING function


Open the project file F:\10774A_Labs\10774A_07_PRJ\10774A_07_PRJ.ssmssln and the T-SQL script 81 - Lab Exercise 4.sql. Ensure that you are connected to the TSQL2012 database. Write a SELECT statement to retrieve the contactname column from the Sales.Customers table. Based on this column, add a calculated column named lastname, which should consist of all the characters before the comma. Execute the written statement and compare the results that you got with the recommended result shown in the file 82 - Lab Exercise 4 - Task 1 Result.txt.

X Task 2: Extend the SUBSTRING function to retrieve the first name

Write a SELECT statement to retrieve the contactname column from the Sales.Customers table and replace the comma in the contact name with an empty string. Based on this column, add a calculated column named firstname, which should consist of all the characters after the comma. Execute the written statement and compare the results that you got with the recommended result shown in the file 83 - Lab Exercise 4 - Task 2 Result.txt.

X Task 3: Write a SELECT statement to change the customer IDs

Write a SELECT statement to retrieve the custid column from the Sales.Customers table. Add a new calculated column to create a string representation of the custid as a fixed-width (6 characters) customer code prefixed with the letter C and leading zeros. For example, the custid value 1 should look like C00001. Execute the written statement and compare the results that you got with the recommended result shown in the file 84 - Lab Exercise 4 - Task 3 Result.txt.

X Task 4 (challenge): Write a SELECT statement to return the number of character occurrences

Write a SELECT statement to retrieve the contactname column from the Sales.Customers table. Add a calculated column, which should count the number of occurrences of the character a inside the contact name. (Hint: Use the string functions REPLACE and LEN.) Order the result from rows with the highest occurrences to lowest. Execute the written statement and compare the results that you got with the recommended result shown in the file 85 - Lab Exercise 4 - Task 4 Result.txt.

Results: After this exercise, you should have an understanding how to use the character functions.

MCT USE ONLY. STUDENT USE PROHIBITED

BETA COURSEWARE EXPIRES 11/2012

7-42 Working With W SQL Server 2012 2 Data Types

Modul le Revie ew

Rev view Questi ions


1. 2. 3. Will SQL Serv ver be able to successfully s im mplicitly conver rt an int data t type to a varch har? What data type is suitable for f storing flag g information, such as TRUE or FALSE? What logical operators are useful for retrieving ranges of date and time values?

Potrebbero piacerti anche