sql querying:advanced (secondscheduletodate.com/images/sql_querying_advanced.pdf · for this...

192
DO NOT DUPLICATE FOR EVALUATION USE ONLY (C) 2017 Logical Operations, Inc. SQL Querying: Advanced (Second Edition) INSTRUCTOR'S EDITION

Upload: others

Post on 26-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SQL Querying:Advanced (SecondEdition)

INSTRUCTOR'S EDITION

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Read Me First! Congratulations on selecting CHOICE courseware! This quick guide will give you access to key instructor resources so you can present the best possible CHOICE learning experience. The CHOICE Instructor’s EditionThis Instructor’s Edition is a crucial tool that provides you with all the course-specific technical and setup information, delivery notes, and instructional material that you need as a training professional to deliver an excellent learning experience to your students.

The CHOICE Facilitator’s GuideBefore presenting this or any CHOICE course, make sure you explore the CHOICE Facilitator’s Guide for critical information about virtual and blended course delivery techniques and the CHOICE instructional philosophy and learning experience. Get access to the CHOICE Facilitator’s Guide through the CHOICE Facilitator’s Course.

The CHOICE Facilitator’s CourseYou can find the CHOICE Facilitator’s Guide and other great resources for delivering Logical Operations courseware products through the free CHOICE Facilitator’s Course. To access the free Facilitator’s Course, simply:

1. Visit www.lo-choice.com 2. Enter access key LCSYB24YEF 3. Download and explore the CHOICE Facilitator’s Guide!

The Logical Operations Instructor CommunityLogical Operations leads a very active online community and resource center where instructors from all over the world share their ideas, interact, and engage with each other. Join the community from the CHOICE Facilitator’s Course, or search www.linkedin.com for the “Logical Operations Instructor Community” group to join the conversation.Again, congratulations on your choice—the right choice—the Logical CHOICE!

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.SQL Querying:Advanced

(Second Edition)

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SQL Querying: Advanced (SecondEdition)Part Number: 094019Course Edition: 1.0

AcknowledgementsPROJECT TEAM

Authors Media Designer Content Editor

Rozanne WhalenBrian S. Wilson

Alex Tong Peter Bauer

Logical Operations wishes to thank the Logical Operations Instructor Community, and in particular Sally Howard and GaryLeenhouts, for their instructional and technical expertise during the creation of this course.

NoticesDISCLAIMERWhile Logical Operations, Inc. takes care to ensure the accuracy and quality of these materials, we cannot guarantee theiraccuracy, and all materials are provided without any warranty whatsoever, including, but not limited to, the implied warranties ofmerchantability or fitness for a particular purpose. The name used in the data files for this course is that of a fictitious company. Anyresemblance to current or future companies is purely coincidental. We do not believe we have used anyone's name in creating thiscourse, but if we have, please notify us and we will change the name in the next revision of the course. Logical Operations is anindependent provider of integrated training solutions for individuals, businesses, educational institutions, and government agencies.The use of screenshots, photographs of another entity's products, or another entity's product name or service in this book is foreditorial purposes only. No such use should be construed to imply sponsorship or endorsement of the book by nor any affiliation ofsuch entity with Logical Operations. This courseware may contain links to sites on the Internet that are owned and operated by thirdparties (the "External Sites"). Logical Operations is not responsible for the availability of, or the content located on or through, anyExternal Site. Please contact Logical Operations if you have any concerns regarding such links or External Sites.

TRADEMARK NOTICESLogical Operations and the Logical Operations logo are trademarks of Logical Operations, Inc. and its affiliates.Microsoft® SQL Server® 2017 and Microsoft® SQL Server® Management Studio 2017 are registered trademarks of Microsoft®Corporation in the U.S. and other countries; the SQL Server 2017 products and services discussed or described may be trademarksof Microsoft® Corporation.All other product names and services used throughout this course may be common law or registered trademarks of their respectiveproprietors.Copyright © 2017 Logical Operations, Inc. All rights reserved. Screenshots used for illustrative purposes are the property of thesoftware proprietor. This publication, or any part thereof, may not be reproduced or transmitted in any form or by any means,electronic or mechanical, including photocopying, recording, storage in an information retrieval system, or otherwise, withoutexpress written permission of Logical Operations, 3535 Winton Place, Rochester, NY 14623, 1-800-456-4677 in the United Statesand Canada, 1-585-350-7000 in all other countries. Logical Operations’ World Wide Web site is located atwww.logicaloperations.com.This book conveys no rights in the software or other products about which it was written; all use or licensing of such software orother products is the responsibility of the user according to terms and conditions of the owner. Do not make illegal copies of books

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

or software. If you believe that this book, related materials, or any other Logical Operations materials are being reproduced or transmittedwithout permission, please call 1-800-456-4677 in the United States and Canada, 1-585-350-7000 in all other countries.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SQL Querying: Advanced(Second Edition)

Lesson 1: Using Nested Queries......................................1Topic A: Search Based on Values from a Subquery.......................... 2Topic B: Compare Values from a Subquery................................... 11Topic C: Search Based on the Existence of Records.......................17Topic D: Generate Output Using Correlated Subqueries................ 24Topic E: Filter Grouped Data Within Subqueries............................ 32Topic F: Perform Multiple-Level Subqueries..................................37

Lesson 2: Manipulating Table Data............................... 43Topic A: Insert Rows.....................................................................44Topic B: Modify and Delete Data...................................................52

Lesson 3: Manipulating Table Structure........................ 61Topic A: Create a Table................................................................ 62Topic B: Create a Table with Constraints.......................................70Topic C: Modify a Table's Structure...............................................81Topic D: Delete Tables................................................................. 89

Lesson 4: Working with Views.......................................93Topic A: Create a View................................................................. 94

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Topic B: Manipulate Data in Views........................................................ 104Topic C: Modify and Delete Views.........................................................110

Lesson 5: Indexing Data..................................................... 117Topic A: Create Indexes....................................................................... 118Topic B: Drop Indexes.......................................................................... 127

Lesson 6: Managing Transactions....................................... 131Topic A: Define Transactions................................................................132Topic B: Commit Transactions.............................................................. 144

Appendix A: The Pub2 Database.........................................................151Mastery Builders................................................................................. 155Glossary............................................................................................. 165Index..................................................................................................169

| SQL Querying: Advanced (Second Edition) |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Using the SQL Querying:Advanced (SecondEdition) Instructor'sEdition

Welcome to the InstructorWelcome and congratulations on your choice to use the finest materials available on themarket today for expert-facilitated learning in any presentation modality. You can utilize theSQL Querying: Advanced (Second Edition) curriculum to present world-class instructionalexperiences whether:• Your students are participating with you in the classroom or virtually.• You are presenting in a continuous event or in an extended teaching plan, such as an

academic semester.• Your presentation takes place synchronously with the students or asynchronously.• Your students have physical courseware or are using digital materials.• You have any combination of these instructional dimensions.To make the best use of the SQL Querying: Advanced (Second Edition) materials in any or all ofthese dimensions, be sure to review the contents of the CHOICE Facilitator's Guide for anorientation to all of the components of the CHOICE experience.

Preparing to Present the CHOICE ExperienceEffectively presenting the information and skills in this course requires adequate preparationin any presentation modality. As such, as an instructor, you should familiarize yourself withthe content of the entire course, including its organization and instructional approaches.You should review each of the student activities, exercises, and Mastery Builders so you canfacilitate them during the learning event. Also, make sure you review the tips for presentingin the different dimensions; these instructor tips are available as notes in the margins of yourInstructor's Edition.In addition to the curriculum itself, Microsoft® PowerPoint® slides, data files, and othercourse-specific support material may be available by downloading the files from theCHOICE Course screen. Be sure to obtain the course files prior to your learning event andmake sure you distribute them to your students.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Course Facilitator IconsThroughout the Instructor’s Edition, you may see various instructor-focused icons that providesuggestions, answers to problems, and supplemental information for you, the instructor.

Icon Description

A display slide note provides a prompt to the instructor to display a specific slidefrom the provided PowerPoint files.

Content delivery tips provide guidance for specific delivery techniques you maywant to utilize at particular points in the course, such as lectures, whiteboardsketching, or performing your own demonstrations for the class.

Managing learning interactions provide suggested places to interact with the classas a whole. You might poll the class with closed-ended questions, checkcomprehension with open-ended questions, conduct planned discussion activities,or take notes and questions from the group to "park" and address at a later point inthe class.

Monitoring learner progress notes suggest when you might want to monitorindividual students as they perform activities, or have private sidebar conversationswith specific individual participants.

Engaging learners notes suggest opportunities to involve the students in activeways with the course presentation, such as enabling them to demonstrate their workto the class as a whole, or checking in on the logistics of the presentation.

Incorporating other assets notes suggest when and how to include other types ofmedia, such as visiting CHOICE social media sites, accessing specific web resources,or utilizing media assets provided with the course, such as Logical Operations'Spotlights.

Digital Software UpdatesThe software vendor may at any time deploy software updates digitally, resulting in changes thatmay not be reflected dynamically in this course. Stay up to date with product updates and be readyto adapt the material to any changes in the user interface.

Course-Specific Technical RequirementsHardwareFor this course, you will need one computer for each student and one for the instructor. Eachcomputer will need the following minimum hardware configurations:• 2 GHz or faster 64-bit (x64) processor• 4 gigabytes (GB) RAM• 40 GB available hard disk space• CD-ROM drive (if installing any software from a CD-ROM)• Keyboard and mouse (or other pointing device)• 1024 x 768 (or higher) resolution monitor recommended• Network cards and cabling for local network access• Internet access (contact your local network administrator)• Printer (optional) or an installed printer driver• Projection system to display the instructor's computer screen

| SQL Querying: Advanced (Second Edition) |

| Using the SQL Querying: Advanced (Second Edition) Instructor's Edition |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SoftwareTo prepare a student or instructor system for the class, install the following software according tothe instructions provided. You will need the following software for each student and instructorcomputer:• Microsoft® Windows® 10 64-bit with sufficient licenses.

Windows 10 requires activation unless you have volume-licensing agreements. There is a graceperiod for activation. If the duration of your class will exceed the activation grace period (forexample, if you are teaching the class over the course of an academic semester), you shouldactivate the installations at some point before the grace period expires. Otherwise, the operatingsystem may stop working before the class ends.

• Microsoft® SQL Server® 2017 Express. (When this course was written, the installation file forthis free software was available for download from https://www.microsoft.com/en-us/sql-server/sql-server-downloads.)

• Microsoft® SQL Server® Management Studio (SSMS). (When this course was written, theinstallation file for this free software was available for download from https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms.)

Setting Up the CourseNote: This course is often delivered immediately following SQL Querying: Fundamentals (SecondEdition) (094018). These two courses are often taught as a two-day series. The softwarerequirements for these two courses are identical, so you can set the computers up before the firstday, including the data files for both courses, which are installed in separate folders.• If you plan to teach both courses as a two-day series, refer to the setup instructions in SQL

Querying: Fundamentals (Second Edition).• If you plan to teach only this course, then follow the setup instructions below.

For each student and the instructor:1. Prepare a Windows 10 computer.

a. Install Microsoft Windows 10 with a local administrator account. You will need to providethe student or instructor using the computer with a local administrator account, so create aseparate user account for that purpose if you do not want to provide them with the mainadministrator account on the computer.

b. Download and install any available Windows updates.c. Restart the computer and log in using the local administrator account.

2. Change how Windows updates are delivered to avoid Windows updates during the class.a. Select the Start button.b. Select Settings.c. Select Update & Security.d. In the Update settings group, select Advanced options.e. Select the Delivery Optimization link.

Note: If you are using a version of Windows prior to the 2017 Fall Creator's Update,select the Choose how updates are delivered link, and slide the toggle to Off.

f. Select the option to Allow downloads from other PCs.g. Close the Settings app.

3. Ensure Windows 10 displays file extensions and hidden items.a. Open File Explorer.b. On the ribbon, select the View tab.c. On the ribbon, in the Show/hide group, check the File name extensions and Hidden

items check boxes.d. Close File Explorer.

| SQL Querying: Advanced (Second Edition) |

| Using the SQL Querying: Advanced (Second Edition) Instructor's Edition |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

4. Install SQL Server 2017 Express.a. Download SQL Server 2017 Express from the Microsoft website.b. Right-click the installation file for SQL Server 2017 Express that you just downloaded from

the Microsoft website, and select Run as administrator.c. If you are prompted by the User Account Control message box to allow the installation of

SQL Server 2017 Express Edition, select Yes.d. In the SQL Server 2017 Express Edition dialog box, select the Basic installation option.e. Select Accept to accept the license terms.f. When prompted for the install location, select Install to use the default location.g. When the installer shows the message Installation has completed successfully!, select

Close, and select Yes to confirm.h. Restart the computer, and log back in to Windows with the local administrator account.

5. Install SQL Server Management Studio.a. Download Microsoft SQL Server Management Studio (SSMS) from the Microsoft

website.b. Right-click the installation file for SQL Server Management Studio that you just downloaded

from the Microsoft website, and select Run As Administrator.c. If you are prompted by the User Account Control message box to allow the installation of

SQL Server Management Studio, select Yes.d. At the Welcome page, select Install.e. When installation completes, select Close.

6. Install the course data files.a. From the course Files tile on CHOICE, download the 094019Files<ver>.zip file to any

location that is convenient for you.

Note: The default download folder will vary depending on your browser version andlocal settings.

b. Go to the download folder and locate and unzip (extract) the 094019Files<ver>.zip file.This will create a local 094019Files<ver> folder. It contains separate subfolders with yourcourse overheads and the course data files.

c. Open the 094019Files<ver> folder.d. Move or copy the 094019Data folder to the root of your C drive. This installs the data files to

the location specified in the course activities.

Note: If you prefer to place the data files in a different location, simply inform yourstudents that they will be accessing the files from that alternate path.

The data files folder contains all the lesson-specific subfolders and data files you will need to runthis course. There is a separate folder with the starter files for each lesson or Mastery Builder,and there may be a Solutions folder with completed files students can use to check their results.

7. Connect to the database server in SQL Server Management Studio.a. Use the student login account to log in to Windows.b. Show the Windows Start menu. Locate the SQL Server Management Studio tile. Right

click the tile, select More, and select Run as administrator.c. In the Connect to Server dialog box, in the Server type drop-down list, verify that

Database Engine is selected.d. In the Server name drop-down list, select the down arrow, and select <Browse for

more...>.e. Before Database Engine, select + to expand the list, showing available database engines.f. Select the database engine identified by the computer's name followed by SQLEXPRESS,

and select OK.g. In the Authentication drop-down list, make sure that Windows Authentication is selected.

| SQL Querying: Advanced (Second Edition) |

| Using the SQL Querying: Advanced (Second Edition) Instructor's Edition |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

h. Select Connect to connect to the server.8. Attach the Pub2 database provided in the course setup files.

a. In the Object Explorer pane (left side of the application), make sure the top icon isexpanded so you can see the Databases folder. Right-click the Databases folder, and selectAttach.

b. Select Add.c. In the left pane, select the C:\094019Data folder. You may need to scroll and expand folders

in order to see this folder.d. In the right pane, select Pub2.mdf.e. Select OK to return to the Attach Databases dialog box.f. Select OK to return to the main window of the SQL Server Management Studio.g. In the Object Explorer pane, expand the Databases folder and verify that the Pub2 database

is shown.9. Select File→Exit to exit SQL Server Management Studio.

Presentation PlannersThe lesson durations given in the course content are estimates based on a typical class experience.The following planners show examples of how the content could be presented in either acontinuous flow or separately across a multi-session seminar series. Your presentation flow may varybased on a number of factors, including the size of the class, whether students are in specialized jobroles, whether you plan to incorporate Spotlights or other assets from the CHOICE Course screeninto the course, and so on. Use the samples and blank planners to determine how you will conductthe class to meet the needs of your own situation.Continuous Presentation: Model Class FlowThis planner provides a sample presentation flow based on one 7.5-hour day of training with breaksand lunch factored in.

Section Duration Day Planner

Welcome and Introductions 0:30 8:30 - 9:00

Lesson 1: Using Nested Queries 1:25 9:00 - 10:25

BREAK 0:15 10:25 - 10:40

Lesson 2: Manipulating Table Data 0:50 10:40 - 11:30

Lesson 3: Manipulating Table Structure 0:50 11:30 - 12:20

LUNCH 0:30 12:20 - 12:50

Lesson 3: Manipulating Table Structure (Cont.) 0:50 12:50 - 1:40

Lesson 4: Working with Views 0:40 1:40 - 2:20

BREAK 0:15 2:20 - 2:35

Lesson 4: Working with Views (Cont.) 0:30 2:35 - 3:05

Lesson 5: Indexing Data 0:30 3:05 - 3:35

Lesson 6: Managing Transactions 0:25 3:35 - 4:00

Continuous Presentation: Your Class Flow

| SQL Querying: Advanced (Second Edition) |

| Using the SQL Querying: Advanced (Second Edition) Instructor's Edition |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Use this planner to plan the flow of your own training day based on the needs of your students, theschedule for your own day, and/or any other modifications you choose.

Section Duration Day Planner

Welcome and Introductions

Lesson 1: Using Nested Queries

Lesson 2: Manipulating Table Data

Lesson 3: Manipulating Table Structure

Lesson 4: Working with Views

Lesson 5: Indexing Data

Lesson 6: Managing Transactions

Non-continuous Presentation: Model Class FlowThis planner provides a sample presentation flow based on separate sessions presented overmultiple days or weeks.

Session Number Material Covered Session Duration

One Welcome and IntroductionsLesson 1: Using Nested Queries

1:55

Two Lesson 2: Manipulating Table DataLesson 3: Manipulating Table Structure

2:30

Three Lesson 4: Working with Views 1:10

Four Lesson 5: Indexing DataLesson 6: Managing Transactions

0:55

Non-continuous Presentation: Your Class Flow

| SQL Querying: Advanced (Second Edition) |

| Using the SQL Querying: Advanced (Second Edition) Instructor's Edition |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Use this planner to plan how you will present the course content based on the needs of yourstudents, your conventions for the number and length of sessions, and any other modifications youchoose.

Session Number Material Covered Session Duration

| SQL Querying: Advanced (Second Edition) |

| Using the SQL Querying: Advanced (Second Edition) Instructor's Edition |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

About This Course

In today's competitive environment, information is one of the most important factors indetermining the success of an organization. If you are able to manage and retrieveinformation efficiently, you can streamline the organization's processes and give it acompetitive edge. Some data analysis tasks may require that you query multiple tablessimultaneously or create complex views of data.In the course SQL Querying: Fundamentals (Second Edition), you learned the basics of SQLquerying. In this course, you will build on this foundation, learning advanced queryingtechniques, such as writing nested queries, using JOINs to combine data from multipletables, summarizing query results, using advanced filtering, and using views to simplifyrepetitive querying tasks. You will also learn how to perform common databaseadministration tasks such as duplicating tables, modifying table structures, inserting,updating, or deleting data, and indexing tables to optimize query performance. You will alsolearn how to work with multiple tasks as a transaction.

Course DescriptionTarget StudentStudents should have basic computer skills and SQL skills, and be familiar with conceptsrelated to database structure and terminology.

Course PrerequisitesTo ensure your success, we recommend you first take the following Logical Operationscourses, or have equivalent skills and knowledge:• SQL Querying: Fundamentals (Second Edition)

Course ObjectivesIn this course, you will work with advanced queries to manipulate and index tables. You willalso create transactions so that you can choose to save or cancel the data entry process.You will:• Use nested queries to generate query output.• Manipulate table data by inserting and updating records in a table and deleting records

from a table.• Manipulate table structure.• Create views, manipulate data through views, modify the view structure, and drop views.• Create indexes on table columns and drop inefficient indexes.• Mark the beginning of a transaction, roll back a transaction, and commit a transaction.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

The CHOICE Home ScreenLogon and access information for your CHOICE environment will be provided with your classexperience. The CHOICE platform is your entry point to the CHOICE learning experience, ofwhich this course manual is only one part.On the CHOICE Home screen, you can access the CHOICE Course screens for your specificcourses. Visit the CHOICE Course screen both during and after class to make use of the world ofsupport and instructional resources that make up the CHOICE experience.Each CHOICE Course screen will give you access to the following resources:• Classroom: A link to your training provider's classroom environment.• eBook: An interactive electronic version of the printed book for your course.• Files: Any course files available to download.• Checklists: Step-by-step procedures and general guidelines you can use as a reference during

and after class.• Spotlights: Brief animated videos that enhance and extend the classroom learning experience.• Assessment: A course assessment for your self-assessment of the course content.• Social media resources that enable you to collaborate with others in the learning community

using professional communications sites such as LinkedIn or microblogging tools such asTwitter.

Depending on the nature of your course and the components chosen by your learning provider, theCHOICE Course screen may also include access to elements such as:• LogicalLABS, a virtual technical environment for your course.• Various partner resources related to the courseware.• Related certifications or credentials.• A link to your training provider's website.• Notices from the CHOICE administrator.• Newsletters and other communications from your learning provider.• Mentoring services.Visit your CHOICE Home screen often to connect, communicate, and extend your learningexperience!

How to Use This BookAs You LearnThis book is divided into lessons and topics, covering a subject or a set of related subjects. In mostcases, lessons are arranged in order of increasing proficiency.The results-oriented topics include relevant and supporting information you need to master thecontent. Each topic has various types of activities designed to enable you to solidify yourunderstanding of the informational material presented in the course. Information is provided forreference and reflection to facilitate understanding and practice.Data files for various activities as well as other supporting files for the course are available bydownload from the CHOICE Course screen. In addition to sample data for the course exercises, thecourse files may contain media components to enhance your learning and additional referencematerials for use both during and after the course.Checklists of procedures and guidelines can be used during class and as after-class references whenyou're back on the job and need to refresh your understanding.At the back of the book, you will find a glossary of the definitions of the terms and concepts usedthroughout the course. You will also find an index to assist in locating information within theinstructional components of the book. In many electronic versions of the book, you can click linkson key words in the content to move to the associated glossary definition, and on page references in

| SQL Querying: Advanced (Second Edition) |

| About This Course |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

the index to move to that term in the content. To return to the previous location in the documentafter clicking a link, use the appropriate functionality in your PDF viewing software.

As You ReviewAny method of instruction is only as effective as the time and effort you, the student, are willing toinvest in it. In addition, some of the information that you learn in class may not be important to youimmediately, but it may become important later. For this reason, we encourage you to spend sometime reviewing the content of the course after your time in the classroom.

As a ReferenceThe organization and layout of this book make it an easy-to-use resource for future reference.Taking advantage of the glossary, index, and table of contents, you can use this book as a firstsource of definitions, background information, and summaries.

Course IconsWatch throughout the material for the following visual cues.

Icon Description

A Note provides additional information, guidance, or hints about a topic or task.

A Caution note makes you aware of places where you need to be particularly carefulwith your actions, settings, or decisions so that you can be sure to get the desiredresults of an activity or task.

Spotlight notes show you where an associated Spotlight is particularly relevant tothe content. Access Spotlights from your CHOICE Course screen.

Checklists provide job aids you can use after class as a reference to perform skillsback on the job. Access checklists from your CHOICE Course screen.

Social notes remind you to check your CHOICE Course screen for opportunities tointeract with the CHOICE community using social media.

| SQL Querying: Advanced (Second Edition) |

| About This Course |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Using Nested QueriesLesson Time: 1 hour, 25 minutes

IntroductionYou have performed some fairly complex queries using a basic SELECT statement.However, SQL provides advanced capabilities that enable you to take your queries further.In this course, you will use these advanced capabilities to build on the fundamentals of SQLquerying. You will start by performing various sorts of nested queries.

Lesson ObjectivesIn this lesson, you will use nested queries to generate query output. You will:

• Use nested queries to search based on values obtained from a subquery.

• Compare data values with values obtained from a subquery.

• Search based on the existence of records.

• Generate output by using correlated subqueries.

• Filter grouped data within subqueries.

• Perform multiple-level subqueries.

1

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC ASearch Based on Values from a SubqueryYou have used WHERE clauses to search for specific rows in tables. On occasion, however, you mightneed to search for rows when you don't have a specific search value. Instead, you want to search atable based on values that are provided in another table. To accomplish this type of search, youmust use nested queries.

Nested QueriesWhen you write a query, you specify various data sources to use as inputs. For example, in the clauseFROM Titles, you specify that your query will use data in the Titles table as its initial input. Youmight also provide a WHERE clause to specify a filter, such as a maximum value. For example, theWHERE slprice < 100 clause limits returned rows to those with a slprice value less than 100.Within a query, you can specify the output of another query to use in place of these inputs. Forexample, you might nest a query in the SELECT clause to specify a column. You might nest anotherquery inside your FROM clause to provide the initial input, as though it were a table. You could alsonest a query inside your WHERE clause to provide a filtering value (instead of a hard-coded 100 value,for example).The query contained within the other query is called the inner query or subquery. The query thatcontains the inner query, as you might guess, is called the outer query. It is sometimes called themain query.Subqueries are always written within parentheses, and in turn can contain their own inner queries,with each inner query enclosed within parentheses. You can sort and group records retrieved by asubquery. If an inner query returns a null value, then the outer query also returns a null value.

Figure 1-1: A nested query example.

2 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic A

Nested Query

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

This example displays any books that have sold in a higher than average quantity. It uses a nestedquery to compute the average quantity, and returns the value to the outer query. The WHERE clause inthe outer query then filters rows coming from the Sales table to return only those rows where thequantity is greater than average.

The IN OperatorIn a WHERE clause, you can use the IN operator to determine whether a value is included within aparticular list. The list is typically provided by a subquery nested within the WHERE clause.The IN operator:• Is preceded by the value you're looking for, which can be a column name or constant value• Is followed by the list of values, which can be provided by a subquery• Can be used with the NOT operator to search for records that are not present in the list of values

Figure 1-2: An IN operator example.

This main query displays rows for those customers who have purchased books. The subqueryreturns a list of customer numbers present in the Sales table, meaning that the customers have madeat least one purchase. The main query uses the IN operator to search within this list to verifywhether the customer number in the Customers table is present in the list returned by the subquery.

Note: When a subquery returns NULL values and the main query has the IN operator in thesearch condition, it will result in an UNKNOWN value, thus producing an unpredictable result.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Search Based on Values from a Subquery.

SQL Querying: Advanced (Second Edition) | 3

Lesson 1: Using Nested Queries | Topic A

The IN Operator

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 1-1Searching Based on a Single-Row SubqueryResult

ScenarioYou work for the Fuller & Ackerman Publishing company. You maintain the SQL database namedPub2. You've been asked to produce a list of sales representatives who have been earning acommission at rates above the average rate for the team.

Note: For information on the tables and column names in the Pub2 database, refer to the tablestructure in Appendix A.

Note: Activities may vary slightly if the software vendor has issued digital updates. Yourinstructor will notify you of any changes.

1. Launch Microsoft® SQL Server® Management Studio and connect to thedatabase server.a) On the Start screen, select SQL Server Management Studio.

b) In the Connect to Server dialog box, in the Server type drop-down list, verify that Database Engine is

selected.c) In the Server name drop-down list, verify that the name of the server is automatically selected. In

this case, the server name is the same as your computer's name, followed by SQLEXPRESS.

4 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic A

Activity: SearchingBased on a Single-RowSubquery Result

Notify students of anychanges to activitiesbased on digital softwareupdates issued by thesoftware vendor.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

d) In the Authentication drop-down list, verify that Windows Authentication is selected.

e) Select Connect to connect to the server.

2. Examine the Pub2 database.a) In the Object Explorer pane (left side of the application), make sure the database icon is expanded

so you can see the Databases folder. Make sure the Databases folder is expanded as well.

You will use the Pub2 database in this course.

3. Write a simple query to show all data in the Slspers table.a) On the Standard toolbar, select New Query to open the Query Editor window.

SQL Querying: Advanced (Second Edition) | 5

Lesson 1: Using Nested Queries | Topic A

Point out that the Pub1database may not bepresent, depending onwhether this course isbeing delivered on thesame computer rightafter the SQL QueryingFundamentals course.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) On the SQL Editor toolbar, from the Available Databases drop-down list, select Pub2.

Other databases are present on the server. You need to specify the database so SQL Server cansend your queries to the right database.

c) Enter the query as shown.

d) Execute the query.

(In SQL Server Management Studio, you can execute a query by selecting Execute from the ribbon,or by pressing F5.)

The Slspers table includes four columns, with 10 rows of data.

4. Return just repid, fname, lname, and commrate columns for representativeswho earn a commission rate that is above the average rate for the team.

6 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic A

SQL code snippets forthe course activities arestored as snippets.sql inthe Solutions folder foreach lesson's coursedata. You can use theseto save yourself sometyping as you leadstudents through theactivities. Or you maywant to direct studentsto these files if they arehaving trouble keepingup with the typing inclass.

Point out that studentsshould not be concernedif the titles in their tabsand windows differ fromthose shown in thescreen images.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Revise the SELECT clause as shown.

b) Add a WHERE clause as shown.

From a quick scan of commrate values, you might guess that the average rate is somewherebetween 3 and 4%.

c) Execute the query.

• Sales representatives whose commission rate is more than 3% are returned.• While this query functions acceptably, it requires that you manually determine the cutoff point,

and it will not automatically adjust the cutoff point if the average changes over time.

5. Revise the query so the average commission is used as the cutoff point,rather than a hard-coded value.a) In the WHERE clause, select .03.b) Press Enter and Tab to start a new, indented line.c) Write a nested query to return the average commission rate.

6. Test the inner query.

SQL Querying: Advanced (Second Edition) | 7

Lesson 1: Using Nested Queries | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Highlight just the inner query, as shown.

b) Press F5.

• When you highlight a portion of SQL in the query editor and execute the query, SQL Server

Management Studio executes only the highlighted portion.• The inner query returns the value 0.037.• This value will be passed to the outer query's WHERE clause as the cutoff value for commrate.

7. Test the outer query.a) Press End to move to the end of the line, so the inner query is no longer highlighted.

With just an insertion point (and no portion of SQL highlighted), the entire statement will nowexecute.

b) Execute the query.

All sales representatives with a commission higher than the calculated average are shown.

8 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 1-2Searching Based on a Multiple-Row SubqueryResult

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioThe sales manager wants you to identify book titles that have not sold any copies at all. These will bebooks in the Titles table (all books currently offered) whose part numbers do not appear at leastonce within the Sales table.

Generate the list of books that have never been sold.a) Clear the old query, and enter a new query as shown.

b) Execute the query.

All books in the Titles table are listed, with their part number (partnum column) and book title(bktitle).

SQL Querying: Advanced (Second Edition) | 9

Lesson 1: Using Nested Queries | Topic A

Activity: SearchingBased on a Multiple-Row Subquery Result

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Add a WHERE clause to select books whose part number is not listed in the Sales table.

d) Highlight the inner query, and execute the query.

• A single-column list of part numbers is returned.• There are 98 rows in the result.• The result is a list of part numbers that appear within the Sales table, so these are books that

have sold.• The NOT IN operator within the outer query's WHERE clause will return only books that are not

in this list—in other words, books that have not sold.e) Press End to move to the end of the line, so the inner query is no longer highlighted.f) Execute the query.

Books that have not sold are listed. The status bar shows that there are 37 of them.

10 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC BCompare Values from a SubqueryYou have retrieved records based on values obtained from a subquery. Sometimes, you might needto write queries that compare a single value with a list of values obtained from a subquery.

Modified Comparison OperatorsA modified comparison operator functions differently when you combine it with the ANY or ALLlogical operator.Use modified comparison operators in the WHERE clause of an outer query to compare a single valuewith a list of values generated by a subquery, as shown in the following example.

Figure 1-3: A modified comparison operator example.

In this example, the subquery returns a list of devcost values from every row in Obsolete_Tables.The main query's WHERE clause uses this list to find rows in the Titles table where the devcostvalue is less than all of the devcost values returned by the subquery.

Note: You can use the ANY and ALL operators only with comparison operators.

Comparison Operators Used with ANY and ALLThe combination of the comparison operator and the ANY and ALL operators determines thecomparison performed in the condition of an outer query. The following table explains variousoperator combinations.

SQL Querying: Advanced (Second Edition) | 11

Lesson 1: Using Nested Queries | Topic B

Modified ComparisonOperators

Comparison OperatorsUsed with ANY and ALL

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Operator Combination Description

> ANY Greater than the minimum value in a list.

>= ANY!< ANY

Greater than or equal to the minimum value in a list.

< ALL Less than the minimum value in a list.

<= ALL!> ALL

Less than or equal to the minimum value in a list.

< ANY Less than the maximum value in a list.

<= ANY!> ANY

Less than or equal to the maximum value in a list.

> ALL Greater than the maximum value in a list.

>= ALL!< ALL

Greater than or equal to the maximum value in a list.

= ANY Equal to any value in a list.

= ALL Equal to all values in a list.

<> ANY!= ANY

Not equal to any of the values in a list.

<> ALL!= ALL

Not equal to all the values in a list.

Note: Note that the various operators with the exclamation point are not specified in the ANSIstandard, although they are recognized by many database servers.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Compare a Value with Unknown Values.

12 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 1-3Searching by Comparing Values from aSubquery

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioThere has been some discussion within Fuller & Ackerman Publishing about the increasing costs ofdeveloping a book. To prepare for an upcoming meeting, the production manager would like toanalyze the profitability of books currently in print that were actually inexpensive to develop.You have a list of books currently in print (from the Titles table), as well as a list of books no longerin print (from the Obsolete_Titles table).You need to extract a list of books currently in print that actually cost less to develop than any ofthe books that are no longer in print.

1. Compare data in the Titles and Obsolete_Titles tables.a) Delete the query currently in the query editor, and type the two queries shown here.

SQL Querying: Advanced (Second Edition) | 13

Lesson 1: Using Nested Queries | Topic B

Activity: Searching byComparing Values froma Subquery

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Execute the queries.The queries produce two tables in the Results pane.

c) Scroll as necessary to view the rows in both tables, and observe the following.

• In the top table (Obsolete_Titles):• 7 out-of-print titles are listed• The lowest development cost for an obsolete title is 9000 (for Learning to Diet)

• In the bottom table (Titles):• 92 currently-in-print titles are listed• The development cost is not specified (NULL) for the first 5 titles currently in print• Conversational Chinese apparently cost nothing to develop• Numerous other current titles cost less than 9000 to develop, so your completed query

should produce some results

2. Revise the second query to return only the books from Titles whosedevelopment cost is less than the development cost of each book containedin Obsolete_Titles.

14 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Insert a WHERE clause in the second query as shown.

3. Test the inner query.a) Select the inner query as shown.

b) Execute the query, and examine the results.

Development costs for the out-of-print books are listed in a single column. This will serve as theinput for the < ALL operator in the main query's WHERE clause.

4. Test the outer query.a) Press End to deselect the inner query.

SQL Querying: Advanced (Second Edition) | 15

Lesson 1: Using Nested Queries | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Press F5 to execute the two queries, and examine the results.

• 15 books are included in the result of the new query.• The 15 books each cost less to develop than the least expensive obsolete title (each less than

9000).• The titles with a NULL devcost were not included in the result, although one title (Conversational

Chinese) had a devcost of 0.00.

16 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC CSearch Based on the Existence of RecordsIn the previous topics, you queried tables by using subqueries to retrieve the values for your searchconditions. On occasion, you might need to display rows from a table based on the existence of oneor more rows in another table.

The EXISTS OperatorThe EXISTS operator is a logical operator that you use in the WHERE clause of an outer query tocheck for the existence of records returned by a subquery.

Figure 1-4: An EXISTS operator example.

As this example shows, you can use the EXISTS operator in the main query's WHERE clause todetermine which rows should be returned in the results.In the main query of this example, the database server works through each row of the Titles table(SELECT * FROM Titles).The WHERE clause is evaluated as the server examines each row in the Titles table. It performs thesubquery, using the value of partnum for the row it is currently evaluating in the Titles table.If the Titles.partnum value doesn't exist within Obsolete_Titles, the inner query will return anempty result. Since a result doesn't exist in that case (EXISTS = False), that row won't be returnedby the outer query.If the Titles.partnum value does exist within Obsolete_Titles, the inner query returns a resultcontaining the part number. Since a result exists in that case, that row will be returned by the outerquery.

SQL Querying: Advanced (Second Edition) | 17

Lesson 1: Using Nested Queries | Topic C

The EXISTS Operator

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Note: You cannot use the COMPUTE and the INTO keywords in a query containing the EXISTSoperator.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Search Based on the Existence of Records.

18 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 1-4Searching Based on the Existence of a Record

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioIn preparation for some cleanup work in your database, you need to determine if any of the booksin your current titles (Titles table) are also in the obsolete titles list (Obsolete_Titles). There arevarious ways to accomplish this, but in this activity you'll use the EXISTS operator.

1. Explore how you might determine which books are obsolete.a) Delete the query currently in the query editor, and type the three queries shown here.

Since the three queries start the same way, you might opt to use copy-and-paste to save yourselfsome typing.

SQL Querying: Advanced (Second Edition) | 19

Lesson 1: Using Nested Queries | Topic C

Activity: SearchingBased on the Existenceof a Record

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Execute the three queries, and examine the results.

• The first query provides a list of all part numbers for obsolete books.• The second query returns a single row showing the part number specified in the WHERE clause.• The third query returns an empty result, since the part number specified in the WHERE clause

doesn't exist.

2. Use the query as an inner query to show current titles that exist within the listof obsolete titles.a) Delete the first two queries, so only the third query remains in the editor.

• You will use this as your inner query.• You will wrap an outer query around this to select books from the Titles table.• Since you will use this as your inner query, you need to surround it with parentheses.

b) Surround the inner query with parentheses.

20 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Add three lines before the inner query to form the outer query, and indent the inner query as shown.

d) Revise the inner query to replace the hard-coded part number with the part number for each record

in the Titles table.

• To produce a result, the database server will iterate through each row of the Titles table in the

outer query. For each row, it will execute the inner query, providing the part number from theTitles table row currently being evaluated.

• If the Titles.partnum value exists within Obsolete_Titles, the inner query will return aresult containing that part number. Since the table will exist in that case, that row will be returnedby the outer query.

• If the Titles.partnum value doesn't exist within Obsolete_Titles, the inner query willreturn an empty result. Since the table won't exist in that case, that row won't be returned by theouter query.

Note: When the subquery references a field in the main query (such asTitles.partnum, in this example), it is also known as a correlated subquery.

e) Execute the query.

Two titles are returned. These titles exist in Titles as well as Obsolete_Titles.

3. Verify your results.

SQL Querying: Advanced (Second Edition) | 21

Lesson 1: Using Nested Queries | Topic C

Point out that theindentation is forreadability only. It is notnecessary for the queryto execute properly.

The concept of acorrelated subquery willbe explored in moredepth in the next topic.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Add another query as shown.

b) Execute the query and examine the results.

• The top table shows the results of your query, which should list books that are included in both

the Titles and Obsolete_Titles tables.• At first glance, it appears that the Developing Mobile Apps book is not in both tables. However,

its partnum value (39905) does appear in both tables, and partnum is what you used in the queryto look for a match.

• It seems that the part number 39905 was reused from a different book (Y2K Why Worry?).

4. Add another condition to the inner query's WHERE clause.a) Position the insertion point after Titles.partnum as shown.

22 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Press Enter to start a new line, and add another condition to the inner query's WHERE clause asshown.

c) Execute the queries, and examine the results.

Only the Clear Cupboards book is now shown in the top results table.

5. Show books in Titles that do not exist in Obsolete_Titles.a) In the top query, revise the WHERE clause to insert NOT as shown.

b) Execute the queries, and examine the results.

The top query returns 91 records of books in Titles that do not exist in Obsolete_Titles.

SQL Querying: Advanced (Second Edition) | 23

Lesson 1: Using Nested Queries | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC DGenerate Output Using Correlated SubqueriesYou've used subqueries to display records based on unknown search values. Sometimes, based onbusiness requirements, you might want SQL Server to execute the outer query first before executingthe subquery. In this topic, you will use correlated subqueries so that SQL Server executes the outerquery initially, followed by the subquery.

Correlated SubqueriesA correlated subquery is a subquery that SQL Server executes simultaneously with the outer query.An example is shown here.

Figure 1-5: A correlated subquery example.

In this example, the query produces a list of customers who bought 400 copies of a book in a singlepurchase.The outer query's WHERE clause selects which rows will be returned. It refers to a subquery thatproduces a list of sales quantities (from the Sales table) for the representative whose ID andcustomer name match those coming from the current row of the main query. If 400 is in the list thatis returned by the subquery, then the row is considered a match, and will be included in the outputof the main query.Because it references columns of data associated with the main query (Slspers.repid andCustomers.custnum), a separate instance of the subquery must be evaluated for each row's datavalues. The expression correlated subquery is used to describe this situation because a unique instanceof the subquery is created for each row of the main query's data, and data values that correlate tothat row are used within the subquery, as shown in the figure.Because many instances of the subquery may need to be processed (one for each row of data beingprocessed by the outer query), correlated queries may be slow to process in some cases.

24 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic D

Correlated Subqueries

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Note: The value to be searched (such as the 400 value specified in the main query's WHEREclause in this example), must always be a constant value and not a column name.

The APPLY OperatorAPPLY is a relational operator that enables you to apply a table expression to all rows of an outertable. The APPLY operator can be used with multiple tables and can contain a WHERE condition. Theoutput of a query using an APPLY operator is similar to an INNER JOIN where you automaticallyretrieve all columns from both tables, and the table expression could be a table, a view, a derivedtable, or even a function that returns a table.

Figure 1-6: An APPLY operator example.

In this example, SQL Server generates a results set that consists of all columns from the Slsperstable combined with all columns in the Sales table where the sales representative ID (repid) is thesame in both tables.

APPLY Operator and Table-Valued FunctionsThe APPLY operator can be used with a table-valued function, where the function can accept one ormore columns as parameters from a source table. The function uses these parameters to produce atable-valued result set.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Generate Output Using Correlated Subqueries.

SQL Querying: Advanced (Second Edition) | 25

Lesson 1: Using Nested Queries | Topic D

The APPLY Operator

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 1-5Generating Output Using Correlated Subqueries

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioThe sales manager at the Fuller & Ackerman Publishing bookstore has been instructed by topmanagement to encourage high-quantity purchasers to achieve the sales targets for the year. Fromthe data on the sales made in the past, the manager has identified that the maximum quantitypurchased by a customer in a single purchase is 500. The manager wants you to list the contactinformation of customers that have bought 500 books in a single purchase. The manager also wantsyou to add the titles of the books sold. The data required to generate the output is available in theCustomers, Sales, and Titles tables.

1. Determine which columns you will select from the Titles and Customerstables.a) Delete the query currently in the query editor, and type the query shown here.

b) Execute the query and scroll to examine the results.

• You have created a cross product of the two tables, giving you a row for each combination of

book title and customer.• 2300 rows are displayed.• This query currently produces more columns and rows than you need.• You can revise the SELECT clause to choose which columns will be provided in the report.• You can write a WHERE clause to reduce the rows down to only those customer/book

combinations for which the customer bought 500 books in a single purchase.

2. Reduce the number of columns shown in the report.

26 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic D

Activity: GeneratingOutput Using CorrelatedSubqueries

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Revise the SELECT clause as shown.

b) Execute the query.

• 2300 rows are returned in five columns.• These five columns should provide sufficient information for the report.• Now you can focus on reducing the number of rows to show only customers who bought 500

books in a single purchase.

3. Determine how you might get sales quantities for a particular customer/bookcombination.a) Enter a new query below the first query, as shown.

SQL Querying: Advanced (Second Edition) | 27

Lesson 1: Using Nested Queries | Topic D

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Execute the queries, and scroll the bottom table as you examine the results.

• The bottom query produces a list of all (98) sales.• The custnum and partnum columns in the bottom query correspond to the custnum and

partnum columns in the top query.• Several rows in the bottom table show sales quantities (qty) of 500. Each custnum/partnum

combination with a quantity of 500 represents a row that should be returned in your top query.c) In the bottom table, scroll to line 45, and view the data in that row.

Customer number 20181 made a purchase of 500 copies of book 40633.You could use the custnum and partnum columns in a WHERE clause to find the sales numbers fora particular customer/book combination.

d) Add a WHERE clause to the bottom query as shown.

e) Execute the query and examine the results.

• This customer made two purchases of this part number.• One of the purchases was for 200 books, and the other was for 500 books.

28 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic D

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

f) Revise the SELECT clause in the bottom query to output just the qty column.

g) Execute the query and examine the results.

• The qty column provides all the information you need from this query. By checking to see if a 500

value is in the list, you can determine whether this customer/book combination should beincluded in the report.

• Now you can use this in a WHERE clause to filter results in your main query.

4. Use the bottom query as a subquery in the main query's WHERE clause.a) In the blank line between the two queries, start a WHERE clause for your main query as shown.

b) Select the three lines of the subquery, and press Tab to indent the selection.c) Add parentheses around the subquery.

d) Examine the hardcoded values in the subquery.

SQL Querying: Advanced (Second Edition) | 29

Lesson 1: Using Nested Queries | Topic D

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

The customer number is currently hardcoded to 20181, and the part number is hardcoded to 40321.You need to pull these values from the main query, so they will be different for each row.

e) Revise the subquery as shown.

f) Execute the query and examine the results.

Seven rows are displayed. The results list any books that have been purchased in quantities of 500,including the customer that made the purchase.

30 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic D

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 1-6Using APPLY to Combine Data from Two Tables

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioThe sales manager would like a list of all salespeople and the titles they have sold. You will useOUTER APPLY to list all the fields from both tables.

Create an OUTER APPLY query to list all salespeople and the books theyhave sold.a) Delete the query currently in the query editor, and type the query shown here.

This query:• Selects all rows from the Slspers table.• Uses the OUTER APPLY operator to include related records from the Sales table.• Uses repid to provide the relationship between the two tables.

b) Execute the query.

SQL Server returns 98 rows.

SQL Querying: Advanced (Second Edition) | 31

Lesson 1: Using Nested Queries | Topic D

Activity: Using APPLY toCombine Data from TwoTables.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC EFilter Grouped Data Within SubqueriesOn occasion, you might want to group the data returned by a subquery based on specific values. Forexample, you might want a list of all sales grouped by the salesperson responsible for the sales. Inaddition, you might want to use a search condition to filter the rows returned by a groupedsubquery. For example, you might want a list of all sales, grouped by the salesperson responsible forthe sales, and filtered so that you see only those rows where the quantity sold exceeds the averagequantity sold.

The GROUP BY ClauseGROUP BY is a clause you can use to group rows in the output based on the content of one ormore columns. The column(s) you specify in the GROUP BY clause must be included in the SELECTstatement. Add an ORDER BY clause to sort the output so that SQL Server groups the rows properly.

Figure 1-7: A GROUP BY clause example.

In this example, SQL Server groups the rows in the Sales table by sales representative ID. It thencalculates the total quantity of the sales for the group. In other words, this query enables you todetermine the total sales quantity for each sales representative.

The HAVING ClauseYou can use the HAVING clause to specify a search condition based on an aggregate value. (Youshould use a WHERE clause if you want to search based on one of the columns in the SELECTstatement.) You use the HAVING clause with the GROUP BY clause. After SQL Server groups andaggregates the data, it applies the conditions in the HAVING clause. If you don't use the GROUP BYclause in a query, the HAVING clause behaves like a WHERE clause.

32 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic E

The GROUP BY Clause

The HAVING Clause

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Figure 1-8: A HAVING clause example.

In this example, the GROUP BY repid clause groups the output rows based on the salesrepresentative IDs. The SUM(qty) aggregate function in the SELECT statement calculates the totalsales for each sales representative. The HAVING clause then restricts the output to only the salesrepresentatives who have sold a total quantity of 600 or more.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Filter Grouped Data Within Subqueries.

SQL Querying: Advanced (Second Edition) | 33

Lesson 1: Using Nested Queries | Topic E

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 1-7Filtering Grouped Data Within a Subquery

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioThe top management of the Fuller & Ackerman Publishing bookstore chain has asked for a 25percent increase in the sales targets for this quarter. The sales manager of a branch in the store chainhad estimated at the beginning of the quarter that each sales representative needs to sell a minimumof 2,375 books to achieve the targets set by the top management. At the end of the quarter, themanager wants you to list the sales representatives who have met or exceeded the target for thequarter. The Slspers and Sales tables contain the data needed to generate the required output.

1. Remove the OUTER APPLY and WHERE clauses from the query.a) Delete the OUTER APPLY and WHERE clauses from the query as shown.

b) Execute the query, and examine the results.

• All of the sales representatives are listed.• These are the columns you'll return from your main query.• Now you need to filter this list to show only those sales representatives who save sold at least

2,375 books. You can do that through a subquery.

34 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic E

Activity: FilteringGrouped Data Within aSubquery

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

2. Prototype a subquery that lists sales representatives who have sold at least2,375 books.a) Write a second query as shown.

b) Execute the queries, and examine the results.

The bottom query returns a list of reps who should appear in the main query. You can use this list inthe WHERE clause for the main query to filter the rows.

3. Add the subquery to the main query.a) Start the WHERE clause for the main query in the blank line between the two queries, as shown.

b) Indent the subquery and surround it in parentheses.

SQL Querying: Advanced (Second Edition) | 35

Lesson 1: Using Nested Queries | Topic E

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Execute the query, and examine the results.

The list shows the four reps who made the cut, using the Slspers data from the main query.

36 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic E

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC FPerform Multiple-Level SubqueriesYou have nested one query within another to create a subquery. As you might guess, for reportsbased on very complicated analyses, you might need to take this nesting approach a level further,and nest one subquery within another subquery, going on this way for as many levels as needed toaccomplish the task.

Nested SubqueriesA nested subquery is a subquery that contains multiple levels of inner queries. Each inner query ina nested subquery is enclosed within parentheses. The number of closing parentheses at the end ofthe nested subquery must match the number of inner queries contained within the subquery. Anunlimited number of inner queries can be contained within a nested subquery. Nested subqueries areused in situations where an outer query requires the values returned by many levels of subqueries todisplay the required records.

Figure 1-9: A nested subqueries example.

In this example, you want to display the names of books bought by customers living in the city ofRyebrook. The outer query displays the book title and checks for the part number in the outputprovided by the subquery. This subquery generates a list of part numbers based on the customernumbers present in the list returned by its inner query. The second inner query returns a list ofcustomers living in the city of Ryebrook.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Perform Multiple-Level Subqueries.

SQL Querying: Advanced (Second Edition) | 37

Lesson 1: Using Nested Queries | Topic F

Nested Subqueries

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 1-8Generating Output Using Nested Subqueries

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioWith the holiday season fast approaching, the sales manager at the Fuller & Ackerman Publishingbookstore wants to send gifts or discount coupons as incentives to customers. The manager wantsto focus on those customers who have purchased high-priced books, and has determined from theprice list in the store that any book that is priced above $49 can be classified under the high-pricecategory. To mail the incentives, the manager wants you to generate the name and address details ofcustomers who have made high-price purchases. The Customers, Sales, and Titles tables contain thedata needed to generate the required output.

1. Identify the information you will draw from three source tables.a) Delete the query and type three new queries as shown.

38 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic F

Activity: GeneratingOutput Using NestedSubqueries

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Execute the query and examine the results.

• The bottom query lists books that sell for more than $49.• The middle query lists all sales.• The top query lists all customers.• You can use part numbers returned by the bottom query to filter the sales in the middle list so

that the middle query will only show sales for part numbers selling for more than $49.• You can use the customer numbers from the middle query to filter the list of customers produced

in the top query.• By nesting the queries in this way, you can produce a list of all customers who have purchased

any books that sell for more than $49.

2. Nest the queries using WHERE clauses.a) Start adding WHERE clauses to nest the queries as shown.

Nested queries can be a bit confusing to look at. Indentation can help.

SQL Querying: Advanced (Second Edition) | 39

Lesson 1: Using Nested Queries | Topic F

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Select the second and third queries, and press Tab to indent them one level as shown.

c) Select the third query, and press Tab to indent it another level as shown.

3. Close the parentheses.a) Count the opening parentheses in your subqueries.

There are two of them. You need to add the corresponding closing parentheses.b) Add two closing parentheses at the end of the last subquery.

40 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries | Topic F

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Revise the SELECT clauses to extract only the columns needed for the report.

d) Execute the query and examine the result.

e) Close the Query Editor window without saving the query.

SQL Querying: Advanced (Second Edition) | 41

Lesson 1: Using Nested Queries | Topic F

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SummaryUsing subqueries enables you to search for rows when you don't know the value or group of valueson which you want to search. Subqueries help you retrieve complex information from a databasebased on your business needs.

When there are alternative ways to write a query, how can you tell which one willbe most efficient?A: The execution time for each query will vary depending upon the complexity of the query and how the

database server you're using has been configured and optimized. There are certain patterns and bestpractices you can follow for a particular server, but when performance is critical, you should turn onstatistics, and test the query with the actual execution plan.

When should you use a subquery?A: To some extent, the answer depends on the database server you are using. For example, with

Microsoft SQL Server, there is often no performance difference between a statement that includes asubquery and a semantically equivalent statement that does not. However, in some cases, a JOINyields better performance than a subquery. Some database servers may not be optimized the sameway as SQL server, and subqueries may be less efficient than alternatives such as JOIN. As a rule ofthumb, consider using a subquery only when you can't accomplish the task in another way. If you canaccomplish the task using a JOIN rather than a subquery, then the JOIN is likely the better option. Tobe sure, turn on statistics and test performance both ways.

Note: Check your CHOICE Course screen for opportunities to interact with your classmates,peers, and the larger CHOICE online community about the topics covered in this course orother topics you are interested in. From the Course screen you can also access availableresources for a more continuous learning experience.

42 | SQL Querying: Advanced (Second Edition)

Lesson 1: Using Nested Queries |

Encourage students touse the socialnetworking toolsprovided on the CHOICECourse screen to followup with their peers afterthe course is completedfor further discussionand resources to supportcontinued learning.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Manipulating Table DataLesson Time: 50 minutes

IntroductionAlthough database client applications typically provide features within the user interface tomanage content, in many cases you may need to set up database structure and contentbefore you deploy an application. Or you might need to perform maintenance tasks outsidethe client application. Using SQL, you can directly perform such tasks. In this lesson, youwill use SQL to insert, update, and delete rows.

Lesson ObjectivesIn this lesson, you will manipulate table data by inserting and updating records in a table anddeleting records from a table. You will:

• Insert data into a table.

• Modify data and delete the records in a table.

2

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC AInsert RowsAs someone who works with databases, you need to know how to add the necessary information tothe tables in your organization's database. In this topic, you will learn how to insert rows into tables.

The INSERT StatementYou use the INSERT statement to insert a record into a table. By executing the INSERT statementalone, you can insert only one record at a time.

Figure 2-1: Sample code for the INSERT statement.

In this example, the INSERT statement adds a record to the Titles table with a part number of 40895,the title "Mythologies of India," and 0.00 for the development cost.If you want to insert multiple rows into a table, you can use the INSERT statement along with aSELECT clause. Microsoft® SQL Server® populates the table you specify in the SELECT clause of theINSERT statement. The order of the columns specified in the SELECT clause must match the columnorder in the INSERT statement or in the table from which records are retrieved. You can also filterthe records inserted into a table by adding a WHERE clause to the SELECT clause in the INSERTstatement.INSERT tablenameSELECT columnname1, columnname2, columnname3FROM tablenameWHERE search condition

Record Insertion MethodsYou can insert records into tables two different ways using the INSERT statement with the VALUESstatement. The methods of record insertion are detailed in the following table.

Method of RecordInsertion

Description

Inserting all columnvalues

You don't have to specify the column names with the INSERT clause.However, if you don't specify the column names, the order of values youput in the VALUES clause must match the order in which the columns areorganized in the table.

44 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data | Topic A

The INSERT Statement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Method of RecordInsertion

Description

Inserting specificcolumn values

You must specify the required column names after the table name in theINSERT clause. In addition, the order in which you write the values in theVALUES clause must match the order of column names specified with theINSERT clause.

You will have to follow some rules while using the INSERT statement. These rules are detailed in thefollowing table.

Rule Description

Table name You must specify the name of the table targeted for data entry after theINSERT statement.

Values to be stored Specify the values you want to store in the columns with the VALUESclause enclosed within parentheses and separated by commas.

Value-data type match The value you specify for a column must match the column's data typeand size.

Null values If you do not specify a value for a column, SQL Server inserts a nullvalue in the column automatically. If you want to explicitly enter a nullvalue in a column, you need to specify the NULL keyword when providingthe column values in the VALUES clause.

Default values Some columns can accept default values if you do not explicitly specify avalue in the VALUES clause. To populate such a column, you need to usethe DEFAULT keyword in the VALUES clause in the place of a constantvalue.

SQL Querying: Advanced (Second Edition) | 45

Lesson 2: Manipulating Table Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Rule DescriptionSingle quotes The values you specify for columns of certain data types, such as char,

varchar, and datetime, must be enclosed within single quotes.

The OUTPUT ClauseThe OUTPUT clause is a SQL clause that enables you to obtain information from rows that areaffected by the INSERT, UPDATE, DELETE, and MERGE statements. You can use the OUTPUT clauseonly in combination with an INSERT, DELETE, UPDATE, or MERGE statement. The OUTPUT clausereturns data modified using these statements in the form of a table. You might use the resultsgenerated by the OUTPUT clause to send information to an application so that it can display amessage for confirmation or for backing up data.

Figure 2-2: Sample code for the OUTPUT statement.

In the example, the INSERT statement inserts a row into the Titles table with the values for eachcolumn defined in the VALUES clause. In addition, the OUTPUT clause results in SQL Serverdisplaying the row it inserted in the Results pane.You can also use the OUTPUT clause along with a user-defined function to store the output data in anew table. You will have to declare table variables to store these records in the table.

Table Value ConstructorsYou use table value constructors to specify a set of row value expressions you want to insert into atable. In other words, you can use table value constructors to insert multiple rows into a SQL tablewithout having to type multiple INSERT statements. Instead, you use a single VALUES clausefollowed by the values you want to insert into each row enclosed in parentheses and separated bycommas.

46 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data | Topic A

The OUTPUT Clause

Table ValueConstructors

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Figure 2-3: Sample code for using table value constructors.

In this example, the INSERT INTO clause specifies the table in which you want to create the newrows and the columns for which you are going to specify values. The VALUES clause then containsvalues for five new rows, with each row's values enclosed in its own set of parentheses.

Note: To save typing, you can type INSERT rather than INSERT INTO.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Insert Data.

SQL Querying: Advanced (Second Edition) | 47

Lesson 2: Manipulating Table Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 2-1Inserting Data into a Table

Data FileC:\094019Data\Manipulating Table Data\Insert_Record.txt

ScenarioYou are going to perform some content updates on the Titles table. Rather than work directly in thetable, you'll make a copy of the table and make your revisions in the copy. Then you'll add six newtitles to the table, as shown here.

Part Number Book Title DevelopmentCost

Sale Price Date ofPublishing

39906 VC++ Made Easy Null 50 2017-06-01

39907 History of the Internet Null 25 2017-07-01

39908 Flash Tips and Tricks Null 35 2017-08-01

39909 CyberSecurity: The Future of theInternet

19000 30 2017-09-01

39910 Y2K Programming Made Easy 22000 40 2017-10-01

39911 The Essence of Java Programming 20000 29 2017-10-01

Note that you do not yet have the development cost data for the first three rows, so you'll leavethose entries as Null for now.

1. Launch SQL Server Management Studio, open a new query editor, and selectthe Pub2 database.a) If SQL Server Management Studio is not running, launch it and connect to the server.b) On the Standard toolbar, select New Query to open the Query Editor window.c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub2

database is selected.

2. Back up the table before you modify it.a) Type the following statement in the query editor.

This will copy data in the Titles table to a new table called Titles_Revised.

b) Execute the statement.The results message shows how many rows were copied into the new table.

48 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data | Topic A

Activity: Inserting Datainto a Table

SQL code snippets forthe course activities arestored as snippets.sql inthe Solutions folder foreach lesson's coursedata. You can use theseto save yourself sometyping as you leadstudents through theactivities. Or you maywant to direct studentsto these files if they arehaving trouble keepingup with the typing inclass.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Right-click the database icon shown at the top of the Object Explorer, and select Refresh to refreshthe list.

d) Expand the Databases folder, the Pub2 database, and the Tables folder.

The Titles_Revised table has been added.

3. Insert records for the books with part numbers 39906, 39907, and 39908.These books do not have information on their development costs.

Note: When specifying the values for the sale price, do not use single quotes.

SQL Querying: Advanced (Second Edition) | 49

Lesson 2: Manipulating Table Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Delete the text within the query editor.b) Select Edit→Insert File As Text.c) In the file type drop-down list, select Text Files (*.txt).

d) In the Insert File dialog box, navigate to the C:\094019Data\Manipulating Table Data folder.e) Select Insert_Record.txt, and select Open.

This INSERT statement will insert three rows into the Titles table.

Note: The editor may show a red wavy underline beneath Titles_Revisedbecause the editor may not immediately recognize the new table. Thestatement should nonetheless execute correctly. To force the editor toimmediately refresh its cache and recognize new objects, selectEdit→IntelliSense→Refresh Local Cache.

f) Execute the statements to insert the records.

4. Verify the new rows have been added.a) Clear the previous statement, and enter a query to show all rows in Titles_Revised.

50 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Execute the query, and scroll to view the last row in the results.

The three new rows have been added.

5. Insert a record for a book with an apostrophe in its title.a) Clear the previous query, and enter the following statement to insert a new record for the book titled

“SQL's Role in Big Data”.

Note: Note that you must type two apostrophes within the string to insert anapostrophe. This is necessary because the single quote (apostrophe) is usedas a string terminator. Though you type two apostrophes, only one will actuallybe added in the text.

b) Execute the query to insert the record. Verify that the Results pane displays the message "(1 rowaffected)."

c) Clear the SQL code in the query editor, and enter the following query to view all four rows that youhave added.

d) Execute the query. You should see the four rows you inserted.

SQL Querying: Advanced (Second Edition) | 51

Lesson 2: Manipulating Table Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC BModify and Delete DataYou have used SQL statements to insert data into a database table. You can also use SQL to modifyand delete data.

The UPDATE StatementYou use the UPDATE statement to modify the data in a column. The statement consists of twoparts: an UPDATE clause with the name of the table with the column values you want to update, anda SET clause that specifies the column name and the new value you want to assign to the column.

Note: You define the default value for a column when you create a table. You can use a defaultvalue in any SQL statement by specifying the DEFAULT keyword.

Figure 2-4: Sample code for the UPDATE statement.

In the example, the UPDATE statement modifies the title of the book in the Titles table with the partnumber of 39911.

Note: Be very careful using the UPDATE statement. If you fail to provide a WHERE clause, itwill update all rows with the new value.

Data Updating RulesYou need to follow specific rules when using an UPDATE statement. These rules are detailed in thefollowing table.

52 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data | Topic B

The UPDATE Statement

Data Updating Rules

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Data Updating Rules Description

Null or default values You can assign a null value or default value to a column by specifying theNULL or DEFAULT keyword in the SET clause.

Modifying multiplecolumn values

You can modify multiple column values by specifying the column namesand the modified values in the SET clause with each column name-valuepair separated by a comma.

Modifying values inspecific records

You can modify the column values of a specific record by using a searchcondition to retrieve the record.

Subqueries in theUPDATE statement

You can use a subquery in the search condition to help in retrieving atargeted record. If you don't use a search condition to retrieve a row, theUPDATE statement modifies ALL the column values in the table.

The DELETE StatementYou use the DELETE statement to delete records from a table. Columns cannot be deleted usingthe DELETE statement. You must specify the name of the target table after the DELETE statement. Bydefault, the DELETE statement deletes all records from a table. However, you can delete specificrecords by retrieving the targeted records using a WHERE clause. You can also use a subquery in thesearch condition to help retrieve the records that you want to delete.

SQL Querying: Advanced (Second Edition) | 53

Lesson 2: Manipulating Table Data | Topic B

The DELETE Statement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Figure 2-5: Sample code for the DELETE statement.

In this example, the DELETE statement deletes the record in the Titles table with the part number of39907.

The TRUNCATE TABLE StatementThe TRUNCATE TABLE statement is a SQL statement that deletes all records from a tablewithout disturbing the table structure. You must specify the name of the table you want to truncateusing the TRUNCATE TABLE statement. Although the DELETE statement can also perform thisfunction, when deleting records from a large table, the DELETE statement requires more processingtime than the TRUNCATE TABLE statement to complete the task. Unlike the DELETE statement, theTRUNCATE TABLE statement cannot delete specific records.

Figure 2-6: Sample code for the TRUNCATE TABLE statement.

In this example, the TRUNCATE TABLE statement deletes all rows in the Titles table.

The MERGE StatementYou use the MERGE statement to merge data present in two tables or columns. In SQL Server,you can use a single MERGE statement to perform the combined equivalent actions of the INSERT,UPDATE, and DELETE statements. SQL Server processes a single MERGE statement more efficientlythan executing individual INSERT, UPDATE, and DELETE statements. When using the MERGEstatement, you need to specify a source table in the USING clause and a target table in the MERGE INTO clause. You must terminate a MERGE statement with a semicolon. The basic syntax for theMERGE statement is:MERGE table_name AS targetUSING table_name AS sourceON (condition)WHEN MATCHED THEN

54 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data | Topic B

The TRUNCATE TABLEStatement

The MERGE Statement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

UPDATE SET column1 = value1 [, column2 = value2 ...] WHEN NOT MATCHED BY TARGET THEN INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...]) WHEN NOT MATCHED BY SOURCE THEN DELETE (column1 [, column2 ...]) VALUES (value1 [, value2 ...]);

Figure 2-7: Sample code for the MERGE statement.

The example uses the MERGE statement to insert rows into the New_titles table from the Titles tablewhen a matching row does not exist in the New_titles table.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Modify and Delete Data.

SQL Querying: Advanced (Second Edition) | 55

Lesson 2: Manipulating Table Data | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 2-2Modifying Data

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.You have copied the Titles table to a table named Titles_Revised.

ScenarioYou have added four new book titles to the catalog of the Fuller & Ackerman Publishing bookstore.You recorded the information related to these titles in the Titles_Revised table. However, thedevelopment cost information was not provided by the publisher for titles with part numbers 39906,39907, and 39908. The publisher has now requested that you update your Titles_Revised table withthe development cost of $21,000 for each of those titles.You have also been informed by the sales representative in the store that the information on one ofthe new titles with part number 39909 is completely incorrect in the table. He has provided you withthe correct information. The book title should be "Java Programming Made Easy." The book'sdevelopment cost is $25,000, and its sale price is $32. The book was published on 11-01-2017.

1. Update the records of books that do not have the development costinformation and verify whether the update is successful.a) Enter the following query to update the development cost:

b) Execute the UPDATE statement to update the required records.

Three rows are affected.c) To verify that your changes took effect, revise the previous query as shown.

The WHERE clause remains the same so you can view the rows you just updated.

56 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data | Topic B

Activity: Modifying Data

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

d) Execute the query, and observe that the development costs for the books with part numbers from39906 to 39908 have been updated to $21000.

2. Correct the information in the record for the book with the part number 39909and verify whether you made the changes successfully.a) Delete the previous query.b) Write a query to update the information in the record for the book with part number 39911. Update

the Book Title, Development Cost, Sale Price, and Date of Publishing with 'Java Programming MadeEasy', 25000, 32.000, and '2017–11–01', respectively:

c) Execute the query.

One row is affected.d) Revise the query as shown.

e) Execute the query and view the results.

SQL Querying: Advanced (Second Edition) | 57

Lesson 2: Manipulating Table Data | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 2-3Deleting a Row of Data from a Table

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.You have copied the Titles table to a table named Titles_Revised.

ScenarioAfter reviewing the sales reports of various branches, the sales manager at the Fuller & AckermanPublishing bookstore is concerned that some of the titles were selling much below the targetednumbers. One of the books named “History of the Internet” with the part number 39907 has notsold at all. To comply with an organizational policy, the manager ordered the removal of titles thatsold less than 100 copies from the store shelves.

1. Delete the record for the book with the part number 39907 from the Titlestable.a) Revise the statement as shown:

b) Execute the statement to delete the record.

One row is affected.

2. Verify whether you deleted the targeted record from the Titles_Revised table.a) Revise the query to attempt to retrieve the record you just deleted.

b) Execute the query.

There is no longer a row with the part number 39907.

58 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data | Topic B

Activity: Deleting a Rowof Data from a Table

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 2-4Deleting All Rows from a Table

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.You have copied the Titles table to a table named Titles_Revised.

ScenarioYou need to start a new table for book data. Since you no longer need to use the data in theTitles_Revised table, you will delete all rows in that table, while maintaining the structure of thetable.

Delete all rows from the Titles_Revised table.a) Remove the WHERE clause from the query.

b) Execute the query.

95 rows are shown.c) Insert two blank lines before the query, and enter a new statement before it as shown.

d) Execute the statements.

All rows have been deleted from Titles_Revised, but the table still maintains its data structure. Fivecolumns are shown, but no rows.

e) Close the Query Editor window without saving the query.

SQL Querying: Advanced (Second Edition) | 59

Lesson 2: Manipulating Table Data | Topic B

Activity: Deleting AllRows from a Table

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SummaryA SQL database is only as good as the information it contains. During the normal operations of abusiness, the contents of a business' database must change to reflect new customers, reductions ininventory, and sales. For these reasons, to maintain an accurate database, you must know how toinsert, update, and delete data from tables.

What are the benefits of being able to manipulate table data through SQL?A: SQL can make quick work of editing tasks, particularly those that affect multiple records. If you can

produce a list of data that requires manipulation (using a WHERE clause, for example), you canmodify all the matching records in a single command.

What are some of the data management tasks you might accomplish throughthe techniques you used in this lesson?A: The data management tasks you used in this lesson have many applications. For example, you might

purge unused records or tables from a database at regular intervals to save disk space and usetables efficiently. Updates such as mass pricing changes can also be made through the datamanipulation techniques you used in this lesson. You might periodically move outdated information toa different table.

Note: Check your CHOICE Course screen for opportunities to interact with your classmates,peers, and the larger CHOICE online community about the topics covered in this course orother topics you are interested in. From the Course screen you can also access availableresources for a more continuous learning experience.

60 | SQL Querying: Advanced (Second Edition)

Lesson 2: Manipulating Table Data |

Encourage students touse the socialnetworking toolsprovided on the CHOICECourse screen to followup with their peers afterthe course is completedfor further discussionand resources to supportcontinued learning.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Manipulating TableStructureLesson Time: 1 hour, 40 minutes

IntroductionOver time, you might need to change your database's structure. You can use SQL to addnew tables and new columns, or change the types of data stored within a particular column.

Lesson ObjectivesIn this lesson, you will manipulate table structure. You will:

• Create a table.

• Create a table with constraints.

• Modify a table's structure.

• Delete tables.

3

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC ACreate a TableAs your organization grows and responds to changes in the marketplace, you might find that itneeds to store new information. In order to store this information, you must know how to create anew table. In this topic, you will learn how to create a new table.

The CREATE TABLE StatementYou use the CREATE TABLE statement to create the structure of a table. However, it does notpopulate the table with data. For example, the following query creates a table named Sales_Newwith six columns.

Figure 3-1: A CREATE TABLE statement example.

You need to follow some rules when writing a CREATE TABLE statement. These rules are detailed inthe following table.

Rule Description

Table name You must specify the name of the table you want to create after the CREATE TABLE statement.

Columndefinitions

After the table name, specify the names of the columns and their definitions,enclosed within parentheses. Each column definition consists of the data type,size, and any other information you need to specify for the column. You canalso specify computed columns while defining a column.

Column size Depending on the column's data type, you might need to specify the size ofthe column, also enclosed within parentheses.

Null values By default, a column can store null values. However, you can restrict thestorage of null values in a column by specifying the NOT NULL keyword in thecolumn definition.

62 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic A

The CREATE TABLEStatement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

The INSERT INTO StatementAfter you create a table, you can use the INSERT INTO statement to insert data into the table. Forexample, the following two statements insert two rows into the Suppliers table:INSERT INTO suppliersVALUES('S001','Allendales','1149 Blossom Road');INSERT INTO suppliersVALUES('S002','Caldwell','981 Connecticut Blvd');

Displaying the Table StructureUse the SP_HELP stored procedure to display a table's structure. The syntax is:SP_HELP tablename1

SQL Data TypesMicrosoft® SQL Server® 2012 supports a number of data types that you can use when defining thecolumns of a table. SQL Server includes support for the following categories of data types:• Exact numeric.• Approximate numeric.• Date and time.• Character strings.• Binary strings.• Other data types.The exact numeric data types enable you to store integers as well as numbers with decimal places.The following table describes the exact numeric data types.

Data Type Range of Values Supported Storage Size

bigint -263 to 263-1 8 bytes

int -231 to 231-1 4 bytes

smallint -215 to 215-1 2 bytes

tinyint 0 to 255 1 byte

bit 1, 0, or NULL If there are 8 or fewer bitcolumns in a table, MicrosoftSQL Server stores the columnsin 1 byte. If there are 9 - 16 bitcolumns in a table, SQL Serveruses 2 bytes to store them; andso on.

money -922,337,203,685,477.5808 to922,337,203,685,477.5807

8 bytes

smallmoney - 214,748.3648 to 214,748.3647 4 bytes

SQL Querying: Advanced (Second Edition) | 63

Lesson 3: Manipulating Table Structure | Topic A

Exact Numeric DataTypes

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Data Type Range of Values Supported Storage Size

decimal (precision, scale)You must specify the precision(the total number of digits bothbefore and after the decimalpoint), and the scale (thenumber of digits after thedecimal point). Precisiondetermines the amount ofstorage the column requires.The numeric data type isfunctionally equivalent to thedecimal data type.

1 - 9 digits of precision10 - 19 digits of precision20 - 28 digits of precision29 - 38 digits of precision

5 bytes9 bytes13 bytes17 bytes

The approximate data types enable you to store numbers with a varying number of digits after thedecimal point. When you use the approximate data types, you can specify a value that identifies thenumber of digits you need to store the mantissa (the significant digits) of a number in scientificnotation. The following table describes the approximate numeric data types.

Data Type Range of Values Supported Storage Size

float (n), where n is a numberfrom 1 to 53

- 1.79308 to -2.23-308, 0, and2.23-308 to 1.79308

If n is 1 - 24, 4 bytes; if n is 25 -53, 8 bytes.

real, which is equivalent to float(24)

-3.4038 to -1.18-38, 0, and1.18-38 to 3.4038

4 bytes

You use the date and time data types in SQL Server to store date information, time information, orboth. The following table describes the date and time data types you can assign.

Data Type Range of Values Supported Storage Size

date 0001-01-01 through 9999-12-31 3 bytes

datetime January 1, 1753 through December 31, 999900:00:00 through 23:59:59.997

8 bytes

datetime2 0001-01-01 through 9999-12-3100:00:00 through 23:59:59.9999999

6 bytes for precisionsless than 3; 7 bytes forprecisions 3 and 4. Allother precisions require8 bytes.

smalldatetime 1900-01-01 through 2079-06-0600:00:00 through 23:59:59

4 bytes

time 00:00:00.0000000 through 23:59:59.9999999 5 bytes

datetimeoffset 0001-01-01 through 9999-12-3100:00:00 through 23:59:59.9999999

10 bytes

SQL Server includes several data types for storing alphanumeric characters. The char and varchardata types enable you to store any one of the 255 characters in the American Standard Code forInformation Interchange (ASCII) character set. In contrast, the nchar and nvarchar data typesenable you to store any of 65,535 characters in the Unicode or Universal Character Set (UCS)-2

64 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic A

Approximate NumericData Types

Date and Time DataTypes

Character Data Types

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

character set. The nchar and nvarchar data types use two bytes to store each character in thecolumn.The char and nchar data types are considered fixed because they consume a fixed amount ofstorage space regardless of how many characters you store in columns with these data types. Forexample, if you assign the data type char(15) to a column, it consumes 15 bytes of storage spaceeven if it's empty. In contrast, varchar and nvarchar consume storage space based on the numberof characters they contain. For example, a column that has the data type varchar(20) will use only6 bytes to store the value "Fuller" instead of 20 bytes.Another category of data types is binary. You use the binary data types to store binary data (onesand zeroes). When you assign a binary data type to a column, you must specify the number of bytesyou want it to use; you can specify 1 to 8,000 bytes. The following table describes the binary datatypes you can define.

Data Type Storage Size

binary(n), where n is the number of bytes youwant to reserve for the column.

1 - 8,000 bytes

varbinary(n), where n is the maximum numberof bytes the column can use. Varbinary is avariable-length data type, so it consumes storagespace based on the values stored in the column.

Actual length of the data stored in the columnplus two bytes.

image Variable-length binary data (images) from 0 to231-1 bytes.

Finally, SQL Server includes other data types for storing a variety of data. The following tabledescribes the other data types.

Data Type Purpose Storage Size

timestamp (also knownas rowversion)

Use to assign a version identifier in binary totable rows. SQL Server changes this value foreach INSERT or UPDATE statement you execute.

8 bytes

xml Use to store XML data. Up to 2 GB

uniqueidentifier Use to assign a unique ID to each row in a table. 16 bytes

Table DesignTable design refers to how you structure a table with the required columns and rows. Creating awell-defined table design helps in the effective organization and storage of data in a table. To designan effective table, follow these guidelines:• Identify the business requirement that you need to fulfill by creating the table.• To determine the columns of a table, decide on the information related to the business

requirement that you want to store in the table, and convert these points of information intocolumns.

• Identify the appropriate data type you should assign to each column. To choose the mostappropriate data type for a column, base your decision on the characteristics of the data that youplan to store in the column.

• Decide on the column width based on the likely size of values that you will store in the column.• Determine whether you need to impose any limitations on the data that is entered into a column.

If required, decide on the restrictions that you need to apply to the column.• Determine the conditions that you must fulfill to meet the business requirements for creating the

column. Based on these conditions, create restrictions on the column.

SQL Querying: Advanced (Second Edition) | 65

Lesson 3: Manipulating Table Structure | Topic A

Emphasize to studentsthat the Unicode datatypes (nchar andnvarchar) require twobytes to store eachcharacter. So if youassign the data typenchar(15) to acolumn, SQL Server willuse 30 bytes to storethat column's data.

Binary Data Types

Other Data Types

Table Design

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.Figure 3-2: A table design example.

For example, at the Fuller & Ackerman Publishing bookstore, you have a business requirement tostore information on books so you decide to create a Titles table. You determine that you want tostore information about each book's part number, book title, development cost, the selling price,and the publication date in the table. Because you plan to store part numbers of up to 10 charactersin the partnum column, you assign it the nvarchar data type.Because you expect to store titles of varying lengths in the bktitle column, you decide to assign thenvarchar data type to this column. You specify 80 as the column size for the bktitle columnbecause you expect the column to store values up to a maximum of 80 characters. You also need toassign data types to the slprice column and the devcost column for the book. Because both of thesecolumns store money information, you assign them the money data type. Finally, you plan to storedates in the pubdate column so you assign it the smalldatetime data type.

Table BackupOne way to create a table is to start with a copy of another table. You can do this by using theSELECT INTO statement.

Figure 3-3: A SELECT INTO statement example.

The SELECT INTO statement creates a backup of a table's structure and data in a new table. You canalso copy the contents from multiple tables or views into a new table.You cannot use the SELECT INTO statement to back up a table that uses the COMPUTE clausebecause SQL Server will not store the results of the COMPUTE clause in the database. Therefore,when you create a new table using the SELECT INTO statement, any calculations produced duringthe execution of the COMPUTE clause will not appear in the new table.

66 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic A

The SELECT INTOStatement

You may want to showthe Spotlight on SQLDatabase Backups fromthe CHOICE Coursescreen or have studentsnavigate out to theCourse screen andwatch it themselves as asupplement to yourinstruction. If not, pleaseremind students to visitthe Spotlights for thiscourse on their CHOICECourse screen afterclass for supplementalinformation andadditional resources.

Point out to students thatthey already usedSELECT INTO to backup a table in Lesson 2.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Note: To further explore backing up, you can access the Spotlight on SQL Database Backupspresentation from the Spotlight tile on the CHOICE Course screen.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Create a Table.

SQL Querying: Advanced (Second Edition) | 67

Lesson 3: Manipulating Table Structure | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 3-1Creating Tables

ScenarioOne of the important points at a monthly meeting of store managers of the Fuller & AckermanPublishing bookstore chain is the increase in demand for titles that were taken off the shelves fromthe store. The demand for these titles, classified as obsolete titles, seems to increase when a movie isfilmed based on these titles. Using this indicator, store managers feel that they can predict thedemand for obsolete titles and prefer to have a mechanism by which such titles can be tracked andprocured quickly.The sales manager of the bookstore chain wants you to create a table to record the part number,book title, sale price, and publishing date information related to titles that are taken off the shelves.You will create this table, naming it Obsolete_Titles1.

1. Launch SQL Server Management Studio, open a new query editor, and selectthe Pub2 database.a) If SQL Server Management Studio is not running, launch it and connect to the server.b) On the Standard toolbar, select New Query to open the Query Editor window.c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub2

database is selected.

2. Create the Obsolete_Titles1 table.a) In the query editor, enter the query as shown.b) Enter a query to create a table.

• Five columns will be initially defined for the table.• Each column definition includes the column name and data type.• The NOT NULL restriction is placed upon the partnum column. The server will reject any

requests (such as an INSERT INTO statement) that would create a row without a partnum value.c) Execute the CREATE TABLE statement to create the Obsolete_Titles1 table.

68 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic A

Activity: Creating Tables

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

3. View the table structure.a) Delete the previous query.b) Enter the command to display the table structure of the Obsolete_Titles1 table:

c) Execute the statement.d) In the Results pane, view the column definitions for the Obsolete_Titles1 table.

SQL Querying: Advanced (Second Edition) | 69

Lesson 3: Manipulating Table Structure | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC BCreate a Table with ConstraintsA table with a simple structure is sufficient to store data but is not effective in an actual businessenvironment. Typically, you need to add checks and conditions to the table structure to ensure thevalidity of the data stored in a table. You implement data validation in SQL by adding constraints tocolumns. In this topic, you will create a table with constraints.

Data IntegrityData integrity is the state of information in a database where all values stored in the database arecorrect. When you ensure data integrity, you ensure that the data is stored exactly as you intended,and when it is retrieved again, the data remains the same as when it was stored.The integrity of data in a database indicates whether the values are valid and whether they can beused for further processing. Data integrity can be classified into entity integrity, domain integrity,referential integrity, and user-defined integrity.

Figure 3-4: An example of data integrity.

There are various data integrity types. They are detailed in the following table.

Type of Data Integrity Description

Entity integrity Indicates the state of the records in a table where each record isunique.

Domain integrity Indicates that the columns of a table contain valid data.

Referential integrity Indicates the state of data in linked tables where the columns thatlink the tables have matching values.

User-defined integrity Indicates the state of data in a database where the validity of thedata is maintained based on business rules defined by a user.

Note: To further explore data integrity, you can access the Spotlight on SQL Database Designpresentation from the Spotlight tile on the CHOICE Course screen.

70 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic B

Data Integrity

You may want to showSpotlight on SQLDatabase Design fromthe CHOICE Coursescreen or have studentsnavigate out to theCourse screen andwatch it themselves as asupplement to yourinstruction. If not, pleaseremind students to visitthe Spotlights for thiscourse on their CHOICECourse screen afterclass for supplementalinformation andadditional resources.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Primary KeysA primary key is a column or a combination of columns that stores values to uniquely identify eachrecord in a table. A value entered in the primary key column for any record must be unique from thevalues in all other records. A table can contain only one primary key, but a primary key can containmultiple columns. Such primary keys are called composite keys. A primary key column cannotstore null values. By creating a primary key, you ensure that the values stored in the relevantcolumn(s) are not duplicated across the records of the table.

Figure 3-5: A primary key example.

ConstraintsA constraint is a validation mechanism you implement in a column of a table to ensure dataintegrity. Constraints define rules that test the values specified for a column when inserting,modifying, or deleting a record. If the values do not comply with the rules you defined by theconstraint, then SQL Server cannot insert, update, or delete the records.For example, you might define a primary key constraint. When a user tries to insert, update, ordelete a record that does not contain primary key values that make the record unique, then SQLServer will prevent the user from completing the operation.Or you might define a constraint that requires a particular condition a data value must satisfy. Forexample, a value entered in the qty column must be less than 225. The server will not permit arecord to be stored or updated if this condition is not true.

Figure 3-6: A constraint example.

SQL Querying: Advanced (Second Edition) | 71

Lesson 3: Manipulating Table Structure | Topic B

Primary Keys

Constraints

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Constraint DefinitionYou can define constraints at the column level or table level. These constraints are detailed in thefollowing table.

Type of Constraint Description

Column-level constraint Defined as part of a column definition in a CREATE TABLE statementand applied to that column alone.

Table-level constraint Defined after the columns have been defined in a CREATE TABLEstatement. You use this type of constraint when you need to specifymultiple columns as part of the constraint.

When you define a constraint, you can name it. If you don't name a constraint, SQL Server willassign a default name to it. Later, if you want to alter the table constraint, you would need to findthe system-generated name before writing the query to alter the table constraint. However, if youassign a name to a constraint, then you can refer to the constraint name whenever you need tomodify or delete it. This is much easier than finding out the system-generated constraint names andusing them in a query.

PRIMARY KEY ConstraintsThese two alternative examples demonstrate how to define a primary key at the column and tablelevels. The examples create an identical table, but the first example specifies the primary key where itdefines the column. The second example specifies the primary key at the table level, after thecolumns have been defined.

Figure 3-7: Defining PRIMARY KEY constraints through the column or table definition.

UNIQUE ConstraintsYou use a UNIQUE constraint to enforce uniqueness in a column of a table.Although PRIMARY KEY constraints also enforce uniqueness, you can define only one primary keyfor a table. In contrast, you can create multiple UNIQUE constraints for a table. In addition, columnsthat are constrained by the UNIQUE constraint can accept null values.

72 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic B

PRIMARY KEYConstraints

UNIQUE Constraints

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

The following example shows how you would define a phone column that contains values that mustbe unique to each record.

Figure 3-8: A UNIQUE constraint example.

There are two types of UNIQUE constraints: column-level and table-level. The syntax for definingcolumn-level and table-level UNIQUE constraints differs, as shown in the following table.

Constraint Type Description

Column-levelUNIQUE constraint

You write the CONSTRAINT keyword first, followed by the constraint name,and then the UNIQUE keyword.CREATE TABLE tablename(columnname1 datatype(sizevalue) [CONSTRAINT constraintname] PRIMARY KEY,columnname2 datatype(sizevalue),columnname3 datatype(sizevalue),columnname4 datatype(sizevalue) [CONSTRAINT constraintname] UNIQUE)

Table-level UNIQUEconstraint

You write the CONSTRAINT keyword first, followed by the constraint name,the UNIQUE keyword, and then write the name of the targeted columnenclosed within parentheses.CREATE TABLE tablename(columnname1 datatype(sizevalue) [CONSTRAINT constraintname] PRIMARY KEY,columnname2 datatype(sizevalue),columnname3 datatype(sizevalue),columnname4 datatype(sizevalue)[CONSTRAINT constraintname] UNIQUE (columnname3))

SQL Querying: Advanced (Second Edition) | 73

Lesson 3: Manipulating Table Structure | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Foreign KeysYou use a foreign key to link a column in one table with a column in another table. The table withthe column referenced by the foreign key of another table is called the referenced table. To maintainreferential integrity, the values stored in the foreign key column must match the values stored in theprimary key or unique key columns of the referenced table. The records in a foreign key can storevalues that exist in other records of the key.

Figure 3-9: A foreign key example.

FOREIGN KEY ConstraintsYou use a FOREIGN KEY constraint to define the foreign key for a table. You create theFOREIGN KEY constraint when you create a table with the CREATE TABLE statement. You can definethe FOREIGN KEY constraint as a column-level or as a table-level constraint. You can't modify anexisting FOREIGN KEY constraint without deleting the constraint and creating it with a newdefinition.Following are examples showing a new Sales table being created with a foreign key in the Slsperstable.

74 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic B

Foreign Keys

FOREIGN KEYConstraints

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Figure 3-10: FOREIGN KEY constraint examples.

The syntax for column-level and table-level FOREIGN KEY constraints differs, as described in thefollowing table.

Constraint Type Description

Column-levelFOREIGN KEYconstraint

You specify the CONSTRAINT keyword first, followed by the constraint name,the FOREIGN KEY keywords, the REFERENCES keyword, the name of thereferenced table, and the name of the column on the referenced table to whichyou want to link the foreign key. You must enclose this column name withinparentheses.CREATE TABLE tablename (columnname1 datatype(sizevalue), columnname2 datatype(sizevalue), columnname3 datatype(sizevalue) [CONSTRAINT constraintname] FOREIGN KEY REFERENCES referencingtablename(columnname), columnname4 datatype(sizevalue), columnname5 datatype(sizevalue) )

Table-levelFOREIGN KEYconstraint

The syntax for a table-level FOREIGN KEY constraint is similar to that of thecolumn-level constraint, except that you specify the foreign key nameimmediately after the FOREIGN KEY keywords and enclose the referencedcolumn name within parentheses.CREATE TABLE tablename ( columnname1 datatype(sizevalue),columnname2 datatype(sizevalue),columnname3 datatype(sizevalue),columnname4 datatype(sizevalue),columnname5 datatype(sizevalue),CONSTRAINT constraintname FOREIGN KEY (foreignkeycolumnname1, foreignkeycolumnname2) REFERENCES referencingtablename(columnname1, columnname2))

SQL Querying: Advanced (Second Edition) | 75

Lesson 3: Manipulating Table Structure | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DEFAULT ConstraintsA DEFAULT constraint is a database constraint you use to specify a default value for a column.You can define the constraint when creating a table with the CREATE TABLE statement. The defaultvalue specified must correspond to the data type of the constrained column.

Figure 3-11: A DEFAULT constraint example.

You can create a DEFAULT constraint only as a column-level constraint, as shown in the example.You define the constraint by using the DEFAULT keyword after the column definition, followed bythe constant value you want to use as the default value for the column. Each new record in thisexample will automatically be assigned an initial commrate value of 0.02.

CHECK ConstraintsYou use a CHECK constraint to validate the values stored in a column based on a condition youspecify with the constraint. The condition is a logical operator that returns a value of TRUE or FALSE,depending on whether the value you insert into the column meets the CHECK constraint'srequirements. If the column value you insert or modify does not comply with the CHECK constraint,SQL Server prevents the insert or update. You can use multiple logical expressions linked withlogical operators such as AND and OR in the CHECK constraint. You can also define multiple CHECKconstraints for a column and SQL Server implements each constraint on the column's value in theorder in which you defined them.

76 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic B

DEFAULT Constraints

CHECK Constraints

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Figure 3-12: CHECK constraint examples.

You can define a CHECK constraint as a table-level or column-level constraint. The following tabledescribes the syntax for adding a CHECK constraint.

Constraint Type Description

Column-level CHECKconstraint

Define using the CONSTRAINT keyword, followed by the constraint name,the CHECK keyword, and the logical expression or expressions you want touse to validate the column values. You can specify only a single CHECKconstraint at the column level. You can't specify other columns of the tablein the logical expression of a column-level CHECK constraint.

Table-level CHECKconstraint

Syntax is similar to the column-level CHECK constraint. However, at the tablelevel, you can specify multiple columns as part of the logical expression.You can't specify columns from other tables in the logical expression.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Create a Table with Constraints.

SQL Querying: Advanced (Second Edition) | 77

Lesson 3: Manipulating Table Structure | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 3-2Planning a Table with Constraints

ScenarioTo attract new customers, the Fuller & Ackerman Publishing bookstore plans to host a number ofcompetitions on its website. The website is being redesigned to include crossword puzzles and othergames with big prize money to act as incentives. By making a contestant register with the websitebefore allowing entry into the competition, the store plans to garner the contact details of a list ofpotential customers. The contact details include a participant's name, address, and phone number.This information can be used by the sales team to contact the potential customers later. You plan tostore the registration information in a table called Potential_customers1.

1. Which is the best method to avoid duplication of customer information?○  Provide a message on the website that requests customers who have already registered to avoidregistering again.○  Prevent users with identical names from registering with the website.○  If users with identical information register, add a prefix to the name of each user to differentiatebetween the users.◉  Uniquely identify each user by defining the custnum column as the primary key for the table.

2. When defining the columns of the Potential_customers1 table, which optionrepresents the best method to ensure that a user provides all the requiredinformation when registering with the website?○  Display a message on the website requesting users to fill all possible fields on the registration form.○  Specify simple names for the table columns.○  Reduce the number of columns in the Potential_customers1 table as compared to the Customerstable.◉  Use the NOT NULL keywords when defining the column values for the Potential_customers1 table.

3. True or False? To ensure that potential customers enter valid cell phonenumbers into the Potential_customers1 table, you need to add a CHECKconstraint to the cellno column to check whether the length of the numberspecified is greater than or equal to 10.☑  True☐  False

78 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic B

Activity: Planning aTable with Constraints

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 3-3Creating a Table with Constraints

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioNow that you've planned the appropriate modifications for the Potential_Customers1 table, youneed to put them in place.

1. Create the Potential_Customers1 table with column constraints for effectivestorage of potential customer information.a) Delete the code in the query editor, and enter a new statement as shown.

• This statement will create a new table called Potential_Customers1, defining six columns of

data, and identifying custnum as the primary key.• The custname, address, and repid values are required.• A length check has been specified for the cellno value.

b) Execute the query.c) Observe that the statement executed successfully.

2. View the structure of the Potential_Customers1 table.a) Clear the code in the query editor and enter the following command to view the table structure.

b) Execute the query.

SQL Querying: Advanced (Second Edition) | 79

Lesson 3: Manipulating Table Structure | Topic B

Activity: Creating Tableswith Constraints

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) In the Results pane, scroll down to view the structure of the Potential_Customers1 table.

d) Observe that you defined a primary key on the custnum column.

80 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC CModify a Table's StructureYou have created various table structures. Based on your requirements, there might be situationswhen you need to modify the structure of those tables by adding or dropping columns, adding ordropping constraints, or modifying a table's columns. In this topic, you will modify a table'sstructure to suit your needs.

The ALTER TABLE StatementYou modify the structure of a table by using the ALTER TABLE statement. By using thisstatement, you can modify the definition of a column, add columns or constraints to a table, anddrop columns or constraints from a table.

Figure 3-13: An ALTER TABLE statement example.

Each structure modification task performed by the ALTER TABLE statement requires a differentsyntax. These structure modification tasks are detailed in the following table.

StructureModification Task

Syntax and Limitations

Add columns To add a column to a table, you specify the ALTER TABLE clause first, followedby the table name, the ADD keyword, the column name, and the definition ofthe new column.ALTER TABLE table_name ADD column_name datatype

Drop columns To drop a column from a table, you specify the ALTER TABLE statement first,followed by the table name, the DROP COLUMN clause, and the name of thecolumn you want to delete. You can't drop columns that are constrained byPRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and DEFAULT constraints.Instead, you must delete the constraint first and then drop the column.ALTER TABLE table_name DROP COLUMN column_name

SQL Querying: Advanced (Second Edition) | 81

Lesson 3: Manipulating Table Structure | Topic C

The ALTER TABLEStatement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

StructureModification Task

Syntax and Limitations

Add constraints To add a new constraint to a table, you specify the ALTER TABLE clausefollowed by the table name, the ADD keyword, and the constraint definitionwith the CONSTRAINT keyword. The syntax of the constraint definition issimilar to the syntax used to define constraints in the CREATE TABLEstatement. The constraint definition when adding a foreign key is similar to thesyntax of a table-level FOREIGN KEY constraint used with the CREATE TABLEstatement.ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES table_name(column_name)

Drop constraints When dropping a constraint, you use the ALTER TABLE statement first,followed by the table name, the DROP CONSTRAINT clause, and the name of theconstraint you want to drop.ALTER TABLE table_name DROP CONSTRAINT constraint_name

Modify thecolumn definition

To modify a column's definition, use the ALTER TABLE clause first, followedby the table name, the ALTER COLUMN clause, the name of the column youwant to modify, and the new column definition. You cannot modify thedefinition of computed columns, primary keys, foreign keys, columns withCHECK or UNIQUE constraints, and columns with the text, ntext, image, ortimestamp data types. If a column has a default constraint, you cannot modifythe data type of the column. However, you can modify the value and the sizeof the value. Modifying the data type of an nchar or nvarchar column tochar or varchar might change the values stored in the column.ALTER TABLE table_name ALTER COLUMN deptno char(10)

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Modify a Table's Structure.

82 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 3-4Adding and Dropping Columns

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open, and youhave created the tables as described in this lesson's previous activities.

ScenarioAfter reviewing the monthly sales reports of the Fuller & Ackerman Publishing bookstore, the storemanager wants to change some of the information displayed. The manager feels that knowing abook's development cost is unnecessary when generating reports of obsolete titles. Instead, themanager wants you to record the publisher's full address.

1. Add a column named pubaddress to the Obsolete_Titles1 table.a) Clear the previous query, and enter the following.

This statement will add a column named pubaddress to the Obsolete_Titles1 table.

b) Execute the query to add the pubaddress column.

2. Drop the devcost column from the Obsolete_Titles1 table.a) Modify the previous query to drop the devcost column:

b) Execute the statement to drop the devcost column.

3. Check whether the modifications succeeded.

SQL Querying: Advanced (Second Edition) | 83

Lesson 3: Manipulating Table Structure | Topic C

Activity: Adding andDropping Columns

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Clear the code in the query editor and enter the following command to view the table structure.

b) Execute the statement.c) In the Results pane, view the changes in the structure of the Obsolete_Titles1 table.

Pubaddress has been added, and devcost has been removed.

84 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 3-5Modifying Column Definitions and Constraints

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open, and youhave created and modified the tables as described in this lesson's previous activities.

ScenarioWhen reviewing the monthly sales reports of the Fuller & Ackerman Publishing bookstore, the storemanager identifies certain discrepancies in the report. Some records in the Sales table are duplicated.Sales records show sales of books that do not exist in the Titles table. Some records of book salesshow zero copies sold to a customer. You deleted these problem records as a temporary measure.However, the store manager asks you to ensure that such discrepancies do not occur in the future.You will work on a copy of the Sales table.

1. Create a copy of the Sales table.a) Clear the previous query, and enter the following.

This will copy data in the Sales table to a new table called Sales_Copy.

b) Execute the statement.

c) Right-click the database icon shown at the top of the Object Explorer, and select Refresh to refresh

the list.d) Expand the Databases folder, the Pub2 database, and the Tables folder.

The Sales_Copy table is now shown in the Pub2 database.

2. View the structure of Sales_Copy.

SQL Querying: Advanced (Second Edition) | 85

Lesson 3: Manipulating Table Structure | Topic C

Activity: ModifyingColumn Definitions andConstraints

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Clear the previous query, and enter the following.

b) Execute the statement.c) Examine the results.

The order number (ordnum) should be a unique value, and would make a good primary key.

3. Add a primary key to the Sales table.a) Clear the query editor and enter a new statement to make the ordnum column a primary key for the

Sales_Copy table.

86 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Execute the statement to attempt to add the primary key.

The statement fails because the key you are trying to assign as the primary key is nullable, meaningit can accept a NULL value assignment. If you have a primary key, its value must be provided, sothe column must be one that is not nullable.

c) Before the ALTER TABLE statement, insert a new statement to configure ordnum to not accept anull value.

d) Highlight and execute the first statement to make ordnum not accept a null value.

e) Highlight and execute the second statement to set ordnum as a primary key.

f) To verify your change, display the structure of the Sales_Copy table using the SP_HELP stored

procedure.

g) Execute the statement.

SQL Querying: Advanced (Second Edition) | 87

Lesson 3: Manipulating Table Structure | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

h) The last section in the Results pane displays the constraint information.

88 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC DDelete TablesThroughout this course so far, you have created, modified, and backed up tables. With time, youmight find that some tables become obsolete and you no longer need them. Rather than havingthem take up space in your database, you can update your database by deleting such tables.

The DROP TABLE StatementThe DROP TABLE statement is a SQL statement that deletes a table from a database. The nameof the table to be dropped must be specified after the DROP TABLE clause. In addition to the recordsin the table, the table's definition, which includes the column definitions and any constraintsprovided in the definition, is also deleted when you execute this statement. However, if a tabletargeted for deletion is being referenced by the foreign key of another table, the referencingFOREIGN KEY constraint or the referencing table must be dropped before the target table can bedeleted.

Figure 3-14: A DROP TABLE statement example.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Delete Tables.

SQL Querying: Advanced (Second Edition) | 89

Lesson 3: Manipulating Table Structure | Topic D

The DROP TABLEStatement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 3-6Deleting Tables

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open, and youhave created and modified the tables as described in this lesson's previous activities.

ScenarioThere are some tables within the Pub2 database that you no longer need. In this activity, you willdrop these tables from the database.

1. View a list of all tables in the Pub2 database.a) Clear the previous query, and enter the following.

• In SQL Server (2005, 2008, 2012, 2014, 2016, or 2017), this query will list all tables in the

specified database.b) Execute the query and examine the list of tables.

You will drop three tables from the database:• Obsolete_Titles1• Potential_Customers1• Sales_Copy

2. Delete the unneeded tables from the Pub2 database.

90 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure | Topic D

Activity: Deleting Tables

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Insert three new statements before the statement in the query editor.

Note: The editor may show a red wavy underline beneath the table titlesbecause the tables were only recently created. The statements shouldnonetheless execute correctly. To force the editor to immediately refresh itscache and recognize the tables, select Edit→IntelliSense→Refresh LocalCache.

b) Execute all of the statements in the query editor to delete the three tables and show the tablesremaining in Pub2.

The three tables have been dropped, as shown by the new list.

c) Close the Query Editor window without saving the query.

SQL Querying: Advanced (Second Edition) | 91

Lesson 3: Manipulating Table Structure | Topic D

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SummaryAs your organization's needs change, you must be prepared to modify the structure of its SQL tablesor even delete unnecessary tables. Knowing how to insert new tables or new columns, modifyexisting columns, and delete columns or tables enables you to quickly respond to your organization'schanging needs.

How should you map business requirements and table designs before creatingtables?A: Answers will vary, but might include that you should design tables based on the users who will access

these tables and their requirements, such as the various reports they will generate on a daily basis.By evaluating the data you need to store in the table, you can identify the column names and theirdata types.

What basic constraints should you implement when creating a table?A: Answers will vary, but might include that you should create a PRIMARY KEY constraint on each table

so that you have information that uniquely identifies each row in the table. You should also considercreating FOREIGN KEY constraints for any columns that contain data that matches columns inanother table.

Note: Check your CHOICE Course screen for opportunities to interact with your classmates,peers, and the larger CHOICE online community about the topics covered in this course orother topics you are interested in. From the Course screen you can also access availableresources for a more continuous learning experience.

92 | SQL Querying: Advanced (Second Edition)

Lesson 3: Manipulating Table Structure |

Encourage students touse the socialnetworking toolsprovided on the CHOICECourse screen to followup with their peers afterthe course is completedfor further discussionand resources to supportcontinued learning.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Working with ViewsLesson Time: 1 hour, 10 minutes

IntroductionSome database users may not know how to write SQL queries, or may not want to bebothered to write a query to view data coming from multiple tables. Or you may want tohide certain columns of data from the view of end users. Database views enable you tocontrol what data users see, like a query, but they can be quickly invoked to present data in aparticular way. In this lesson, you will create views, use them to manipulate data, modifyviews, and delete views.

Lesson ObjectivesIn this lesson, you will work with views. You will:

• Create a view.

• Manipulate the data in views.

• Modify and drop views.

4

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC ACreate a ViewYou've used the SELECT clause to control which columns are shown in a report, and you haveused the WHERE clause to define which rows are shown. You've used JOIN and other tools tocombine data from multiple tables. You can use these features in a query to define exactly whatinformation will be shown. If you use a particular query on a repeated basis, you should considerturning that query into a custom view that can be quickly retrieved and displayed, as though it were asimple table.

ViewsViews enable you to select columns and rows for display from one or more tables, much as youmight do through a query. However, once you define a view, it becomes part of the database andyou can display its data much like you might display a table. For example, to list all rows in a viewnamed booklist, you would use the following syntax.SELECT *FROM booklistBecause views can be treated like a table, they are sometimes described as "virtual tables." However,unlike actual tables, Microsoft® SQL Server® 2017 doesn't store data in views. Views pull data fromrecords stored in a table, much like a query.

Figure 4-1: A sample view.

The table from which you retrieve records is called the source table. The example shows a viewnamed BookSalesOver200, with the ordnum, partnum, and qty columns from the Sales source table,as well as bktitle and slprice from the Titles table. It also includes a calculated column based on qty(from Sales) and slprice (from Titles).

94 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic A

Views

Emphasize to studentsthat views simply enablethem to view selectedrows and columns froma table; a view does notstore the data itself.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

You can work with BookSalesOver200 like a title, querying it and even changing data valuespresented through the view. Changes made to data through the view are recorded in the sourcetables, not in the view itself. Likewise, changes made to data in the source tables will be reflected inthe data shown in the view.

Note: To further explore the views included with SQL Server 2017, you can access the Spotlighton SQL Server Information Schema Views presentation from the Spotlight tile on theCHOICE Course screen.

The CREATE VIEW StatementIn SQL Server, you use the CREATE VIEW statement to create views. You assign a name to theview immediately after the CREATE VIEW statement. You then add a SELECT statement following theview name and the AS keyword. This SELECT statement retrieves and displays records in the form ofa virtual table. You can create a view based on a single table or multiple tables.There are different types of views you can choose from. These view types are detailed in thefollowing table.

Type of View Description

Simple views Creates a view based on a single table. Using this view, you can insert andupdate records in a source table or delete records from the source table.When inserting, updating, or deleting records through a simple view, youmight make changes that violate the condition you defined in the SELECTstatement when you created the view. For example, you might create aview that displays all customers who live in Rhode Island. If you update arow and change the state a customer lives in to Pennsylvania, SQL Serverwon't display that customer in the view. If you want to prevent users fromchanging data that then prevents SQL Server from displaying a row in theview, use the WITH CHECK OPTION clause after the SELECT statementwhen you create the view. The SELECT statement of simple views cannotcontain aggregate functions.

Complex views Creates a view based on multiple source tables. You cannot insert, update,or delete records in this type of view. You can create complex views basedon tables in other databases or even other database servers. You caninclude aggregate functions in the SELECT statement of complex views. Ifyou use an aggregate function, you must provide a name for the column inthe view. You define the name of the column as part of the CREATE VIEWstatement. You can also define specific column names if you want todisplay names that are different from the column names in the sourcetable.

Figure 4-2: A CREATE VIEW statement example.

In the example, the CREATE VIEW statement creates a view named BookSalesOver200 that containsthe partnum column from the Sales table and the bktitle, devcost, and slprice columns from the

SQL Querying: Advanced (Second Edition) | 95

Lesson 4: Working with Views | Topic A

You may want to showSpotlight on SQL ServerInformation SchemaViews from the CHOICECourse screen or havestudents navigate out tothe Course screen andwatch it themselves as asupplement to yourinstruction. If not, pleaseremind students to visitthe Spotlights for thiscourse on their CHOICECourse screen afterclass for supplementalinformation andadditional resources.

The CREATE VIEWStatement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Titles table. In addition, the CREATE VIEW statement defines column names that SQL Serverdisplays when you display the view instead of the column names from the tables. You can displaythe structure of a view by executing the sp_helptext view_name stored procedure.

EncryptionSQL Server includes support for encrypting the definition of a view. You should encrypt a view'sdefinition if you do not want users to be able to see how you defined the view. You might encrypt aview when you don't want users to be able to identify the structure of the source table(s) thatcomprise the view. When you encrypt a view, SQL Server cannot display its structure when you usethe sp_helptext view_name stored procedure. SQL Server displays the following message instead:

The syntax for encrypting a view is:CREATE VIEW viewnameWITH ENCRYPTIONAS SELECT column1, column2, column3FROM table1, table2

Schema BindingWhen you create a view, one of the options you can include is SCHEMABINDING. You useSCHEMABINDING to protect the source table on which you based the view. SCHEMABINDING preventsusers from modifying the source table on which you based a view because changes to the sourcetable's structure can affect the view's definition. When you use the SCHEMABINDING option, SQLServer does not permit you to make changes to the source table if they would affect a view. Instead,if you need to change the structure of the source table, you must first drop or change the view sothat it is no longer using the SCHEMABINDING option.

Figure 4-3: Sample code for a SCHEMABINDING statement.

In this example, the CREATE VIEW statement defines a view named sales_view with theSCHEMABINDING option. The view is based on the Customers table and displays only the custnamecolumn. When you use the SCHEMABINDING option, you must specify the two-part table name,which consists of the table's owner followed by the table name.

96 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic A

Encryption

Schema Binding

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

The TOP KeywordYou can use the TOP keyword followed by a number or a percentage in a SELECT statement tolimit the number of records SQL Server displays. You can retrieve a specific number of records byindicating a constant value. To retrieve a specific percentage of records, you must specify a constantvalue followed by the PERCENT keyword. If the SELECT statement in a CREATE VIEW statementcontains an ORDER BY clause, you must specify the TOP keyword with the SELECT statement.

Figure 4-4: Sample code for the TOP keyword.

This example creates a view named salesperf that displays the top 10 sales (based on the quantitysold) from the Sales table. Notice that you must use the ORDER BY clause in descending order to listthe records with the greatest quantity sold.The following code block shows the use of the TOP keyword along with the CREATE VIEW clause:CREATE VIEW viewname [(columnname1, columnname2, columnname3)]AS SELECT TOP value [PERCENT] SUM(columnname3) AS 'Colname',columnname2, columnname3FROM tablename1 [, tablename2]WHERE columnname4=columnname5GROUP BY columnname1, columnname2ORDER BY SUM(columnname3) DESC

Benefits and Disadvantages of ViewsBenefits of using database views include the following.• Helps to limit data access to specific users. You may not want a subset of sensitive data to

be queryable by all users. You can use a database view to expose only non-sensitive data to aspecific group of users.

• Can simplify complex queries. When you create a database view, you essentially wrap a querywithin an object that behaves like a table. The view can combine many underlying tables, andperform filtering of content. With a view, you can hide the complexity of underlying tables andSQL operations from end users and external applications.

• Provides a layer of cybersecurity. The database view provides extra security for a databasemanagement system. The database view allows you to create the read-only view to expose read-only data to specific users. Users can only retrieve data in read-only view but cannot update it. Adatabase view enables computed columns.

• Provides a good place to implement calculated columns. While you shouldn't implementcalculated columns directly in a table, a view is a more appropriate place to do so. When youquery data from the database view, the data of the computed column is calculated on the fly.

• Supports backward compatibility. Over time, you may need to redesign your tables to meetnew business requirements. To support backward compatibility, you can create a view to take theplace of the original table. The view can present the same columns and data types as the originaltable that was revised.

Disadvantages of using database views include the following.• May "break" if underlying tables change. When you create a view based on a table or tables

whose structure you change later on, you may have to revise the view to accommodate those

SQL Querying: Advanced (Second Edition) | 97

Lesson 4: Working with Views | Topic A

The TOP Keyword

Benefits andDisadvantages of Views

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

changes. You can use SQL Server's schema binding protection to prevent you from making suchchanges inadvertently.

• May be slow in some situations. Querying data from a view may be slow, depending on thecomplexity of the view, how the database is indexed, and other variables. Through careful design,you can avoid performance problems.

Guidelines for Creating a View

Note: All of the Guidelines for this lesson are available as checklists from the Checklist tile onthe CHOICE Course screen.

Follow these guidelines when creating a view.

Avoid Creating Performance Bottlenecks with ViewsCareless use of views may lead to performance problems in your database. Avoid creatingperformance problems by doing the following.• Limit the number of inner joins in your view definition. Inner joins slow down the

processing of a view, so use inner joins in a view only when most of the queries using the viewrequire data from the joined table. Consider creating multiple views, if necessary, so inner joinsare used only as needed.

• As much as possible, use only one view in a query. Avoid using one view as the base tablefor another view.

• Use indexing to your advantage. If you can create an index that returns data in the same orderneeded for a join within a view, then data can be pulled in without sorting, saving considerabletime.

Adhere to Limitations in the SELECT Statement for a ViewThere are some limitations on what tasks you can perform in the SELECT statement for a view.Follow these guidelines when you define a view.• Don't use an ORDER BY clause in the SELECT statement for a view unless you include the TOP

keyword followed by the number of rows to show.• Don't include a COMPUTE or COMPUTE BY clause in the view's SELECT statement.• Don't use aggregate functions such as AVG in the SELECT statement for a simple view.• Don't use the INTO keyword after the SELECT statement for a view. (Remember, you use

SELECT INTO to create a copy of a table and its data.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Create a View.

98 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic A

Guidelines for Creating aView

Point out that studentswill use indexes in thenext lesson.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 4-1Creating Views

ScenarioAt frequent intervals, you must generate a list of the top 20 books based on quantity sold. Youretrieve the part number, title, and total quantity sold for each book. You also frequently run a queryto search for books priced between $20 and $40, retrieving the book title, part number, and saleprice. To simplify the process of running these queries, you will create two views.

1. Launch SQL Server Management Studio, open a new query editor, and selectthe Pub2 database.a) If SQL Server Management Studio is not running, launch it and connect to the server.b) On the Standard toolbar, select New Query to open the Query Editor window.c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub2

database is selected.

2. Create a querya) Enter a query to display a list of medium-priced books as shown.

b) Execute the query and examine the results.

A list of medium-priced books is shown. There are 67 rows in the result.

3. Create a view named mediumprice based on the query.

SQL Querying: Advanced (Second Edition) | 99

Lesson 4: Working with Views | Topic A

Activity: Creating Views

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Insert two lines before the query as shown.

b) Execute the statements to create the view.

The results should show that the commands completed successfully.c) Write a SELECT statement to retrieve the view.

d) If SQL Server Management Studio's Intellisense feature is showing a red wavy line beneath

mediumprice, then select Edit→IntelliSense→Refresh Local Cache.e) Execute the query.

67 books are shown in the medium price range.f) Write and execute the sp_helptext mediumprice stored procedure to review the view definition.

4. Create a view named salesperf to generate the top 20 list of books sold.a) Clear the previous statement and enter a statement to create the salesperf view.

100 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Highlight just the query portion of the statement as shown.

c) Press F5 to execute the selected portion of the statement.

This shows the columns and rows the view will return.20 rows are returned, showing the top 20 books sold.

5. Create and test the view.a) Press End to deselect the highlighted text.b) Press F5 to execute the entire statement.c) Enter a new statement to test the view.

d) If SQL Server Management Studio's Intellisense feature is showing a red wavy line beneath

salesperf, then select Edit→IntelliSense→Refresh Local Cache.e) Execute the query.

The top 20 selling books are shown. You can now use this view as though it were a table.

SQL Querying: Advanced (Second Edition) | 101

Lesson 4: Working with Views | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 4-2Creating Views with Schema Binding

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioYou created a view to display a list of all customer names in the Customers table. But anotherperson on your team altered the schema of the source table, unwittingly breaking the view youcreated. To prevent such problems from occurring in the future, you decide to create the view sothat SQL Server prevents modifications to the source table.

1. Create a view named sales_view with schema binding on the Customerstable.a) In the query editor, clear the statement and enter a new statement as shown.

• This view will return a list of all customer names.• The SCHEMABINDING option will prevent any changes to underlying tables that will cause the

view to fail.b) Execute the statement.

2. Attempt to alter the structure of the Customers table.a) In the query editor, clear the statement and enter a new statement as shown.

This statement will attempt to modify the CustName column, changing its configuration fromnvarchar(60) to varchar(30) and making it not nullable.

b) Execute the statement.

102 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic A

Activity: Creating Viewswith Schema Binding

Point out that you mustspecify the two-parttable name (consistingof the table owner andthe table name itself)when you use theSCHEMABINDINGoption.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Observe the error message.

The statement failed because you attempted to modify the structure of a table that is schema boundto a view.

SQL Querying: Advanced (Second Edition) | 103

Lesson 4: Working with Views | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC BManipulate Data in ViewsAfter you create a view, you might need to manipulate the data displayed in the view. SQL Serverenables you to insert, modify, and delete rows while using a view. In this topic, you will learn how tomanipulate the data in views.

Data Manipulation through ViewsSQL Server includes support for inserting, modifying, and deleting data through views. You can usethe INSERT, UPDATE, and DELETE statements to work with data displayed in a view just as you canuse those same statements to work with a table's data. The syntax is identical with the exception thatyou use a view name in place of the table name.There are some limitations you can encounter when attempting to manipulate data through a view.These limitations include:• If you created the view using the WITH CHECK OPTION, you can't make changes to the view's

data that will violate the view's definition. For example, if you create a view that displays allbooks with a price between $20 and $30 and you use the WITH CHECK OPTION, you cannot usethe UPDATE statement to change a book's price to $35 because this change violates the definitionof the view.

• You can insert, modify, or delete data through a view only if the view is based on a single table.SQL Server does not permit you to manipulate data through a view based on multiple tables.

• If the base table for the view includes columns that don't permit null values and the view doesnot include those columns, you will receive an error when you attempt to add a row because youhave not provided values for those columns.

Data InsertionYou insert a row in a view by using the INSERT statement. Although you insert the row using theview, SQL Server actually stores the inserted row in the table on which the view is based. Here is thesyntax for the INSERT statement using a view:INSERT view_name(column1, column2, column3)VALUES (value for column1, value for column2, value for column3)

Figure 4-5: An example of inserting data through a view.

104 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic B

Data Manipulationthrough Views

Data Insertion

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

In the example, the INSERT statement inserts a new row using the ttl_view view. The new row has apart number of 78901, a title of "Object-Oriented Programming," and a sale price of $69.95.Although the INSERT statement uses the view name ttl_view, SQL Server actually inserts the rowinto the table on which the view is based: the Titles table.

Data ModificationYou can modify a row's contents through a view as long as your changes don't violate the view'sdefinition. Just as with the INSERT statement, SQL Server updates the table on which the view isbased. Keep in mind that you must include a WHERE clause to select the row(s) you want to modifyor the UPDATE statement will modify all rows in the table. Use this syntax to update a row through aview:UPDATE view_nameSET column1=valueWHERE search_condition

Figure 4-6: An example of modifying data through a view.

In this example, the UPDATE statement changes the title of the book with the part number of 78901to "Object-Oriented Programming Simplified."

Data DeletionFinally, you can delete rows through a view by using the DELETE statement. Be sure to use a WHEREclause to identify the row(s) you want to delete. Use this syntax to delete a row through a view:DELETE view_nameWHERE search_condition

Figure 4-7: An example of deleting data through a view.

SQL Querying: Advanced (Second Edition) | 105

Lesson 4: Working with Views | Topic B

Data Modification

Data Deletion

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

In this example, the DELETE statement deletes the row with the part number of 78901 using theview.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Manipulate Data in Views.

106 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 4-3Manipulating Data in Views

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioThe store manager of the Fuller & Ackerman Publishing bookstore has been getting reports fromsalespeople that a number of new titles are not listed in the database. The salespeople have compileda list of titles missing from the database, as shown in the following list.In addition, a salesperson let you know that the sale price of the book with part number 40256should be $30, not $35. The book with part number 40234 does not exist in the store, but is listed asavailable.Because customers view the part number, book title, and sale price when they use the EasySearchcomputer, the store manager wants you to implement these changes right away.Books containing erroneous information include the following.

Part Number Book Title Sale Price

40256 How to Play Violin (Intermediate) 35

40257 How to Play Violin (Advanced) 39

1. Insert the new books into the Titles table by using the mediumprice viewthat you created. Verify that you successfully added the rows.a) Clear the query editor, and enter the statements as shown.

These statements insert the two new books through the mediumprice view.

b) Execute the statements to insert the records.

SQL Querying: Advanced (Second Edition) | 107

Lesson 4: Working with Views | Topic B

Activity: ManipulatingData in Views

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Clear the query editor, and enter the query as shown.

d) Execute the SELECT statement, and verify that the two new rows are shown.

2. Change the sale price of the book with part number 40256 by using themediumprice view. Verify that your change succeeded.a) Clear the query editor, and enter the query as shown.

This query updates the sale price of the book with part number 40256 through the mediumpriceview.

b) Execute the query.c) Revise the statement to verify that you modified its sale price.

d) Execute the query.

The result should show a price of 30.

3. Delete the record for the book with part number 40234 using themediumprice view. Verify this change.

108 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Clear the query editor, and enter the query as shown.

This statement deletes the record with part number 40234.

b) Execute the query.c) Revise the statement to verify that you deleted the record.

d) Execute the query.

No titles are shown.

SQL Querying: Advanced (Second Edition) | 109

Lesson 4: Working with Views | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC CModify and Delete ViewsYou have created views and manipulated the data within the view. It's possible that you might needto change the structure of the view because of changing business needs. SQL Server enables you tomodify the structure of a view by using the ALTER VIEW statement. You can also delete a view byusing the DROP VIEW statement. In this topic, you will modify the view structure by adding anddeleting columns, and deleting views.

The ALTER VIEW StatementYou use the ALTER VIEW statement to modify the definition of a view. By defining a newSELECT statement with the ALTER VIEW statement, you modify the structure of the view. Youspecify the name of the view in the ALTER VIEW clause. Then, add a new SELECT statementfollowed by the AS keyword. You can optionally include the WITH CHECK OPTION clause in theALTER VIEW statement to have SQL Server verify that the data displayed by the view complies withthe WHERE clause (search condition) of your SELECT statement.

Figure 4-8: Sample code for an ALTER VIEW statement.

In the example, the ALTER VIEW statement modifies the bookview view and changes its SELECTstatement to include just the partnum and bktitle columns. In addition, the WHERE clause for theview configures it to display only those books with prices higher than $40.

The DROP VIEW StatementWhen you want to delete a view, you use the DROP VIEW statement. If you need to delete atable, SQL Server requires that you delete all views based on that table first. To delete a view, usethe DROP VIEW statement followed by the name of the view.

110 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic C

The ALTER VIEWStatement

The DROP VIEWStatement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Figure 4-9: Sample code for a DROP VIEW statement.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Modify and Delete Views.

SQL Querying: Advanced (Second Edition) | 111

Lesson 4: Working with Views | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 4-4Modifying and Deleting Views

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.

ScenarioTo monitor the performance of salespeople in the Fuller & Ackerman Publishing bookstore, youdeveloped a view named salesperf for the store manager that retrieves the representative ID, name,and total quantity sold by the top 10 salespeople.The store manager just announced that each of the top three salespeople will be rewarded with abonus based on their sales volume at the end of each month. The manager wants you to change theview named salesperf to list only the top three salespeople.In addition, the manager has decided to remove the medium price range view from the customerEasySearch software.

1. Copy the old view code.a) Clear the previous query and enter a new statement in the query editor as shown.

b) Execute the statement.

The statement used to create the view is shown in the result.

c) Right-click in the Results pane, and select Select All.d) Right-click in the Results pane, and select Copy.

112 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic C

Activity: Modifying andDeleting Views

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

e) Clear the code in the query editor, and press Ctrl+V to paste the text into the editor.

2. Revise the SQL to create an ALTER VIEW statement.a) Revise the statement as shown.

• Change CREATE to ALTER.• Change 20 to 3.

b) Execute the script.

3. Verify that the view functions correctly.a) Clear the statements and enter a new statement to verify that the view functions properly.

b) Execute the statement.

The view now returns only the top three books.

4. Drop the mediumprice view and verify that you deleted it successfully.

SQL Querying: Advanced (Second Edition) | 113

Lesson 4: Working with Views | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Enter the statement as shown to drop the mediumprice view.

b) Execute the query.c) Clear the text from the query editor, and enter the query as shown.

d) Execute the query.

The view has been removed successfully.

e) Close the Query Editor window without saving the query.

114 | SQL Querying: Advanced (Second Edition)

Lesson 4: Working with Views | Topic C

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SummaryViews enable you to display only certain columns, rows, or both. Thus, you can use views to manageexactly what information users can and cannot see. You will find that views provide a convenientway to hide confidential information from users or mask the complexity of a query.

How does your organization use views?A: Answers will vary, but might include that views enable you to easily generate output you can use for

reports that contain data from one or more tables. Using these reports makes data managementeasier than working with larger tables.

Does your organization use views to generate reports? Why?A: Answers will vary, but might include that, yes, it uses views extensively to generate reports because

views enable you to select only the data you need instead of working with huge tables.

Note: Check your CHOICE Course screen for opportunities to interact with your classmates,peers, and the larger CHOICE online community about the topics covered in this course orother topics you are interested in. From the Course screen you can also access availableresources for a more continuous learning experience.

SQL Querying: Advanced (Second Edition) | 115

Lesson 4: Working with Views |

Encourage students touse the socialnetworking toolsprovided on the CHOICECourse screen to followup with their peers afterthe course is completedfor further discussionand resources to supportcontinued learning.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Indexing DataLesson Time: 30 minutes

IntroductionHow SQL Server retrieves the data that satisfies a query can have a huge impact on yourdatabase server's performance, especially if you have very large tables. One of the strategiesyou can use to improve the efficiency of SQL Server is to create indexes to support yourmost frequently executed queries.

Lesson ObjectivesIn this lesson, you will create indexes on table columns and drop inefficient indexes. Youwill:

• Create indexes on table columns.

• Drop an index.

5

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC ACreate IndexesThe first step in optimizing the performance of your queries is to create indexes on your tables. Inthis topic, you'll learn how to create indexes by using the CREATE INDEX statement.

Indexes

Figure 5-1: An index can reduce the time needed to retrieve information.

Much of the work performed by a database server involves searching for particular records. In someways, this is analogous to the process you might follow to search for a particular passage of text in abook. Suppose you were searching a book for passages about "transactions." You might just flipthrough the book from front to back, scanning each page, looking for the word. Or you might usean indexing feature provided by the book to look up "transactions" and then jump directly to thespecific page where it appears. For example:• Table of Contents• Index• Glossary of Terms, including the page number where the term was first used• If a book is organized alphabetically (like a dictionary), it might provide thumb tabs along the

edges of the pagesBooks often provide multiple indexes like this—each optimized to help you find a different sort ofinformation quickly. Because indexes are sorted and organized for fast retrieval, if you're looking for

118 | SQL Querying: Advanced (Second Edition)

Lesson 5: Indexing Data | Topic A

Indexes

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a specific kind of information that the index is optimized to provide, it can be much quicker to usean index than to scan all the pages.When processing a query, Microsoft® SQL Server® normally retrieves data by performing a tablescan. A table scan means that SQL Server goes through a table one row at a time to find the rowsfor the results set of a query. Although computers process data very quickly, they do have limitationsthat become apparent when you require them to process massive amounts of data, such as youmight have in a very large, complex database.Just as a book index can help you find information quickly, a database index can help a databaseserver find information quickly when processing a query. Indexes can improve both theperformance of queries and the performance of your server as a whole. Just as using the index in theback of a book enables you to quickly find the information you need, so does an index enable SQLServer to quickly identify the information that satisfies a query.

Note: Each index takes up storage space. Since storage space, like all computing resources, islimited, you need to judiciously choose what you will index.

Query ExecutionYou can create an index on one or more columns in a table. The column on which you base anindex is called the index key. SQL Server stores the values that make up the index key in the index.When you execute a query for which SQL Server can use an index, it automatically uses the index toretrieve the query's results set. The index contains the contents of the index key column, along withrow pointers that point to the original rows in the table on which you based the index. If your queryselects columns that are not stored in the index, SQL Server uses the row pointers to retrieve thedata from the other columns.The database server attempts to use the most efficient method for executing a query. The databaseserver uses a query execution plan to describe how it executes a query. If you find that a query isexecuting slowly, you can refer to the query execution plan to see how the query is being processed,which might help you to identify where you need to make changes to speed up execution. To viewthe query execution plan, select Query→Display Estimated Execution Plan. A chart is shown,like the following.

Figure 5-2: Using an index to retrieve the results of a query.

You read a query execution plan from right to left. In this example, the query execution plan showsthat SQL Server uses an index named titles.idx_bktitle to retrieve the SELECT query's results set.

SQL Querying: Advanced (Second Edition) | 119

Lesson 5: Indexing Data | Topic A

Query Execution

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Types of IndexesSQL Server supports two types of indexes: clustered and nonclustered. With a clustered index, SQLServer stores the table itself in order by the clustered index key. By default, SQL Server creates atable's clustered index using the table's primary key. For example, earlier in the course, youconfigured the partnum column in the Titles table as the primary key for the table. When you addedthe primary key constraint, SQL Server automatically reorganized the table so that it stored the tablein order by the partnum column. If you do not define a primary key for a table, you can create aclustered index that defines the order in which SQL Server stores the table's rows.In contrast to a clustered index, SQL Server stores nonclustered indexes as separate databaseobjects. The contents of the index include the index key column(s) plus pointers to the original rowsin the table. When SQL Server uses a nonclustered index to satisfy a query, it retrieves the indexkeys from the index and then uses the row pointers to retrieve the rest of the data for a given set ofrows.You can configure both clustered and nonclustered indexes as unique. When you create an index asunique, you prevent SQL Server from storing identical values in the index key column(s). By default,SQL Server creates a unique clustered index for a table when you assign a primary key constraint tothat table.The following table describes the types of indexes you can create and the SQL statement you use tocreate them.

Type of Index Description

Clustered index Physically sorts the values in a column based on the index key values.You can define only one clustered index for a table. This type of index iseffective in organizing data in columns where a range of values is stored,such as employee IDs or serially numbered primary key values. Whenyou create a primary key, SQL Server automatically creates a clusteredindex on the primary key column. The syntax to create a clustered indexis:CREATE [UNIQUE] CLUSTERED INDEX indexnameON tablename(columnname1,[ columnname2])

Nonclustered index Does not physically sort the values in the table. Instead, SQL Serverstores the index key for each row in the table, along with a pointer to thetable row, in the index. You can define a maximum of 249 nonclusteredindexes for a table. The syntax to create a nonclustered index is:CREATE [UNIQUE] NONCLUSTERED INDEX indexnameON tablename(columnname1 [, columnname2])

The Query OptimizerYou can significantly improve the performance of SQL Server by reducing disk input/output (I/O)operations by implementing indexes. Keep in mind that in a computer, the slowest component istypically the hard disk. Thus, any strategy that minimizes how often a computer accesses the harddisk will improve an application's performance.When you execute a query, SQL Server uses a component called the query optimizer to generate anexecution plan for retrieving the data that satisfies the query. Choices available to the queryoptimizer include:• A table scan. With a table scan, SQL Server examines or scans every row in the table and

determines whether each row belongs in the results set. A table scan uses the most disk I/O andhas the greatest impact on the server's performance.

• An index scan. With an index scan, SQL Server examines every row in the index to identifywhich rows belong in the results set. If necessary, SQL Server then uses the record pointers in

120 | SQL Querying: Advanced (Second Edition)

Lesson 5: Indexing Data | Topic A

Types of Indexes

The Query Optimizer

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

the index to retrieve the rest of the data for the rows. For example, if you execute the querySELECT bktitle, partnum FROM titles, and you created an index on the bktitle column ofthe Titles table, the query optimizer can use the index to retrieve the title of each book and thenuse the record pointers in the index to retrieve the part number columns from the table itself. Anindex scan uses less system resources than a table scan but is more resource-intensive than anindex seek.

• An index seek. With an index seek, SQL Server searches the index to retrieve only certain rows.The query optimizer chooses an index seek only when you use a SELECT query with a WHEREclause. If possible, SQL Server attempts to satisfy the results of the query from the index alone.SQL Server can satisfy the results of a query from only the index if the index keys contain thecolumns you specify after the SELECT statement. For this reason, when you design the indexesfor a table, you should first consider the types of queries you will execute most often. Creatingindexes to support these queries will improve your server's overall performance.

Figure 5-3: The query optimizer choices.

Note: To further explore execution plans, you can access the Spotlight on SQL ServerExecution Plans presentation from the Spotlight tile on the CHOICE Course screen.

The CREATE INDEX StatementYou use the CREATE INDEX statement to create a clustered or nonclustered index on one ormore table columns. The columns on which you create the index become the index's keys. Definethe name of the index immediately after the CREATE INDEX statement. Next, you use the ONkeyword followed by the name of the table that contains the column(s) on which you want to createthe index. Finally, you write the name of the column or columns on which you want to create theindex enclosed within parentheses. If you specify multiple columns, you must separate the nameswith commas.

SQL Querying: Advanced (Second Edition) | 121

Lesson 5: Indexing Data | Topic A

You may want to showSpotlight on SQL ServerExecution Plans fromthe CHOICE Coursescreen or have studentsnavigate out to theCourse screen andwatch it themselves as asupplement to yourinstruction. If not, pleaseremind students to visitthe Spotlights for thiscourse on their CHOICECourse screen afterclass for supplementalinformation andadditional resources.

The CREATE INDEXStatement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.Figure 5-4: A CREATE INDEX statement example.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Create Indexes.

122 | SQL Querying: Advanced (Second Edition)

Lesson 5: Indexing Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 5-1Creating Indexes

ScenarioTo improve performance of the database, you will index tables that you frequently access. You willcreate the following indexes.

• Titles table:• Named idx_title• Nonclustered• Bktitle, slprice columns

• Sales table:• Named idx_sales• Nonclustered• Custnum, partnum, repid columns

• Titles table:• Named idx_partnum• Unique index• Partnum column

1. Launch SQL Server Management Studio, open a new query editor, and selectthe Pub2 database.a) If SQL Server Management Studio is not running, launch it and connect to the server.b) On the Standard toolbar, select New Query to open the Query Editor window.c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub2

database is selected.

2. Create a nonclustered index on the frequently queried columns of the Titlestable. Verify that you successfully created the index.a) In the query editor, enter the statement shown here.

• The index will be named idx_title.• The index will be nonclustered.• You will index the Titles table using the bktitle and slprice columns as the index keys.• The goal is to speed up queries that retrieve data from bktitle and/or slprice columns, especially

when the table has many rows of data.b) Execute the statement to create the index.

SQL Querying: Advanced (Second Edition) | 123

Lesson 5: Indexing Data | Topic A

Optionally, use morestructured index namesfor more clarity (butmore tedious typing forstudents) such asidx_T_BktitleSlprice,idx_S_CustnumPartnumRepid, andidx_T_partnum.

Point out that a queryinvolving small tablessuch as those in thiscourse may actually runslower with extraoverhead of an index.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Clear the query editor and enter the following statement to verify you successfully created the index.

d) Execute the statement.e) In the Results pane, observe the index information for the Titles table. You can see that you created

a nonclustered index on the bktitle plus slprice columns.

3. Create a nonclustered index on the frequently used columns of the Salestable. Verify that you successfully created the index.a) Clear the query editor and enter the statement shown here.

• The index will be named idx_sales.• The index will be nonclustered.• You will index the Sales table using the custnum, partnum, and repid columns as the index keys.

b) Execute the CREATE INDEX statement to create the index.c) Clear the query editor and enter the following statement to verify you successfully created the index.

124 | SQL Querying: Advanced (Second Edition)

Lesson 5: Indexing Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

d) Execute the statement and examine the result.

4. Create a unique index on the partnum column of the Titles table. Verify thatyou successfully created the index.a) Clear the query editor and enter the statement shown here.

• The index will be named idx_partnum.• You will index the Titles table using the partnum column as the index key.

b) Execute the CREATE INDEX statement to create the idx_partnum index.c) Clear the query editor and enter the following statement to verify you successfully created the index.

SQL Querying: Advanced (Second Edition) | 125

Lesson 5: Indexing Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

d) Execute the statement and examine the result.

126 | SQL Querying: Advanced (Second Edition)

Lesson 5: Indexing Data | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC BDrop IndexesThere is a cost to SQL Server for maintaining indexes. In essence, because SQL Server stores theindex keys in the index, indexes duplicate the data stored in your tables. After analyzing the types ofqueries users execute on the server, you might find that the query optimizer is not utilizing theindex, or the cost of maintaining an index exceeds the benefit it offers. For this reason, you need toknow how to delete indexes that you no longer need.

The DROP INDEX StatementYou use the DROP INDEX statement to delete an index created on a table. You use thisstatement to delete all clustered indexes except for a clustered index created when you defined aprimary key or UNIQUE constraint for the table. To delete a clustered index created for a primary keyor UNIQUE constraint, you must drop the constraint, not the index. To delete an index, use DROP INDEX followed by the table name on which you based the index, a period, and then the name youassigned to the index. If you aren't sure of the name of an index, execute sp_help table_name toobtain a list of the indexes defined on the table.

Figure 5-5: A DROP INDEX statement example.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Drop Indexes.

SQL Querying: Advanced (Second Edition) | 127

Lesson 5: Indexing Data | Topic B

The DROP INDEXStatement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 5-2Dropping Indexes

Before You BeginYou have launched SQL Server Management Studio and connected to the server. You haveselected the Pub2 database from the Available Databases list. A query editor is open.You have performed the preceding activity in this lesson to create indexes.

ScenarioYou have an index in your database that you no longer need. To save room in the database, you willdrop it from the database.

Drop the index named idx_sales from the Sales table. Verify that yousuccessfully deleted the index.a) Type the following query to delete the idx_sales index:

b) Execute the DROP INDEX statement to drop the index.c) Clear the query editor and enter the following statement to verify you successfully dropped the

index.

128 | SQL Querying: Advanced (Second Edition)

Lesson 5: Indexing Data | Topic B

Activity: DroppingIndexes

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

d) Execute the statement, and examine the result, scrolling if necessary.

There is no longer an index on this table.

e) Close the Query Editor window without saving the query.

SQL Querying: Advanced (Second Edition) | 129

Lesson 5: Indexing Data | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SummaryYou can create and drop indexes as your organization's business requirements change. You useindexes to optimize the performance of the queries your users execute most often.

How effective do you think indexing will be in speeding up record retrieval in thedatabases maintained by your organization?A: Answers will vary, but might include that the main benefit of indexing is fast retrieval of data.

Depending on the volume of data, you can optimize the performance of your SQL environment byimplementing indexes.

Which index type might you implement on a table with employee data for yourorganization?A: Answers will vary, but might include that in a large organization with many employees, the most

frequent query of an employee table might be one that uses employees' Social Security numbers. Ifso, you should create a clustered index on employees' Social Security numbers to optimize theperformance of the most frequent query.

Note: Check your CHOICE Course screen for opportunities to interact with your classmates,peers, and the larger CHOICE online community about the topics covered in this course orother topics you are interested in. From the Course screen you can also access availableresources for a more continuous learning experience.

130 | SQL Querying: Advanced (Second Edition)

Lesson 5: Indexing Data |

Encourage students touse the socialnetworking toolsprovided on the CHOICECourse screen to followup with their peers afterthe course is completedfor further discussionand resources to supportcontinued learning.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Managing TransactionsLesson Time: 25 minutes

IntroductionSome database transactions must be accomplished through more than one SQL statement.If a problem occurs at any point in the transaction, you need to roll back each step of theentire transaction to get the database back to its original state. SQL provides features thatenable you to accomplish this.

Lesson ObjectivesIn this lesson, you will manage transactions. You will:

• Create and roll back transactions.

• Commit transactions.

6

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC ADefine TransactionsAt times, you may need to execute a series of SQL statements to complete a single objective, such asrecording a sale, in which you might update one table to reduce the amount of items in inventory,and then update another table to record the sale. If any of the statements fail, you may find itnecessary to "undo" all of the statements that preceded it. The transaction functionality enables youto provide an "undo" capability for one or more SQL statements.

TransactionsSome database updates may involve a transaction, a sequence of SQL statements that must becompleted to accomplish a single logical unit of work. For example, suppose the publishing databasewere to include a table named Inventory, which contains the part number for each book title andthe number of books with that title currently held in the shipping warehouse.Suppose the Inventory table shows that 8 copies of the 40897 book (Mythologies of the World) arecurrently in stock. Then suppose that a bookstore orders copies of that book, and you need toconduct an SQL transaction to fulfill the sale. You might conduct the transaction something likethis.

Problems encountered in Step 3 might include such things as:• The number of books requested to fulfill the sale exceed the number of books in inventory.• The requested part number does not exist in either table.• Any of the data provided for the new Sales record is not in the correct form.

Note: Consider using BEGIN TRAN even for some situations involving a single statement, toprovide an "undo" capability for your SQL statements. If you enter a typo and see results thatyou didn't intend, you can roll back the statements that follow BEGIN TRAN.

132 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions | Topic A

Transactions

Point out that in practice,actual databasetransactions are oftenmuch more complexthan this simpleexample.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACID PropertiesTo ensure that data quality is maintained when database transactions are conducted, experts indatabase design have identified four principles that database analysts, administrators, andprogrammers should follow when conducting database transactions, called ACID properties afterthe first initial of each quality.

Item Description

Atomicity Transactions should be atomic. In other words, to be consideredcomplete, they can't be broken down into smaller units of work. If allparts of the transaction can't be performed, then no part of thetransaction should be performed.

Consistency All data must be in the correct state at the end of the transaction. Forexample, constraints that you applied (primary key, uniqueness, checkconstraints, etc.) must be met, data types must be correct, and so forth. Ifnot, then no part of the transaction should be performed.

Isolation When multiple transitions are requested at the same time, they should bequeued by the system and completed in sequence. No part of anytransaction should be affected by any other transaction occurring at thesame time. This is sometimes called serialization because transactionsoccur in sequence, and do not overlap.

Durability Once a transaction is finished, its effects should persist—even in theevent of a system failure, unless of course they are overwritten by asubsequent transaction.

Database servers provide various features to help enforce these qualities, but SQL analysts,administrators, and programmers also need to take these principles into account as they work. Forexample, you should start and end transactions at points that enforce the logical consistency of thedata, using transaction management features provided by SQL.

Protection for Simultaneous Database AccessTransactions can also help you deal with problems caused by working on a multiple user system.Database servers are typically implemented as multiple user systems. At any time, various users maybe viewing data through a desktop application, web application, or an SQL console like SQL ServerManagement Studio, for example. At the same time, other users may be adding, revising, or deletingdata. In many cases, all of this simultaneous access is problem-free. The database server handlesrequests as they come in. If one user changes a record in a table, the next user that views that tablewill see the results of that change.

Transaction ManagementOne of the strategies you can use to enforce ACID properties is to explicitly mark the beginning andthe end of transactions. By explicitly marking the beginning of a transaction, if an error occurs orthe power fails, you can easily undo the transaction by rolling it back. You use transactions whenyou want a query's changes to be atomic: either all the changes succeed, or they all fail.Implement transactions by using the BEGIN TRANSACTION statement. After you've made thenecessary changes and no errors occur, you use the COMMIT TRANSACTION statement. On the otherhand, if an error occurs, you can undo your changes by executing the ROLLBACK TRANSACTIONstatement.A transaction is a collection of SQL statements that you execute as a single unit. Use the BEGIN TRANSACTION or BEGIN TRAN statement to mark the beginning of a transaction, followed by anoptional name for the transaction. Next, enter your SQL statements you want to execute as part of

SQL Querying: Advanced (Second Edition) | 133

Lesson 6: Managing Transactions | Topic A

ACID Properties

TransactionManagement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

the transaction. Finally, you complete the transaction by adding a COMMIT TRANSACTION orCOMMIT TRAN statement.The basic syntax for transactions is:BEGIN TRAN [<tran_name>] <statements that change data or design>COMMIT TRAN [<tran_name>] <or>BEGIN TRAN [<tran_name>] <statements that change data or design>ROLLBACK TRAN [<tran_name>]

Figure 6-1: The top transaction is committed, and the bottom one is rolled back.

In the top example, the BEGIN TRAN statement creates a transaction named salesPlaceOrder. TwoSQL statements are then performed, affecting two different tables. When ROLLBACK TRAN isexecuted, the effects of the two SQL statements within the transaction are reversed, as though theynever happened.The bottom example is similar, except that the transaction is committed at the end, so the effects ofthe two SQL statements within the transaction persist after the transaction concludes.Once a transaction begins, SQL queries issued by other users on the same database are notcompleted until the transaction ends—by being either committed or rolled back. Then any pendingqueries will be executed by the database server.

The ROLLBACK TRAN StatementIf a problem occurs during a transaction, you use the ROLLBACK TRAN statement to cancel thetransaction. SQL Server rolls back or undoes all of the changes made by the transaction.

134 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Note: Transaction processing is useful in conjunction with stored procedures. To furtherexplore programming stored procedures, you can access the Spotlight on Stored Procedurespresentation from the Spotlight tile on the CHOICE Course screen.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Create Transactions.

SQL Querying: Advanced (Second Edition) | 135

Lesson 6: Managing Transactions | Topic A

You may want to showSpotlight on StoredProcedures from theCHOICE Course screenor have studentsnavigate out to theCourse screen andwatch it themselves as asupplement to yourinstruction. If not, pleaseremind students to visitthe Spotlights for thiscourse on their CHOICECourse screen afterclass for supplementalinformation andadditional resources.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 6-1Beginning and Rolling Back a Transaction

Data FileC:\O94019Data\Managing Transactions\Create_Inventory.sql

ScenarioWeb developers on your team have begun working on a web application that sales representativescan use to place book orders. You are helping them prepare the database to record salestransactions. You will start by adding an Inventory table to keep track of the number of booksavailable for order. Then you will examine how the sales transactions should be recorded in thedatabase by manually updating the tables involved in a sale.

1. Launch SQL Server Management Studio, open a new query editor, and selectthe Pub2 database.a) If SQL Server Management Studio is not running, launch it and connect to the server.b) On the Standard toolbar, select New Query to open the Query Editor window.c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub2

database is selected.

2. Use SQL to create and populate an Inventory table.a) Clear all code from the query editor, and select Edit→Insert File as Text.b) Navigate to C:\O94019Data\Managing Transactions.c) Select Create_Inventory.sql, and select Open.

136 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions | Topic A

Activity: Beginning andRolling Back aTransaction

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

d) Examine the statements in the query editor.

• The CREATE TABLE statement creates a table named Inventory.• The Inventory table will contain two columns, partnum and bookcount.• The partnum column provides a reference to the books in the Titles and Sales tables, which

have corresponding partnum columns.• The bookcount column holds an integer representing the number of books in stock at the

shipping warehouse.• A constraint on the bookcount column does not allow NULL values.• A CHECK constraint on the bookcount column does not allow values less than zero.• The INSERT INTO statement populates the new table with bookcount values for each partnum

in Titles.e) Execute the statements.

93 rows are created.f) Right-click the database icon shown at the top of the Object Explorer, and select Refresh to refresh

the list.g) Expand the Databases folder, the Pub2 database, and the Tables folder.

The Inventory table should now appear in the list.

3. Plan a Sales transaction.

SQL Querying: Advanced (Second Edition) | 137

Lesson 6: Managing Transactions | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Clear all code in the query editor, and write the SQL as shown, to view data in the Inventory andSales tables.

Note: The editor may show a red wavy underline beneath the Inventory tabletitle because the table was only recently created. The statements shouldnonetheless execute correctly. To force the editor to immediately refresh itscache and recognize the table, select Edit→IntelliSense→Refresh LocalCache.

b) Execute the statements.

When you conduct a sales transaction, you will need to:• Create a new order in Sales, specifying the required quantity of the order.• Reduce the bookcount for the corresponding partnum in Inventory.• If any part of the transaction fails, roll back the entire transaction.• If all parts of the transaction succeed, then commit the transaction.

4. Show inventory and sales records for book number 40897.

138 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) Add a WHERE clause to both statements as shown, and execute the statements.

• There are 8 books in inventory.• Over time, only one order has been placed for the book. 170 books were ordered on April 9,

2017.

5. Write SQL to conduct a sales transaction.a) Open a new query editor window, and from the Available Databases list, select Pub2.

SQL Querying: Advanced (Second Edition) | 139

Lesson 6: Managing Transactions | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

b) Write the SQL as shown.

• The BEGIN TRAN statement starts a transaction named salesPlaceOrder.• The INSERT INTO statement creates a new sales order in the Sales table.• The UPDATE statement attempts to subtract a quantity of 10 from the book count for book 40897.

(This will fail, as there are only 8 books in inventory.)• Depending on the results of the first two statements, you will execute either COMMIT TRAN or

ROLLBACK TRAN to commit the statements if they succeed, or roll them back if any part of thestatements fail.

6. Arrange the layout so you can see both query editors at the same time.a) Right-click the tab for the active query editor and select New Vertical Tab Group.

The two query editors now appear side-by-side.

7. Begin the transaction.

140 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) In the query editor for the salesPlaceOrder transaction, select just the lines shown here.

b) Execute the selected lines.

An error message is shown.(1 row affected)Msg 547, Level 16, State 0, Line 7The UPDATE statement conflicted with the CHECK constraint "CK__Inventory__bookc__4E53A1AA". The conflict occurred in database "Pub2", table "dbo.Inventory", column 'bookcount'.The statement has been terminated.• The UPDATE statement failed because of the CHECK constraint on the bookcount. (No value

less than zero is allowed in bookcount.)

SQL Querying: Advanced (Second Edition) | 141

Lesson 6: Managing Transactions | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Return to the query editor containing the SELECT statements, and execute the query.

• A busy indicator is shown in the lower left.• No results are shown in the Results pane.• The queries cannot execute until the salesPlaceOrder transaction has completed, because the

transaction still has a lock on the tables.

8. Roll back the transaction.a) Return to the tab for the salesPlaceOrder transaction, and select ROLLBACK TRAN.

b) Execute the selected statement to roll back the transaction.

142 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Examine the tab containing the SELECT queries.

• When you issued the ROLLBACK TRAN command, the salesPlaceOrder transaction was

ended. The database server then unlocked the tables, enabling the pending queries to execute.• From the results of the SELECT queries, you can see that the bookcount for partnum 40897 is

still 8, and there is still only one sale for that book in the Sales database, so it seems that thetransaction was successfully rolled back.

SQL Querying: Advanced (Second Edition) | 143

Lesson 6: Managing Transactions | Topic A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOPIC BCommit TransactionsIn the last topic, you created and rolled back transactions. When you are ready to write thetransactions to a database, you can commit the transactions. In this topic, you will committransactions.When you use an important command in Windows®, it prompts you to confirm that you want toexecute the command. For example, when you delete all the files in a folder, Windows prompts youto confirm the deletion. Similarly, when you execute a set of transactions, SQL enables you toconfirm you want to save your changes by using the COMMIT TRAN statement.

The COMMIT TRAN StatementWhen you execute a transaction, you use the COMMIT TRAN statement to save the datamodifications made by the SQL statements within the transaction. The COMMIT TRAN statementsaves the data modifications made by all SQL statements executed after the BEGIN TRAN statement.If you assigned a name to the transaction in the BEGIN TRAN statement, you must put the name ofthe transaction after the COMMIT TRAN statement. After you execute the COMMIT TRAN statement fora transaction, you cannot roll back the data modifications made by the SQL statements in thetransaction.

Figure 6-2: The COMMIT TRAN statement.

Access the Checklist tile on your CHOICE Course screen for reference information andjob aids on How to Commit Transactions.

144 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions | Topic B

The COMMIT TRANStatement

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

ACTIVITY 6-2Beginning and Committing a Transaction

Before You Begin• Ensure SQL Server Management Studio is open.• On the Standard toolbar, select New Query.• On the SQL Editor toolbar, in the Database drop-down list, ensure that the Pub2 database is

selected.

ScenarioYou will try to perform the sales transaction again, this time using a quantity of books that areavailable in inventory. If the SQL statements succeed, you will commit the query.

1. Revise the order to a quantity that can be fulfilled by available inventory.a) In the query editor for the salesPlaceOrder transaction, change the two 10 values to 5, as shown

here.

2. Begin the transaction.

SQL Querying: Advanced (Second Edition) | 145

Lesson 6: Managing Transactions | Topic B

Activity: Beginning andCommitting aTransaction

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

a) In the query editor for the salesPlaceOrder transaction, select just the lines shown here.

b) Execute the selected lines.

The INSERT INTO and UPDATE statements both completed successfully.

c) Return to the query editor containing the SELECT statements, and execute the query.No message is returned, and the busy indicator is shown. The statements can't execute until thesalesPlaceOrder has been committed, which will remove the lock from the affected tables.

3. Commit the transaction.a) Return to the tab for the salesPlaceOrder transaction, and select COMMIT TRAN.b) Execute the selected statement to commit the transaction.

The command completed successfully.

146 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions | Topic B

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

c) Examine the tab containing the SELECT queries.

• As soon as you committed the transaction, the SELECT queries were able to execute.• From the results of the SELECT queries, you can see that the bookcount for partnum 40897 is

now 3, and there are now two sales for that book in the Sales database, so the transaction wassuccessfully committed.

SQL Querying: Advanced (Second Edition) | 147

Lesson 6: Managing Transactions | Topic B

If you have time andstudents are interested,replace thesalesPlaceOrdertransaction script withthe "Activity 6-1 Bonus"script from C:\094019Data\ManagingTransactions\Solution\Snippets.sql, and showhow transactions can beincorporated within aTRY CATCH routine toautomatically roll back ifthe quantity is too large.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SummaryYou create and commit transactions to make sure that all the changes within a query completesuccessfully, or you roll back transactions to make sure that all of the changes are reverted. By usingtransactions, you ensure that the data in your database is valid and consistent across all tables.

How do you think you might implement transactions in your organization?A: Answers will vary, but might include that you might implement transactions as part of error-checking

within stored procedures.

What benefit does using transactions offer you?A: Answers will vary, but might include that using transactions enables you to ensure that a set of

changes either all succeed or all fail, thus enabling you to ensure the accuracy of the data in yourdatabase.

Note: Check your CHOICE Course screen for opportunities to interact with your classmates,peers, and the larger CHOICE online community about the topics covered in this course orother topics you are interested in. From the Course screen you can also access availableresources for a more continuous learning experience.

148 | SQL Querying: Advanced (Second Edition)

Lesson 6: Managing Transactions |

Encourage students touse the socialnetworking toolsprovided on the CHOICECourse screen to followup with their peers afterthe course is completedfor further discussionand resources to supportcontinued learning.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Course Follow-UpOrganizations use SQL databases to store one of their most precious resources: data. Organizationsuse their data to track customers' sales, monitor inventory, and design marketing strategies. Tosupport these activities, you must know how to not only query the data, but also how to performtasks such as creating and populating tables, managing indexes to optimize performance, andimplementing views to simplify users' access to data.In this course, you used SQL statements and their clauses to perform a number of complex tasks.You used subqueries to retrieve and display records. You inserted, updated, and deleted rows intables using advanced querying techniques. In addition, you modified the structure of tables in adatabase. By using views, you displayed specific parts of a table and multiple tables. You alsoindexed the columns in a table to streamline the performance of SQL Server. Finally, you created,saved, and rolled back transactions; you used transactions to ensure that SQL Server saves either allyour changes or none of your changes. Implementing transactions ensures the validity of yourdatabase.

What's Next?You are encouraged to explore SQL Querying: Advanced (Second Edition) further by activelyparticipating in any of the social media forums set up by your instructor or training administratorthrough the Social Media tile on the CHOICE Course screen.

SQL Querying: Advanced (Second Edition) | 149

Course Follow up

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

The Pub2 DatabaseThe database used in this book, called the Pub2 database, is being used in a hypotheticalbook publishing company called Fuller & Ackerman Publishing. The following tablesconstitute the Pub2 database.• The Customers table describes each of Fuller & Ackerman Publishing's customers.• The Sales table describes each book sale.• The Slspers table describes each sales representative working at Fuller & Ackerman

Publishing.• The Titles table describes each book produced by Fuller & Ackerman Publishing.• The Obsolete_Titles table describes all books that are out of print.• The Potential_Customers table describes any possible new customers for Fuller &

Ackerman Publishing.

The Customers Table

Column Name Data Type Length Description

custnum nvarchar 10 The customer number for each client.Each customer is assigned a uniquecustomer number.

referredby nvarchar 10 The customer number of the client whoreferred this potential customer to Fuller& Ackerman Publishing.

custname nvarchar 60 The customer’s name, or business name.

address nvarchar 50 The customer’s street address.

city nvarchar 40 The city in which the customer resides.

state nvarchar 4 The state in which the customer resides.

zipcode nvarchar 24 The state’s zip code.

repid nvarchar 6 The customer’s sales representative’sidentification number.

The Sales Table

Column Name Data Type Length Description

ordnum nvarchar 10 The order number for each book sale.Each sales order is assigned a uniqueorder number.

sldate smalldatetime 4 The date of sale.

qty int 4 The number of books ordered.

A

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Column Name Data Type Length Descriptioncustnum nvarchar 10 The customer number for the customer

purchasing books.

partnum nvarchar 10 The part number of the book beingordered.

repid nvarchar 6 The sales representative responsible forthe sale.

The Slspers Table

Column Name Data Type Length Description

repid nvarchar 6 The identification number for eachsalesperson. Each sales representative isassigned a unique identification number.

fname nvarchar 20 The first name of the sales representative.

lname nvarchar 40 The last name of the sales representative.

commrate float 8 The sales representative’s commission rate.

The Titles Table

Column Name Data Type Length Description

partnum nvarchar 10 The part number for each book publishedby Fuller & Ackerman. Each book isassigned a unique part number.

bktitle nvarchar 80 The title of the book.

devcost money 8 The development cost of the book.

slprice money 8 The sale price of the book.

pubdate smalldatetime 4 The date when the book was published.

The Obsolete_Titles Table

Column Name Data Type Length Description

partnum nvarchar 10 The part number for each book consideredobsolete.

bktitle nvarchar 80 The title of the obsolete book.

devcost money 8 The development cost of the obsolete book.

slprice money 8 The price of the book.

pubdate smalldatetime 4 The date when the book was published.

The Potential_Customers Table

Column Name Data Type Length Description

custnum nvarchar 10 A unique number assigned for the potentialcustomer.

152 | SQL Querying: Advanced (Second Edition)

Appendix A : The Pub2 Database |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Column Name Data Type Length Descriptionreferredby nvarchar 10 The customer number of the client who

referred this potential customer to Fuller &Ackerman Publishing.

custname nvarchar 60 The potential customer’s name, or businessname.

address nvarchar 50 The potential customer’s street address.

city nvarchar 40 The city in which the potential customerresides.

state nvarchar 4 The state in which the potential customerresides.

zipcode nvarchar 24 The potential customer’s zip code.

repid nvarchar 6 The identification number of the salesrepresentative in the potential customer’sarea.

SQL Querying: Advanced (Second Edition) | 153

Appendix A : The Pub2 Database |

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Mastery Builders

Mastery Builders are provided for certain lessons as additional learning resources for thiscourse. Mastery Builders are developed for selected lessons within a course in cases whenthey seem most instructionally useful as well as technically feasible. In general, MasteryBuilders are supplemental, optional unguided practice and may or may not be performed aspart of the classroom activities. Your instructor will consider setup requirements, classroomtiming, and instructional needs to determine which Mastery Builders are appropriate for youto perform, and at what point during the class. If you do not perform the Mastery Buildersin class, your instructor can tell you if you can perform them independently as self-study,and if there are any special setup requirements.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Mastery Builder 1-1Using Subqueries to Perform AdvancedQuerying

Activity Time: 15 minutes

ScenarioThe top management of the Fuller & Ackerman Publishing bookstore chain has beenmonitoring the progress of sales in the store. The financial results of the bookstorechain show that the store has performed exceedingly well. Management wants toreward its employees for their contributions, and has decided to give a bonus to allemployees.In addition, the top performer from the Sales department is to be rewarded with aspecial bonus and a raise. The vice president of sales wants you to identify the salesrepresentative who has sold the most copies of books for the year. Use the Sales andSlspers tables to generate the required output.To identify the column names in the table, refer to Appendix A.

Note: The file C:\094019Data\Using Nested Queries\Solution\Using NestedQueries.sql contains one possible solution for these tasks. Try to perform thesetasks on your own before you refer to the solution file.

1. If SQL Server Management Studio is not running, launch it andconnect to the server. Open a new query editor window, and fromthe Available Databases list, select Pub2.

2. Determine the logic to write a subquery that generates informationon the sales representatives who have sold the maximum numberof copies.

3. Frame the outer query to display the representative ID, first name,and last name of each sales representative.

4. Frame the inner levels of queries and execute the subquery togroup records by repid.

5. Execute the query. Kent Allard is the sales representative who hassold the most copies of books for the year.

6. Close the Query Editor window without saving the query.

156 | SQL Querying: Advanced (Second Edition)

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Mastery Builder 2-1Manipulating Table Data

Activity Time: 15 minutes

ScenarioYou insert the details of an old book into the Obsolete_titles table. Its data values are:• partnum: 39999• bktitle: Learn to Play the Violin• devcost: 5000• slprice: 45• pubdate: 2010-05-11Later, you realize that you have entered the book title wrong. The book title should be "Learn toPlay the Mandolin." So, you modify this record by replacing the wrong book title with the correctone.After a few months, you learn that this book has no value in the market and you decide to removethe title from the Obsolete_titles table.

Note: The file C:\094019Data\Manipulating Table Data\Solution\Manipulating Table Data.sqlcontains one possible solution for these tasks. Try to perform these tasks on your own beforeyou refer to the solution file.

1. If SQL Server Management Studio is not running, launch it and connect to theserver. Open a new query editor window, and from the Available Databaseslist, select Pub2.

2. Insert the record for the book into the Obsolete_titles table and verify whetherthe record is inserted into the table.

3. Change the book title to "Learn to Play the Mandolin", and verify whetheryou've successfully changed the record.

4. Delete the record and verify that you deleted it successfully.

SQL Querying: Advanced (Second Edition) | 157

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

5. Close the Query Editor window without saving the query.

158 | SQL Querying: Advanced (Second Edition)

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Mastery Builder 3-1Manipulating Table Structure

Activity Time: 15 minutes

ScenarioThe Fuller & Ackerman Publishing bookstore store manager wants to hire several people on acontract basis for a short period during the holidays. The store manager wants you to ensure thatthe database contains information on the contract ID, first name, last name, and salary of thecontractors.You need to create a table called Contractors with the table structure given. After creating the table,you want to ensure that each record is unique and that the salary value for a contractor is alwaysgreater than zero. You have also been instructed by the SQL Server administrator to delete theContractors table from the database after the holidays when the contract expires.The columns you must insert include:• ctrid varchar (5) NOT NULL• fname varchar (10)• lname varchar (10)• salary money

Note: The file C:\094019Data\Manipulating Table Structure\Solution\Manipulating the TableStructure.sql contains one possible solution for these tasks. Try to perform these tasks on yourown before you refer to the solution file.

1. If SQL Server Management Studio is not running, launch it and connect to theserver. Open a new query editor window, and from the Available Databaseslist, select Pub2.

2. Create the Contractors table based on the column information provided.Verify that you successfully created the table.

3. Add a constraint to the table to ensure the uniqueness of each record. Verifythat you added the PRIMARY KEY constraint.

SQL Querying: Advanced (Second Edition) | 159

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

4. Add a constraint to prevent salary values below zero from beingstored in the table. Verify that you added the CHECK constraint.

5. Drop the table and verify that you successfully dropped it.

6. Close the Query Editor window without saving the query.

160 | SQL Querying: Advanced (Second Edition)

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Mastery Builder 4-1Working with Views

Activity Time: 15 minutes

ScenarioTo celebrate the 10th anniversary of the bookstore, Fuller & Ackerman Publishing plans to mailgifts and discount coupons to its customers. You have been advised by the public relations managerof the bookstore that the courier company servicing the bookstore's mail might require an accuratelist of all customer names and their addresses.To implement a method for generating this list in a short span of time, you need to create a viewnamed custview based on the custnum, custname, and address columns of the Customers table.A few weeks after implementing the anniversary plan, you receive a request from the couriercompany to provide the full address of each customer, including the city, state, and zip codes.Later, the SQL Server administrator asks you to delete the view you created because you no longerneed it.

Note: The file C:\094019Data\Working with Views\Solution\Working with Views.sql containsone possible solution for these tasks. Try to perform these tasks on your own before you refer tothe solution file.

1. If SQL Server Management Studio is not running, launch it and connect to theserver. Open a new query editor window, and from the Available Databaseslist, select Pub2.

2. Create a view named custview to retrieve the customer number, customername, and address in the Customers table, and verify that you successfullycreated it.

3. Modify the structure of the custview view to add the city, state, and zip codeinformation to the address displayed by the view. Query the custview viewto verify your changes.

4. Delete the custview view. Verify that you successfully deleted thecustview view by attempting to retrieve records from the view.

SQL Querying: Advanced (Second Edition) | 161

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Mastery Builder 5-1Indexing Data

Activity Time: 15 minutes

ScenarioThe number of customers buying from the Fuller & Ackerman Publishing bookstorehas increased tremendously over the last decade of the bookstore's existence and hasresulted in a large number of records in the Customers table. To optimize theperformance of queries that use the Customers table, you decide to index the table.After reviewing the most frequent queries, you find that most queries have WHEREclauses that query the city and state columns. Later, you find that the cost ofmaintaining this index exceeds the benefit it offers. The database administrator asksyou to delete it.

Note: The file C:\094019Data\Indexing Data\Solution\Indexing Data.sqlcontains one possible solution for these tasks. Try to perform these tasks on yourown before you refer to the solution file.

1. If SQL Server Management Studio is not running, launch it andconnect to the server. Open a new query editor window, and fromthe Available Databases list, select Pub2.

2. Create a nonclustered index named idx_cust on the columns mostcommonly used for searching the Customers table.

3. Verify that you successfully created the index.

Your index should appear in the list.

4. Delete the idx_cust index.

5. Verify that you successfully deleted the idx_cust index from theCustomers table.

162 | SQL Querying: Advanced (Second Edition)

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Your index should no longer appear in the list.

SQL Querying: Advanced (Second Edition) | 163

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Mastery Builder 6-1Managing Transactions

Activity Time: 15 minutes

Data FileLab_Starter.sql

ScenarioYou have joined the Fuller & Ackerman Publishing bookstore as a SQL programmer.The store manager just gave you a list of books that have become obsolete. However,the manager warns you that the information in the list is not accurate and that you mayneed to undo the additions you make to the table. You want to be sure you can undoyour changes if the list of books changes, so you decide to use a transaction. After youadd these records to the Obsolete_titles table, you are instructed by the manager toundo the changes and use a new list with the correct information. The manager asksyou to ensure that you add the information in this new list to the Obsolete_titles table.

1. If SQL Server Management Studio is not running, launch it andconnect to the server. Open a new query editor window, and fromthe Available Databases list, select Pub2.

2. In the C:\094019Data\Managing Transactions folder, open theLab_Starter.sql file in SQL Server Management Studio. Below thecomment Incorrect Records, use your mouse to select theBEGIN TRAN obsInsert statement through the third INSERTstatement. On the toolbar, select Execute to begin to insert recordsinto the Obsolete_titles table.

3. The store manager tells you she gave you the wrong list of books.With your mouse, select the ROLLBACK TRAN obsInsertstatement and execute it to undo your changes.

4. Verify that you did not insert the rows listed below the commentIncorrect Records.

5. With your mouse, select the statements marked under thecomment Correct Records, starting with the BEGIN TRANstatement through the COMMIT TRAN statement to insert thecorrect records into the Obsolete_titles table. On the toolbar, selectExecute to begin and commit your changes.

6. Verify that you inserted the new rows into the Obsolete_titles tablebased on the part numbers.

164 | SQL Querying: Advanced (Second Edition)

Mastery Builders

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Glossary

ALTER TABLE statementA SQL statement that modifies thestructure of a table.

ALTER VIEW statementA SQL statement that modifies a view.

APPLY operatorA relational operator that enables you toapply a table expression to all rows of anouter table.

CHECK constraintA constraint that validates the valuesstored in a column based on a conditionyou specify with the constraint.

COMMIT TRAN statementA SQL statement that saves the datamodifications by SQL statements in atransaction.

composite keyA primary key containing multiplecolumns.

constraintA validation mechanism you implement ona column or a table to ensure data integrity.

correlated subqueryA SQL statement that SQL Server executessimultaneously with the outer query.Unlike other subqueries, the correlatedsubquery depends on the input from theouter query to return values.

CREATE INDEX statementA SQL statement that creates an index onone or more table columns.

CREATE TABLE statementA SQL statement you use to create a table.

CREATE VIEW statementA SQL statement that creates views inSQL.

data integrityThe state of the information in a databasewhere all values stored in the database arecorrect.

DEFAULT constraintA constraint that specifies a default valuefor a column.

DELETE statementA SQL statement that deletes records froma table.

DROP INDEX statementA SQL statement that deletes an indexcreated on a table.

DROP TABLE statementA SQL statement that deletes a table froma database.

DROP VIEW statementA SQL statement that deletes a view froma database.

EXISTS operatorA logical operator that you use in thecondition of an outer query to check for

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

the existence of records returned by thesubquery.

foreign keyA column that links the records in a tablewith the primary key of another table.

FOREIGN KEY constraintA constraint that creates a foreign key on atable.

GROUP BY clauseA clause you can use to group rows in theoutput based on the content of one ormore columns.

HAVING clauseA clause to specify a search conditionbased on an aggregate value.

IN operatorA logical operator that you use in thesearch condition of a query to search for avalue in a list of values.

indexA data organization mechanism that helpsin the speedy retrieval of records.

inner queryA SQL statement that is contained withinan outer query. You use an inner querywhen the value needed by the outer query'scondition is unknown.

INSERT statementA statement to insert a record into a table.

MERGE statementA SQL statement that you use to mergethe data in two tables or columns.

modified comparison operatorA comparison operator whose functionyou modify by combining it with the ANYor ALL logical operator.

nested subqueryA SQL statement that contains multiplelevels of inner queries.

outer queryA query that depends on the valuesreturned by another query used to displayrecords.

OUTPUT clauseA SQL statement used to get informationfrom rows that are influenced by theINSERT, UPDATE, and DELETEstatements.

primary keyA column or a combination of columnsthat store values to uniquely identify eachrecord in a table. You cannot store nullvalues in the primary key for a table.

PRIMARY KEY constraintA constraint that creates a primary key ona column or a combination of columns in atable. SQL Server does not permit nullvalues in a primary key column orcolumns.

query execution planA description of the way in which a queryis executed. This information can provide auseful tool for determining why a query isperforming slowly.

ROLLBACK TRAN statementA SQL statement that cancels themodification of data implemented by theSQL statements in a transaction.

SCHEMABINDINGAn option you can use in the CREATE VIEW SQL statement when you create aview to prevent changes to the table onwhich the view is based.

SELECT INTO statementA SQL statement that creates a backup ofa table's structure and data into a newtable.

subqueryA query that is contained within an outerquery. You use a subquery when the valueneeded by the outer query's condition isunknown.

166 | SQL Querying: Advanced (Second Edition)

Glossary

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

TOP keywordA keyword that you use in a SELECTstatement to retrieve a number orpercentage of rows from a table.

transactionA collection of SQL statements that SQLexecutes as a single unit.

TRUNCATE TABLE statementA SQL statement that deletes all records in atable but retains the table structure.

UNIQUE constraintA constraint that implements uniqueness in thevalues stored in a column. You can store nullvalues in columns to which you assign thisconstraint.

UPDATE statementA SQL statement that modifies the data in acolumn of a table.

viewA virtual table that retrieves and displaysrecords from a base table.

SQL Querying: Advanced (Second Edition) | 167

Glossary

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

Index

AACID properties 133Atomicity, Consistency, Isolation,Durability properties, See ACID properties

Cclauses

GROUP BY 32HAVING 32

composite keys 71constraints

CHECK 76DEFAULT 76definitions 72FOREIGN KEY 74PRIMARY KEY 72UNIQUE 72

correlated subqueries 24

Ddata integrity 70

Eencryption 96

Fforeign keys 74

Iindexes

clustered 120keys 119

nonclustered 120index scan 120index seek 121inner queries 2

Kkeywords

TOP 97

Nnested queries 2nested subqueries 37

Ooperators

APPLY 25EXISTS 17IN 3modified comparison 11

outer queries 2

Pprimary keys 71

Qquery execution plan 119query optimizer 120

SSQL clauses

OUTPUT 46SQL data types 63

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.

SQL statementsALTER TABLE 81ALTER VIEW 110COMMIT TRAN 144COMMIT TRANSACTION 133CREATE INDEX 121CREATE TABLE 62CREATE VIEW 95DELETE 53, 105DROP INDEX 127DROP TABLE 89DROP VIEW 110INSERT 44, 104INSERT INTO 63MERGE 54ROLLBACK TRAN 134ROLLBACK TRANSACTION 133SCHEMABINDING 96SELECT INTO 66TRUNCATE TABLE 54UPDATE 52, 105

subqueries 2

Ttable backup 66table design 65table scan 120table value constructors 46transactions

management 133

Vviews

benefits and disadvantages of 97

170 | SQL Querying: Advanced (Second Edition)

Index

DO N

OT

DUPL

ICAT

E

FOR

EVAL

UATI

ON

USE

ONL

Y

(C) 2

017

Logi

cal O

pera

tions

, Inc

.