SQL Query Writing and Fundamentals Reference Guidesqlsteps.com/assets/pdf/SQL...
Transcript of SQL Query Writing and Fundamentals Reference Guidesqlsteps.com/assets/pdf/SQL...
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 1 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
SQL Query Writing and Fundamentals
Reference Guide
Welcome to the SQL Query Writing and Fundamentals Reference Guide. This guide contains all the text content covered in the online course.
For the animated screen Demonstrations, Simulations and Quizzes referred to in this PDF
Guide please visit the online course provided by www.SQLSteps.com
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 2 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Table of Contents
Module 1: Database: An Overview .......................................................................... 6
What will you learn in this module? ............................................................................ 6
What is a Database? ............................................................................................... 6
What is a Database Management System? .................................................................. 7
What are the advantages of a DBMS? ......................................................................... 7
What is a Relational Database Management System? .................................................... 8
What is a Table? ..................................................................................................... 8
What are Data Types? ............................................................................................. 9
Describing Relationships ........................................................................................ 10
Listing the Different Types of Relationships ............................................................... 12
Understanding Primary and Foreign Keys .................................................................. 13
What is Normalization? .......................................................................................... 14
Module 2: SQL: An Overview................................................................................ 16
What will you learn in this module? .......................................................................... 16
What is SQL? ....................................................................................................... 16
What is the Role of SQL?........................................................................................ 17
What are the Functions of SQL? .............................................................................. 17
What are the Components of SQL? .......................................................................... 17
Module 3: Getting Started with Microsoft SQL Server ............................................... 20
What will you learn in this module? .......................................................................... 20
What is Microsoft SQL Server? ................................................................................ 20
Using the SQLCMD Utility ....................................................................................... 21
Using SQL Server Management Studio for Scripting .................................................... 24
What is the Debug Feature? ................................................................................... 26
Module 4: Using the SELECT Statement ................................................................. 27
What will you learn in this module? .......................................................................... 27
Understanding the SELECT Statement....................................................................... 27
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 3 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using the SELECT Statement ................................................................................... 28
Executing a Query Using the SQL Server Management Studio....................................... 28
Retrieving Data from Specific Columns in a Table ....................................................... 29
Filtering Rows with the WHERE Clause ....................................................................... 29
Using Operators to Create Conditions ....................................................................... 30
What is the NULL Keyword?.................................................................................... 33
Sorting the Result Set with the ORDER BY Clause ........................................................ 34
Using the DISTINCT keyword to Suppress Duplicate Rows ............................................ 35
Viewing Top Rows in a Large Result Set .................................................................... 36
Using Wildcards to Retrieve Data ............................................................................. 37
Working with Calculated Columns ............................................................................ 39
Module 5: Working with Multi-table Queries ............................................................ 41
What will you learn in this module? .......................................................................... 41
What are Joins? .................................................................................................... 41
Understanding Types of Joins ................................................................................. 42
Creating Joins with the WHERE Clause ....................................................................... 46
Module 6: Using SQL Functions in Queries .............................................................. 48
What will you learn in this module? .......................................................................... 48
Understanding SQL Functions ................................................................................. 48
What are Aggregate Functions? ............................................................................... 49
What are Mathematical Functions? ........................................................................... 52
What are Date Functions? ...................................................................................... 55
What are String Functions? .................................................................................... 56
What are Conversion Functions? .............................................................................. 59
Module 7: Grouping Data..................................................................................... 62
What will you learn in this module? .......................................................................... 62
Defining Grouping of Data ...................................................................................... 62
Working with the GROUP BY Clause .......................................................................... 62
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 4 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Working with the HAVING Clause .............................................................................. 63
Adding Totals and Subtotals to Grouped Data ............................................................ 64
Module 8: Working with Tables ............................................................................. 68
What will you learn in this module? .......................................................................... 68
Using the CREATE Statement ................................................................................... 68
Modifying a Table ................................................................................................. 69
Deleting a Table Using the DROP Statement ............................................................... 70
Using the CREATE DATABASE Statement .................................................................... 70
Using the DROP DATABASE Statement ....................................................................... 71
Module 9: Manipulating Data in Tables ................................................................... 72
What will you learn in this module? .......................................................................... 72
Using the INSERT INTO Statement ........................................................................... 72
Using the UPDATE INTO Statement ........................................................................... 73
Using the DELETE Statement ................................................................................... 74
Using the TRUNCATE Statement ............................................................................... 74
Module 10: Working with Programming Objects ........................................................ 76
What will you learn in this module? .......................................................................... 76
Understanding what is a View ................................................................................. 76
Using the CREATE VIEW Statement ........................................................................... 77
Using the SELECT Statement to Access a view ........................................................... 78
Modifying a View .................................................................................................. 78
Deleting a View .................................................................................................... 79
Renaming a View .................................................................................................. 79
What is an Index? ................................................................................................. 79
What is a Stored Procedure .................................................................................... 80
Using the CREATE PROCEDURE Statement ................................................................... 81
Using the EXECUTE Statement ................................................................................. 83
Using the ALTER PROCEDURE Statement .................................................................... 84
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 5 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using the DROP PROCEDURE statement ...................................................................... 85
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 6 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 1: Database: An Overview
What will you learn in this module?
At the end of this module, you will be able to:
Describe a Database
Define a Database Management System (DBMS)
List the Advantages of a DBMS
Define a Relational Database Management System (RDBMS)
Describe a Table
Explain Data Types
Describe Relationships
Explain Primary and Foreign Keys
Define Normalization
What is a Database?
A database is a logical collection of data. Data can be easily accessed, managed, and updated using a database. Typically, a database stores related data in a single file.
Before the advent of databases, data was typically stored in separate files. Managing and accessing related information was difficult and time consuming.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 7 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Customer Information
Product Information
Order Information
Sales Database
What is a Database Management System?
A Database Management System (DBMS) is a set of programs used to manage the database. The DBMS manages, processes and retrieves data in the database. While adding, updating, or deleting information, the DBMS maintains the consistency and integrity of the data.
For example, it will not allow a customer‟s details to be deleted if there are pending orders for the customer.
What are the advantages of a DBMS?
These are some of the main DBMS advantages:
Single repository of data. Related data is stored at a single location. For example, customer, product and order details are all stored in a single database.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 8 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Fast and easy data access. Access to related data is quick and easy. For example, you can easily access details of all orders placed by a customer.
Reduced redundancy. Ideally, only one copy of data is stored and this helps in avoiding duplication of data. For example, a particular customer‟s details are stored only once, and not with every order.
Multiple user access: Multiple users can access a single DBMS at once.
Security. A DBMS provides data security by allowing only authorized persons to access the database. The database administrator decides who can view and update the data.
What is a Relational Database Management System?
A Relational Database Management System (RDBMS) is a DBMS in which data is stored in tables according to the relationships between the data elements. In an RDBMS, each table stores data about a particular type of entity.
For example, details of various customers can be stored in a Customers table. Similarly,
details about various products can be stored in the Products table. The Orders table can
store details of the various products in an order and some details of the customer who ordered them.
What is a Table?
A table is a collection of similar data items. For example, a Books table can contain details
about various books.
Tables consist of rows and columns.
Each row represents a unique entity. Within each row, every column holds one detail about the entity. For example, each row in the Books table contains details of a book.
Each individual detail is stored in a separate column. For example, name of the author is stored in the AuthorName column.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 9 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
While defining a table, you must specify:
The name of the table
The names of the columns in the table
The data type for each column
What are Data Types?
A data type specifies the type of information that can be stored in a column.
Column Type of Data
ProductName Text
Cost Real numbers
NumberOfItems Integers
DateOfShipping Date
Logo Image file
For example, NumberOfItems should always be whole numbers or integers, while
ProductName will always be text. Similarly, the DateOfShipping must be a valid date.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 10 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
By defining the data type for a column, you are limiting the type of data that can be stored in that column. For example, Cost cannot be text.
What are the Data Types Available in Microsoft SQL Server?
Microsoft SQL Server offers a wide range of data types that can be broadly classified as:
Integer Data Types
Numeric Data Types
Data and Time Data Types
Character Data Types
Binary Data Types
Other Data Types
Commonly used data types in Microsoft SQL Server:
Data type Description Example
Int Whole numbers or integer data Number of employees
float Real numbers Salary
datetime Date and time Date and time of login
Char Character data with a fixed length Telephone number
varchar Character data of variable length Notes
image Images Product image
Describing Relationships
What are Entities?
An entity is anything about which data can be stored. The properties of an entity are known as its attributes.
For example, a book is an entity while details such as its author, title etc are its attributes.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 11 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
An entity is represented in the form of a table in a database. The column headings in a table represent the attributes of an entity. The data about an entity is represented in the form of rows.
What is a Relationship?
A relationship is an association that links entities. It establishes the connection between entities.
A library owns books. Library and book are entities, while the relationship between them arises from the library owning the books.
A customer buys many products.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 12 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
A teacher teaches students.
Listing the Different Types of Relationships
There are three types of relationships:
One-to-one
One-to-many
Many-to-many
What is a One-to-One Relationship?
In a one-to-one relationship, one instance of an entity can relate to only one instance of another entity.
For example, a company can have only one CEO and that CEO can work only for that company.
Company CEO
What is a One-to-Many Relationship?
In a one-to-many relationship, one instance of an entity can relate to more than one instance of another entity.
For example, a company can have many employees.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 13 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Company Employees
What is a Many-to-Many Relationship?
In a many-to-many relationship, more than one instance of an entity is associated with more than one instance of another entity.
For example, in a company, one employee can be assigned many projects, and one project can have many employees.
Project 1 Project 2 Project 3
Understanding Primary and Foreign Keys
What is a Primary Key?
In an RDBMS, each table must have a unique identifier which uniquely identifies individual rows of the table. This identifier helps in accessing and updating each record efficiently.
This unique identifier is known as the primary key.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 14 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
For example, an EmployeeID is unique to each employee and so can be the primary key in
the Employee table. We cannot use the employee‟s name as the primary key as there could
potentially be two employees with the same name.
What is a Foreign Key?
To establish a relationship between two tables, there has to be a common element between the two. In an RDBMS, the relationship is established between two tables when the primary key of a table (table A) is also a column in the other table (table B). In the related table (table B), this common column is referred to as the foreign key.
For example, the CustomerID is a primary key in the Customers table. The Orders
table must also indicate the Customer who placed the order. Thus, the Orders table will
have a CustomerID column that will help uniquely identify the customer who placed the
order. In the Orders table, the CustomerID column is a foreign key.
What is Normalization?
Raw data, when received, has a lot of redundancy and the relationship between the entities is not evident.
Normalization is the process that involves organizing data elements into tables such that:
Data redundancy is eliminated.
Relationships are clearly established.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 15 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Normalization ensures that:
Data integrity is maintained.
Results of queries are predictable.
Changes to data have to be made only once.
Amount of storage required by the database is optimal.
Note: A full study of the process of Normalization is outside the scope of this course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 16 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 2: SQL: An Overview
What will you learn in this module?
At the end of this module, you will be able to:
Explain the Role of SQL
List the Functions of SQL
Define SQL Components
What is SQL?
Structured Query Language, or SQL as it is popularly known, is used to access, manipulate and manage data in a relational database.
SQL was originally developed by IBM and was later adopted as an industry standard. The American National Standards Institute (ANSI) defines the standards for SQL. However, many database vendors have developed variations of ANSI SQL. For example, Microsoft SQL Server uses Transact-SQL (T-SQL).
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 17 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
What is the Role of SQL?
SQL provides users with a way of interacting with and manipulating databases. With SQL you can:
Create, alter and delete the database and objects such as tables.
Add, modify and delete data within the database.
Set permissions for database objects.
The syntax of SQL statements is simple and easy to learn. SQL provides a standard way of accessing data in any relational database.
What are the Functions of SQL?
Although retrieving data is one of the most important functions of SQL, it also performs the following functions:
Data Integrity – SQL ensures valid and correct data in the database. It protects the data from corruption due to certain inconsistencies or system failures.
Data Retrieval – SQL allows a user to retrieve stored data from the database and use it.
Data Manipulation – SQL allows a user to update the database by adding new data, modify existing data, or deleting data.
Data Definition – SQL allows a user to define the structure of a database, organize data, and create logical relationships among the stored data items.
Access Control – SQL allows a user to set permissions for other users to access, add, or modify data in a database. It protects the stored data against unauthorized access.
What are the Components of SQL?
SQL statements can be divided into three major categories:
Data Manipulation Language (DML)
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 18 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Data Definition Language (DDL)
Data Control Language (DCL)
What is Data Manipulation Language (DML)?
Data Manipulation Language (DML) is a set of SQL commands that are used to manipulate the data. With DML, you can insert, update or delete data in tables.
The DML statements are:
SELECT – Retrieves data from a database
INSERT – Add rows to a table in a database
UPDATE – Updates existing rows of a table in a database
DELETE – Deletes rows from a table in a database
What is Data Definition Language (DDL)?
Data Definition Language (DDL) is a set of SQL commands used for creating and managing a database and objects within it. DDL includes all the commands that are required to build and modify the structure of tables and other objects in a database.
The commonly used DDL statements are:
CREATE – Creates a new database, table or an index
ALTER – Modifies a table or a database
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 19 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
DROP – Deletes a table or an index
TRUNCATE – Deletes all data from a table
What is Data Control Language (DCL)?
Data Control Language (DCL) is a set of SQL commands that are used to control access to a database. Using DCL, you can allow or deny access to specified database objects to certain users or roles.
The commonly used DCL statements are:
GRANT – Allows specified users or roles to perform specified tasks on a database object.
REVOKE – Prevents specified users or roles from performing specified tasks on a database object.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 20 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 3: Getting Started with Microsoft SQL Server
What will you learn in this module?
At the end of this module, you will be able to:
Understand what is Microsoft SQL Server
Use the SQLCMD utility
Use SQL Server Management Studio for scripting
Explain the Debug feature
What is Microsoft SQL Server?
Microsoft SQL Server is a RDBMS developed by Microsoft. Besides storing and managing relational data, Microsoft SQL Server allows you to use the data effectively through features such as queries, reports and analysis tools. With its high-performance, scalable architecture it is used in businesses large and small.
Listing the Features of Microsoft SQL Server
Some of the notable features of Microsoft SQL Server are:
SQL Server Management Studio: Enables you to access, manage, and develop various components of Microsoft SQL Server from a common environment.
Analysis Services: Design wide-ranging analytics solutions that provide business insights to power your decisions.
Reporting Services: Generate a variety of reports, including interactive web-based reports that deliver information when needed.
Integration Services: Manage data from a wide variety data sources.
Performance Tools: Enhance the performance of your database server with tools such as Database Engine Tuning Advisor and SQL Server Profiler.
Microsoft Sync Framework: Allows applications to work in an offline mode by enabling synchronization of data on connection.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 21 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Security: Protect your data with powerful, customizable security features including robust authentication and access control, powerful encryption and key management capabilities, and enhanced auditing.
Listing the Two Ways to Execute SQL Statements
Microsoft SQL Server provides two ways to execute SQL statements:
SQLCMD – A command-line tool provided by Microsoft for executing SQL statements. In Windows, the command-line is a text based approach for executing various instructions.
SQL Server Management Studio – A popular graphical tool provided by Microsoft for accessing and managing databases.
Both of these approaches will be covered in this module.
Using the SQLCMD Utility
SQLCMD is Microsoft SQL Server‟s command line utility for writing and executing SQL statements from the command prompt. Using the SQLCMD utility, you can also create and run a set of SQL statements as scripts. The results obtained from the executed SQL statements can be displayed on screen or stored in a file.
Starting the SQLCMD Utility
To use the SQLCMD utility, you first need to access the Windows command prompt. At the Command Prompt:
1. Type sqlcmd.
2. Press ENTER.
You are now connected to the SQLCMD utility. The name of the command prompt window changes to SQLCMD. The cursor changes to 1>, indicating that the first command can be typed there.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 22 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Note: This topic includes a demo. To view this demo, please refer to the online course.
By default, the SQLCMD utility connects to the SQL Server using the Windows login and password.
You can also connect to Microsoft SQL Server using the SQL Server login and password using the syntax:
sqlcmd -U [username] -P [password]
Note: Ask the Database Administrator for the SQL Server User Name and Password, if required.
Executing the SQL Statements
After connecting to SQLCMD, to execute a command:
1. At the command prompt, type the SQL statement.
2. Press ENTER.
3. On the new line, type Go.
4. Press ENTER.
The SQL Command is now executed.
Changing a Database in SQLCMD
When you start the SQLCMD utility, it connects to the default instance of Microsoft SQL Server. The default database is selected as the active database.
To change the active database, use the command:
use <Database_Name>
Note: To set the active database while connecting to SQLCMD, use the syntax: sqlcmd –d
northwind.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 23 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Executing Commands Using SQLCMD
In SQLCMD, you can write an SQL statement over multiple lines. To execute the statement, on a new line type Go and press ENTER.
A sample of a SQL SELECT statement specified over multiple lines is shown below:
Executing SQL Statements from a Saved File
You may want to run a particular SQL statement or set of SQL statements often. In such situations, you can save the SQL statements in a text file with the extension .sql. This file will now be called a script.
You can execute a script using the syntax.
sqlcmd –i <Full_Path_of_Script_File_Name>
Executing SQL Statements from a Saved File
Consider the file MyQuery.sql file which contains the following SQL statements.
Use Northwind
Select EmployeeID, FirstName, LastName, Title from Employees
To execute the commands in the script file MyQuery.sql, at the Command Prompt, type:
sqlcmd –i c:\MyQuery.sql.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 24 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
The results are displayed on the screen as shown in the image below.
Saving Output to a File
By default, the result of executing an SQL statement is displayed on screen. You can send the output to a file, instead of displaying it on screen, using the syntax:
sqlcmd –o <Full_Path_of_Output_File_Name>
Consider the command:
sqlcmd –o c:\MyQueryResult.txt
All results from SQL statements executed will now be saved in the file c:\MyQueryResult.txt.
Click on Sending Output to a File to view the results.
Using SQL Server Management Studio for Scripting
SQL Server Management Studio is a tool that can be used to access, manage, and develop all components of Microsoft SQL Server. SQL Server Management Studio incorporates a rich set of script and graphical tools, making it easy-to-use across a wide spectrum of users.
With SQL Server Management Studio, you can:
Auto-generate SQL statements
Write SQL statements using the Graphical Query Designer
Use templates to create SQL statements
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 25 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Listing the Scripting Features of SQL Server Management Studio
SQL Server Management Studio provides a variety of ways to generate SQL Statements.
Listed below are some features that simplify writing SQL statements in the SQL Server Management Studio:
A rich set of templates that serves as a base for creating a variety of SQL statements. You can also save your queries as templates for future use.
Microsoft IntelliSense displays the syntax as you type the SQL statements.
Dynamic help displays relevant help topics immediately.
Create offline queries or scripts without having to connect to a server.
Create SQLCMD queries and scripts.
Auto-generating SQL Statements
Writing lengthy SQL statements can be tedious and time consuming. With SQL Server Management Studio, you can generate SQL statements using an intuitive, menu-based method.
Note: This topic includes a demo. To view this demo, please refer to the online course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 26 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Building SQL Queries Using the Query Designer
The Graphical Query Designer is a visual tool that lets you design SQL statements graphically. It is useful for those who are learning how to write SQL as they do not need to remember the syntax for creating complex SQL statements.
Note: This topic includes a demo. To view this demo, please refer to the online course.
Using Templates to Write and Execute SQL Statements
Templates in SQL Server Management Studio are files containing pre-written SQL statements that you can modify and use as required
Templates are organized into various categories and they can be viewed through the Template Explorer window in the SQL Server Management Studio.
Note: This topic includes a demo. To view this demo, please refer to the online course.
What is the Debug Feature?
Checking long multi line SQL statements for errors can be time consuming. To make this task easy, SQL Server Management Studio provides the Debugger function.
The Debugger function helps you find errors in SQL statements by observing their runtime behavior. It helps ensure that the SQL statements are executed in the way that they were intended.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 27 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 4: Using the SELECT Statement
What will you learn in this module?
At the end of this module, you will be able to:
Introduce the SELECT statement
Use the SELECT statement
Execute a query in Microsoft SQL Server
Retrieve specific columns in a table
Filter rows with the WHERE clause
Use operators to create conditions
Retrieve unknown values from the database
Sort result sets
Suppress duplicate rows
View top rows in a large result set
Use wildcards to retrieve data
Work with calculated columns
Understanding the SELECT Statement
The SELECT statement enables you to access and retrieve information from the database.
The rows retrieved by the SELECT statement are known as the result set.
Using the SELECT statement, you can retrieve all information from a table or narrow your
search to retrieve only specific information from a table. You can also sort and group data, and perform calculations.
The syntax of the SELECT statement is:
SELECT column_list
[INTO new_table]
FROM table
[WHERE search_condition]
[GROUP BY group_by_expression]
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 28 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC]]
Note: SQL is not case sensitive.
As you progress through this module, you will learn to use the SELECT statement and its
clauses.
Using the SELECT Statement
In the simplest form, the SELECT statement retrieves all rows and columns from the specified
table.
The syntax of the SELECT statement to retrieve all the data from a table is:
SELECT * FROM <table_name>
Consider the query:
SELECT * FROM Employees
This statement retrieves all rows and columns from the Employees table.
Executing a Query Using the SQL Server Management Studio
You can execute queries using the SQL Server Management Studio.
Note: This topic includes a demo. To view this demo, please refer to the online course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 29 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Retrieving Data from Specific Columns in a Table
The SELECT statement can also be used to retrieve data from specific columns of a table.
To retrieve data from specific columns of a table, the syntax is:
SELECT <column1,column2,…,columnN> FROM <table_name>
Consider the query:
SELECT TitleOfCourtesy, FirstName, LastName, Title
FROM Employees
This SELECT statement retrieves data from the columns TitleOfCourtesy, FirstName,
LastName, and Title for all rows of the table Employees.
Filtering Rows with the WHERE Clause
You may want to view those rows that meet specific conditions. In such situations, the WHERE clause is used with the SELECT statement.
The syntax of a SELECT query that uses the WHERE clause is:
SELECT <column1,column2,…,columnN>
FROM <table_name>
WHERE <column> <operator> <value1>
Consider the query:
SELECT TitleOfCourtesy, FirstName, LastName, Title
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 30 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
FROM Employees
WHERE Title='Sales Representative'
This statement retrieves data only from those rows where the Title column has the value
Sales Representative.
Using Operators to Create Conditions
An operator is a character or a reserved word that is used to specify a condition, or combine two or more conditions. The operators are used with the WHERE clause in the SELECT statement to set the filter criteria for data.
There are four types of operators:
1. Comparison Operators
2. List Operators
3. Range Operators
4. Logical Operators
The syntax for using an operator in a query is:
SELECT <column1,column2,…,columnN>
FROM <table_name>
WHERE <expression1> <operator> <expression2>
We shall look at each category of operators in detail in the topics to follow.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 31 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
What are Comparison Operators?
The comparison operators shown in the table below are used to compare two expressions.
Comparison Operator Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
Consider the query:
SELECT ProductName,UnitsInStock,UnitsOnOrder
FROM Products
WHERE UnitsOnOrder >=70
This query retrieves data only from those rows of the Products table where the value of
UnitsInStock is greater than or equal to 70.
What are Logical Operators?
Logical operators are used to test if a specified condition is true or not. They are also used to combine multiple conditions.
Some of the commonly used logical operators are:
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 32 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
OR Retrieves rows that meet any one of the specified conditions.
AND Retrieves rows that meet both the conditions.
NOT Retrieves rows that do not meet the specified condition.
BETWEEN Retrieves rows where the tested value falls within the specified range.
Consider the following query:
SELECT CompanyName,City
FROM Customers
WHERE City = 'London' OR City = 'Madrid'
This query retrieves data only from those rows of the Products table where the City is
London or Madrid.
What are List Operators?
The IN list operator checks if the result of the expression meets one of the specified values.
The syntax for using a list operator in a query is:
SELECT <column1,column2,…,columnN>
FROM <table_name>
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 33 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
WHERE <column> IN (‘value1’,‘value2’,…,‘valueN’)
Note: Use NOT IN to retrieve rows that do not meet the specified criteria.
Consider the query:
SELECT CompanyName,City
FROM Customers
WHERE City IN ('London','Madrid','Paris')
This query retrieves data only from those rows of the Products table where the City is
London, Madrid and Paris.
What is the NULL Keyword?
A NULL value in a column means that there is no data in the column. You can retrieve rows
which contain NULL values using the IS NULL keyword with the WHERE clause.
The syntax for retrieving records with NULL values is:
SELECT <column1,column2,…,columnN>
FROM <table_name>
WHERE < column1> IS NULL
Consider the query:
SELECT CompanyName,City,Region,Country
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 34 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
FROM Customers
WHERE REGION IS NULL
This query retrieves data only from those rows of the Customers table where the Region is NULL.
Sorting the Result Set with the ORDER BY Clause
The ORDER BY clause sorts the retrieved results in the ascending or descending order of the
values in the specified columns. The ASC and DESC keywords specify the sort order. If the
sort order is not specified, the results are sorted in the ascending order.
The syntax for using the ORDER BY clause is:
SELECT <column1,column2,…,columnN>
FROM <table_name>
ORDER BY <column1 [ASC|DESC],column2 [ASC|DESC],…,columnN
[ASC|DESC]>
Sorting Columns with the ORDER BY Clause
Consider the query:
SELECT * FROM [Order Details] ORDER BY Quantity ASC
This query retrieves all the rows and columns from the [Order Details] table and sorts
the rows in the ascending order by the column Quantity.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 35 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using the DISTINCT keyword to Suppress Duplicate Rows
Queries may return result sets with duplicate rows. The DISTINCT keyword eliminates
redundant rows from a result set.
The syntax for limiting result sets with the DISTINCT keyword is:
SELECT DISTINCT <column1,column2,…,columnN>
FROM <table_name>
Consider the query:
SELECT DISTINCT OrderID,Quantity
FROM [Order Details]
This query retrieves distinct values of the OrderID and the Quantity columns from the
Order Details table.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 36 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Viewing Top Rows in a Large Result Set
When accessing a large database, you can set a limit to the number of records you want to retrieve using the TOP keyword.
The syntax for retrieving the top N (Number) rows is:
SELECT TOP <N> <column1,column2,…,columnN>
FROM <table_name>
You can also specify the percentage of rows to be retrieved. The syntax for retrieving the top N percentage of rows is:
SELECT TOP <N> PERCENT <column1,column2,…,columnN>
FROM <table_name>
Consider the query:
SELECT TOP 30 ProductName FROM Products
This query retrieves the top 30 rows from the Products table.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 37 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using Wildcards to Retrieve Data
Using the LIKE keyword and patterns
Sometimes we know only a part of the data to be retrieved or are unsure of the exact spelling. For example, we may know that the name begins with Al or that the address contains the word Palm.
To retrieve data based on partially known information, use the LIKE keyword and wildcards.
Wildcards are special characters that can be used as substitutes for one or more unknown characters when searching for a match.
The syntax for retrieving data using wildcards is:
SELECT <column1,column2,…,columnN>
FROM <table_name>
WHERE <expression1> LIKE <Pattern>
Different wildcard characters are described below.
Wildcard Substitutes Example
% Zero or more characters
WHERE Name Like ‘Ja%’ returns
all rows where the column Name has data that starts with the characters Ja. For example, Jade, Jane, Janet, Jake, Jasper, etc.
_ Exactly one character WHERE Name Like ‘Ja_e’ returns
all rows where the column Name has
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 38 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Wildcard Substitutes Example
four-letter data that starts with the characters Ja and ends in e. For example, Jade, Jane, Jake, etc.
[] Any single character in the specified list
WHERE Name Like ‘Ja[dn]e’
returns all rows where the column Name has four-letter data that starts with the characters Ja and ends in e and the third character is d or n. That is, rows where the Name is Jade or Jane.
[^] Any single character not in the specified list
WHERE Name Like ‘Ja[^dn]e’
returns all rows where the column Name has four-letter data that starts with the characters Ja and ends in e and the third character is NOT d or n. That is, rows where the Name is Jade or Jane are excluded.
Note: You can use a combination of wildcards.
How to use the LIKE Keyword?
Consider the query:
SELECT CompanyName,Country
FROM Customers
WHERE CompanyName LIKE 'L%'
This query retrieves all the data from the Customers table where the CompanyName starts
with L.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 39 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Working with Calculated Columns
Consider a database table in SQL Server containing two columns, Unit Price and Quantity.
Unit Price Quantity
100 15
150 32
125 18
50 45
If we want to calculate the total cost price of each commodity automatically, we need to multiply Unit Price by Quantity. When we use this formula in a SQL Query, a new column is generated; this is called a calculated column.
By default, the new column is returned with no column name. We can assign a name to this unnamed column. For example, Total Cost.
Unit Price Quantity Total Cost
100 15 1500
150 32 4800
125 18 2250
75 45 3375
Note: Calculated columns are also called computed columns.
Generating Calculated Columns
The syntax for generating calculated columns is below:
SELECT <column1,column2,…,columnN> <CalculatedColumn>
AS <NameforCalculatedColumn>
FROM <table_name>
Consider the query:
SELECT ProductID, Quantity, UnitPrice * Quantity AS TotalPrice
FROM [Order Details]
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 40 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
This query retrieves the ProductID and Quantity from the Order Details table and
creates a new calculated column called TotalPrice.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 41 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 5: Working with Multi-table Queries
What will you learn in this module?
At the end of this module, you will be able to:
Understand what are joins
Understand types of joins
Create joins with the WHERE clause
What are Joins?
Often, you may need to extract data from more than one table, based on certain conditions. For example, details of all customers who have an outstanding order.
To extract related data from two tables, you must be able to establish a logical relationship between the two.
For example, in the Customers table, each customer is assigned a CustomerID. In the
Orders table, the customer who placed an order is identified by the CustomerID. So the
CustomerID field can be used to establish a relationship.
In a SQL statement, a join establishes the logical relationship between the tables from which data is to be extracted.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 42 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Joins can be categorized as:
Inner Joins
Outer Joins
Joins can be specified using the WHERE or the FROM clause.
Understanding Types of Joins
What is an Inner Join?
Inner Joins return only those rows that match the join condition.
For example, all employees who are assigned to a project and details of the project. The query will not show details of employees not assigned to a project or a project with no employees assigned to it.
The syntax for an inner join is:
SELECT <columns_from_table_1_and_table_2>
FROM <table_1>
INNER JOIN <table_2>
ON <table_1.column_name>=<table_2.column_name>
Note: If you want to use columns from multiple tables, use the syntax:
<table_name.column_name>
Consider the example:
Employees Projects
Inner Join
Employees who are assigned to a project
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 43 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
SELECT Customers.CustomerID,Customers.ContactName,
Orders.OrderID, Orders.OrderDate
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
Note: This topic includes a demo. To view this demo, please refer to the online course.
What is an Outer Join?
Outer Joins return all rows from one table and only those rows from the other table that match the condition specified in the join condition.
For example, all employees whether or not they are assigned to a project and details of the project, where available.
Outer joins have three types:
Left Outer Join
Right Outer Join
Full Outer Join
What is a Left Outer Join?
Every join has a comparison expression that involves fields from the two tables to be joined.
In a left outer join, all rows from the left table are retrieved. For every row in the left table where there is a match available in the right table, details from the right table are also retrieved. When a row in the left table has no matches in the right table, null values are displayed in place of values from the table in the right.
Those rows in the right table which have no matching rows in the table on the left are not retrieved.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 44 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
The syntax for a left outer join is:
SELECT <columns_from_table_1_and_table_2>
FROM <table_1> LEFT OUTER JOIN <table_2>
ON <table_1.column_name>=<table_2.column_name>
Consider the query:
SELECT Customers.CustomerID,Customers.ContactName,
Orders.OrderID,
Orders.OrderDate FROM Customers
LEFT OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
Note: This topic includes a demo. To view this demo, please refer to the online course.
What is a Right Outer Join?
In a right outer join, all rows from the right table are retrieved. For every row in the right table where there is a match available in the left table, details from the left table are also retrieved. When a row in the right table has no matches in the left table, null values are displayed in place of values from the table in the left.
Those rows in the left table which have no matching rows in the table on the right are not retrieved.
Employees Projects
Left Outer Join All employees and details of
projects where available.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 45 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
The syntax for a right outer join is:
SELECT <columns_from_table_1_and_table_2>
FROM <table_1> RIGHT OUTER JOIN <table_2>
ON <table_1.column_name>=<table_2.column_name>
Consider the query:
SELECT Customers.CustomerID,Customers.ContactName,
Orders.OrderID,
Orders.OrderDate FROM Customers
RIGHT OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
Note: This topic includes a demo. To view this demo, please refer to the online course.
What is a Full Outer Join?
The full outer join retrieves all rows from the left and the right tables, whether there is a corresponding match or not. The joined table contains data from both the tables. However, if a column in one table does not have a match in the corresponding column of the other table, a NULL is displayed in place of the column value.
Employees Projects
Right Outer Join All projects and details of
employees where available.
Full Outer Join
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 46 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
The syntax for a full outer join is:
SELECT <columns_from_table_1_and_table_2>
FROM <table_1> FULL OUTER JOIN <table_2>
ON <table_1.column_name>=<table_2.column_name>
Consider the query:
SELECT Customers.CustomerID,Customers.ContactName,
Orders.OrderID,
Orders.OrderDate FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
Note: This topic includes a demo. To view this demo, please refer to the online course.
Creating Joins with the WHERE Clause
The WHERE clause can be used to specify an inner join, left outer join and right outer join in a
multi-table query.
The syntax for specifying an inner join with the WHERE clause is:
SELECT <columns_from_table_1_and_table_2>
FROM <table_1> INNER JOIN <table_2>
Employees Projects
Full Outer Join
All Employee and Project details
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 47 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
ON <table_1.column_name>=<table_2.column_name>
WHERE <Condition>
The syntax for specifying a left outer join with the WHERE clause is:
SELECT <columns_from_table_1_and_table_2>
FROM <table_1> LEFT OUTER JOIN <table_2>
ON <table_1.column_name>=<table_2.column_name>
WHERE <Condition>
The syntax for specifying an right outer join with the WHERE clause is:
SELECT <columns_from_table_1_and_table_2>
FROM <table_1> RIGHT OUTER JOIN <table_2>
ON <table_1.column_name>=<table_2.column_name>
WHERE <Condition>
Note: This topic includes a demo. To view this demo, please refer to the online course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 48 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 6: Using SQL Functions in Queries
What will you learn in this module?
At the end of this module, you will be able to:
Use functions in SQL
Use aggregate functions
Use mathematical functions
Use date functions
Use string functions
Use conversion functions
Understanding SQL Functions
Using functions, you can manipulate retrieved data to create useful and relevant information. For example, you can find the total value of all products in stock, rather than just viewing price and quantity details of each product in stock.
Microsoft SQL Server provides a variety of functions for performing different calculations on data. These functions are classified into categories such as:
Aggregate functions
Mathematical functions
Date functions
String functions
Conversion functions
What are Function Arguments and Return Values?
A function argument is the input required by a function. The data that a function needs to process is passed to the function as one or more arguments. Arguments are enclosed in brackets after the function name.
The typical syntax for a function is:
Function_Name(Argument_1, Argument_2,…, Argument_N)
The result of the function calculation is called the return value.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 49 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
What are Aggregate Functions?
Aggregate functions process a set of values and return a single value as a result. The aggregate functions in SQL include:
SUM()
AVG()
MAX()
MIN()
COUNT()
All aggregate functions require only one argument, typically the name of the column whose values are to be processed.
If duplicate values are to be ignored, the aggregate function uses the keyword DISTINCT.
To process all values, use the keyword ALL.
Note: The keyword ALL is also the default and can be omitted.
The syntax for an aggregate function is:
Aggregate_Function([ALL|DISTINCT]<column_name>)
Working with the SUM Function
SUM() is one of the most commonly used aggregate functions. This function returns the sum
total of all non-null values in the specified column. The column must contain numerical values.
The syntax of a query using the SUM() function is:
SELECT SUM([ALL|DISTINCT]<column_name>) FROM <table_name>
Consider the query:
SELECT SUM(Quantity) AS 'Total number of units ordered' FROM
[Order Details]
This query returns the sum of the values present in the column Quantity and displays it
under the heading Total number of units ordered.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 50 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Working with the AVG Function
AVG()calculates the average of all non-null data values in the specified column. The column
must contain numerical values.
The syntax of a query using the AVG() function is:
SELECT AVG([ALL |DISTINCT]<column_name>) FROM <table_name>
Consider the query:
SELECT AVG(UnitPrice) AS ‘Average Unit Price’ FROM [Order
Details]
This query returns the average of the values present in the UnitPrice column and displays
it as Average Unit Price.
Working with the MIN Function
MIN() retrieves the smallest non-null data value from the specified table column. The column
can contain numeric, string, or date/time values.
The syntax of a query using the MIN() function is :
SELECT MIN([ALL|DISTINCT]<column_name>) FROM <table_name>
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 51 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Consider the query:
SELECT MIN(UnitPrice) AS 'Minimum Unit Price' FROM [Order
Details]
This query returns the minimum value present in the UnitPrice column and displays it as
Minimum Unit Price.
Working with the MAX Function
MAX()retrieves the largest non-null data value in the specified table column. Like MIN(),
this function works for numeric, string, and date/time values.
The syntax of a query using the MAX() function is:
SELECT MAX([ALL|DISTINCT]<column_name>) FROM <table_name>
Consider the query:
SELECT MAX(Discount) AS 'Maximum Discount Given' FROM [Order
Details]
This query returns the maximum value present in the Discount column and displays it as
Maximum Discount Given.
Working with the COUNT Function
COUNT()counts the number of non-null values in the specified table column.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 52 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
The syntax of a query using the COUNT() function is:
SELECT COUNT([ALL|DISTINCT]<column_name>) FROM <table_name>
Consider the query:
SELECT COUNT(Quantity) AS 'Number of Products Ordered' FROM
[Order Details]
This query returns the count of all the non-null values present in the Quantity column and
displays it as Number of Products Ordered.
What are Mathematical Functions?
Microsoft SQL Server provides a variety of functions to perform a range of mathematical operations. Some of the mathematical functions are:
ROUND()
CEILING()
FLOOR()
SQUARE()
SQRT()
SIGN()
Working with the ROUND Function
ROUND()rounds off the numerical values to the specified precision.
The syntax of a query using the ROUND() function is:
ROUND(<expression>,<length>)
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 53 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
If length is a positive number, ROUND() restricts the number of digits after the decimal
point to the number specified by length. If length is a negative number, ROUND()
rounds the digits before the decimal point as specified by length.
Expression Result
SELECT ROUND(487.2378,2) 487.2400
SELECT ROUND(487.2311,2) 487.2300
SELECT ROUND(487.2378,-1) 490.0000
SELECT ROUND(487.2378,-2) 500.0000
SELECT ROUND(487.2378,-3) 0.0000
Working with the CEILING and FLOOR Functions
CEILING() returns the smallest integer greater than or equal to the specified number, while FLOOR()returns the largest integer less than or equal to the specified number.
The syntax of the CEILING() function is:
CEILING(<numeric_expression>)
The syntax of the FLOOR() function is:
FLOOR(<numeric_expression>)
Consider the query:
SELECT CEILING(1875.85)
The result of this query is 1876.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 54 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Consider the query:
SELECT FLOOR(2471.68)
The result of this query is 2471.
Working with the SQUARE and SQRT Functions
SQUARE() and SQRT()return the square and the square root of the specified numerical
value.
The syntax of the SQUARE() function is:
SQUARE(<numeric_expression>)
Consider the query:
SELECT SQUARE(100)
The result is 10000.
The syntax of the SQRT() function is:
SQRT(<numeric_expression>)
Consider the query:
SELECT SQRT(100)
The result is 10.
Working with the SIGN Function
SIGN()returns 1 if the argument value is positive, and -1 if the argument is negative.
The syntax of the SIGN() function is:
SIGN(<numeric_ expression>)
Consider the query:
SELECT SIGN(100)
The result is 1.
Consider the query:
SELECT SIGN(-100)
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 55 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
The result is -1.
What are Date Functions?
The date functions are used to work with date values. You can retrieve the system date and time as well as extract parts of a date or time value.
The most common date functions are:
GETDATE()
DAY()
MONTH()
YEAR()
Working with the GETDATE Function
GETDATE()returns the system time of the computer on which the SQL Server is running.
The syntax of the GETDATE() function is:
GETDATE()
This query returns the current date and time.
Working with the DAY, MONTH, and YEAR Functions
The DAY(), MONTH() and YEAR() functions return the day, month, and the year
respectively for the specified date.
The syntax of the DAY() function is:
DAY(<date_value>)
The syntax of the MONTH() function is:
MONTH(<date_value>)
The syntax of the YEAR() function is:
YEAR(<date_value>)
Consider the query:
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 56 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
SELECT GETDATE()AS 'Current Date & Time',
DAY(GETDATE())AS Day,
MONTH(GETDATE())AS Month,
YEAR(GETDATE())AS Year
The result of this query is shown in the screen below.
What are String Functions?
A string consists of a series of characters; alphabets, numbers, spaces, and special characters such as &, #, % etc.
String functions perform actions such as extracting parts of a string, substituting a sequence of characters with another and other such operations.
Typically, strings are enclosed in quotes. For example, „USA‟ or „3456.45‟.
Note: A number enclosed in quotes is treated as a string and not a numerical value.
Some important string functions are:
LEN()
SUBSTRING()
REPLACE()
LTRIM() and RTRIM()
Working with the LEN Function
LEN() returns the number of characters in the specified string expression.
The syntax of the LEN() function is:
LEN(<string_expression>)
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 57 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Consider the query:
SELECT ProductName,LEN(ProductName) AS Length FROM Products
The screen below shows the result of the query.
Working with the SUBSTRING Function
SUBSTRING() retrieves a part of the string, starting from the specified character. This
function needs three arguments:
The character string The start point of character string The length of the substring to be returned
The syntax of the SUBSTRING() function is:
SUBSTRING(<value_expression>,<start_expression>,<length_expressio
n>)
Consider the query:
SELECT SUBSTRING('Learn basics of SQL databases',6,14) AS
Substring
The result set of this query is “basics of SQL”.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 58 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Working with the REPLACE Function
REPLACE()replaces a specified set of characters with another string. This function requires
three arguments:
The character string
The characters to be replaced
The new character string
The syntax of the REPLACE() function is:
REPLACE(<string_expression>,<string_pattern>,<string_replacement>
)
Consider the query:
SELECT REPLACE('Queries','ries','stions')AS 'New String'
The result of this query is “Questions”.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 59 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Working with the LTRIM and RTRIM Functions
The LTRIM() and RTRIM()functions return strings after removing blanks from the left and
right of the string respectively.
The syntax of the LTRIM() function is:
LTRIM(<character_expression>)
Consider the query:
SELECT LTRIM(‘ MICROSOFT SQL SERVER’)
The result is ‘MICROSOFT SQL SERVER’.
The syntax of the RTRIM() function is:
RTRIM(<character_expression>)
Consider the query:
SELECT RTRIM(‘SQL MANAGEMENT STUDIO ‘)
The result is ‘SQL MANAGEMENT STUDIO’.
What are Conversion Functions?
Conversion functions are used to convert the data from one data type to another. While some conversions are automatic, many conversions such as numeric to string need special functions.
Some of the conversion functions are:
CAST()
CONVERT()
STR()
Working with the CAST Function
CAST()converts the data from one data type to another specified data type.
The syntax of the CAST() function is:
CAST (<expression> AS <new_data_type> [(length)])
Consider the query:
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 60 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
SELECT CAST(OrderDate AS VARCHAR(12)) FROM Orders
The query converts the value retrieved from the OrderDate column of the Orders table to
the data type varchar.
Working with the CONVERT Function
CONVERT() is similar to CAST(), except that CONVERT() allows you to specify the format
for date and time conversions.
The syntax for the CONVERT() function is:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
The style argument is optional which can be used to specify the format for date-time
values.
Consider the query:
SELECT OrderDate,
CONVERT(VARCHAR(12), OrderDate, 101) AS 'Date Format 1',
CONVERT(VARCHAR(12), OrderDate, 106) AS 'Date Format 2' FROM
Orders
This query displays the value in the OrderDate column of the Orders table as a string in
the format specified by the built-in styles 101 and 106.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 61 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Working with the STR Function
STR() converts numerical data into a string. This function accepts three arguments:
The numerical expression
The overall length of the string
Number of places to the right of the decimal point
The syntax of the STR() function is:
STR ( float_expression [ , length [ , decimal ] ] )
The length argument is optional and can be used to specify the overall length of the
numerical expression to be returned.
Note: If length is less than the number of digits before the decimal point, STR() returns
** as the result.
The decimal argument is also optional and returns the number of places to the right of the
decimal point.
Expression Result
SELECT STR(567.890,7,1) 567.9
SELECT STR(567.890,7,2) 567.89
SELECT STR(567.890,3,1) 568
SELECT STR(567.890,2,1) **
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 62 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 7: Grouping Data
What will you learn in this module?
At the end of this module, you will be able to:
Define grouping of data
Use the GROUP BY clause
Use the HAVING clause
Add totals and subtotals to grouped data
Defining Grouping of Data
Grouping is the process of summarizing a set of rows into a single row, based on specified criteria. Aggregate functions are used to combine values in one or more columns of the original set of rows into a single value in the summary row.
For example, we can add up orders by customer to find the total value of orders placed by each customer.
Working with the GROUP BY Clause
The GROUP BY clause is used to achieve grouping. This clause is written after the WHERE and
ORDER BY clauses in a SQL statement.
The syntax for the GROUP BY clause is:
SELECT <column1,column2,…,columnN>, <aggregate_function>(column)
FROM <table>
WHERE <condition>
GROUP BY <column1,column2,…,columnN>
Consider the following query that will display the total value of each order.
SELECT OrderID,SUM(Quantity * UnitPrice) AS 'Total Order Value'
FROM [Order Details]
GROUP BY OrderID
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 63 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Working with the HAVING Clause
Consider a query that uses the GROUP BY clause to calculate and display the total value of
orders placed by each customer. We may want to view only those customers whose order
values exceed a certain amount. In such a case, we will use the HAVING clause.
The HAVING clause is used to filter rows returned by the GROUP BY clause.
When you use the WHERE clause along with the GROUP BY and HAVING clauses, first the
condition in the WHERE clause is used to create a result set of rows that meet the WHERE
condition. Next, the GROUP BY clause is used to create the summary rows. Finally, the
HAVING clause is applied to the summary rows to create the final result set.
If a GROUP BY is not used then the HAVING clause behaves exactly the same way as the
WHERE clause.
The syntax for the HAVING clause is:
SELECT <column1, column2, …, columnN>, <aggregate_function>
(column)
FROM <table_name>
[WHERE <condition>]
GROUP BY <column1, column2, …, columnN>
HAVING <condition>
Consider the query that retrieves orders having total value of each order more than 500.
SELECT OrderID, ProductID, SUM(Quantity * UnitPrice) AS 'Total
Order Value'
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 64 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
FROM [Order Details]
WHERE ProductID BETWEEN 20 AND 35
GROUP BY OrderID, ProductID
HAVING SUM(Quantity * UnitPrice) > 500
Adding Totals and Subtotals to Grouped Data
Describing the ROLLUP and CUBE Operators
Grouping is the process of summarizing a set of rows into a single row, based on specified criteria. You can add totals and subtotals to the summary rows using the following operators:
ROLLUP
CUBE
Using the ROLLUP Operator
The ROLLUP operator calculates the subtotals on the first column specified in the GROUP BY
clause. It calculates the sum of each unique value found in the column and displays the subtotals in new rows.
The syntax of the ROLLUP operator is:
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 65 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
SELECT <column1, column2, …, columnN>, <aggregate_function>
(column)
FROM <table_name>
GROUP BY ROLLUP (column1, column2, ,…, columnN)
Consider the following example to understand how the ROLLUP operator works:
Original Data SELECT CustID, ProductID,
SUM(Quantity)
FROM MyOrders
GROUP BY CustID, ProductID
SELECT CustID, ProductID,
SUM(Quantity)
FROM MyOrders
GROUP BY ROLLUP (CustID,
ProductID)
CustID
ProductID
Quantity
CustID
ProductID
Quantity
CustID
ProductID
Quantity
C_1 P_1 5 C_1 P_1 13 C_1 P_1 13
C_1 P_1 6 C_1 P_2 8 C_1 P_1 8
C_1 P_2 8 C_2 P_1 5 C_2 P_1 5
C_1 P_1 2 C_2 P_2 11 C_2 P_2 11
C_2 P_1 5 C_1 NULL 21
C_2 P_2 6 C_2 NULL 16
C_2 P_2 5
Consider the following query and its result:
SELECT ProductName,SupplierID,CategoryID,
SUM(UnitPrice * UnitsInStock) AS 'Cost Of Stock'
FROM Products
WHERE ProductName LIKE 'C%'
GROUP BY ROLLUP(ProductName,SupplierID,CategoryID)
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 66 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using the CUBE Operator
The ROLLUP operator creates subtotals only for the first column in the GROUP BY clause. The
CUBE operator creates subtotals for all combinations of columns specified in the GROUP BY
clause. In addition, it creates a grand total that includes all rows.
The syntax of the CUBE operator is:
SELECT <column1, column2, … , columnN>, <aggregate_function>
(column)
FROM <table_name>
GROUP BY CUBE (column1, column2, … , column)
Consider the following example to understand how the CUBE operator works:
Original Data SELECT CustID, ProductID,
SUM(Quantity)
FROM MyOrders
GROUP BY CustID, ProductID
SELECT CustID, ProductID,
SUM(Quantity)
FROM MyOrders
GROUP BY CUBE (CustID,
ProductID)
CustID
ProductID
Quantity
CustID
ProductID
Quantity
CustID
ProductID
Quantity
C_1 P_1 5 C_1 P_1 13 C_1 P_1 13
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 67 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
C_1 P_1 6 C_1 P_2 8 C_1 P_2 8
C_1 P_2 8 C_2 P_1 5 C_2 P_1 5
C_1 P_1 2 C_2 P_2 11 C_2 P_2 11
C_2 P_1 5 C_1 NULL 21
C_2 P_2 6 C_1 NULL 16
C_2 P_2 5 NULL P_1 18
NULL P_2 19
NULL NULL 37
Consider the following query and its result:
SELECT ProductName,SupplierID,CategoryID,
SUM(UnitPrice * UnitsInStock) AS 'Cost Of Stock'
FROM Products
WHERE ProductName LIKE 'C%'
GROUP BY CUBE(ProductName,SupplierID,CategoryID)
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 68 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 8: Working with Tables
What will you learn in this module?
At the end of this module, you will be able to:
Create a table
Modify a table
Delete a table
Create a database
Delete an existing database
Using the CREATE Statement
The CREATE statement can be used to create a new table in the current database. You need
to specify the name of the table along with names, data types and constraints of the columns in the table.
Some of the constraints that can be set on a column are:
Primary key
Foreign key
Null values
Remember, a Null value represents an unknown or a missing value. It is important to understand that a null value does not mean a zero of a text string or one or more blank spaces.
As a result, when we allow a column to hold null values, we are saying that data in that column is optional
The syntax of the CREATE statement that is used to create a table is:
CREATE TABLE <table_name>
(
<column_name1> <data_type> PRIMARY KEY,
<column_name2> <data_type> NOT NULL,
…,
<column_nameN> data_type
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 69 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
)
Consider the example given below, where the CREATE statement will create a table named
Franchise.
CREATE TABLE Franchise
(FranchiseID int PRIMARY KEY,
FranchiseName varchar(255) NOT NULL,
Quantity varchar(255),
ContactName varchar(255)
)
Note: This topic includes a demo. To view this demo, please refer to the online course.
Modifying a Table
The ALTER statement can be used to change the structure of an existing table by:
Adding columns to a table
Modifying the data type of a column
Deleting columns from a table
Adding Columns to a Table Using the ALTER Statement
The ALTER statement can be used to add columns to an existing table.
The syntax of the ALTER statement is below:
ALTER TABLE <table_name>
ADD <column_name> <data type>
Modifying Columns in a Table Using the ALTER Statement
The ALTER TABLE statement can also be used to modify the data type of a column.
The syntax of the ALTER statement as used to modify the data type of a column is:
ALTER TABLE <table_name>
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 70 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
ALTER COLUMN <column_name> <new_data type>
Deleting Columns in a Table Using the ALTER Statement
The ALTER TABLE statement can also be used to delete a column using the DROP keyword.
The syntax of the ALTER statement as used to delete a column is:
ALTER TABLE <table_name>
DROP COLUMN <column_name>
Note: This topic includes a demo. To view this demo, please refer to the online course.
Deleting a Table Using the DROP Statement
The DROP statement can be used to delete a table permanently and completely from the
database. This statement will drop a table if and only if the data in the table is not referenced by any other table or component of the database.
The syntax of the DROP statement as used to delete a table is:
DROP TABLE <table_name>
Using the CREATE DATABASE Statement
So far, we have used an existing database to work with tables. But, If you are starting a completely separate project or want to create a database simply to practice with, you can create a new database.
The CREATE DATABASE statement is used to create a new database.
The syntax to create a database is:
CREATE DATABASE <database_name>
Consider the query:
CREATE DATABASE mydatabase
This query creates a new database called mydatabase.
Note: You can add tables to the new database using the CREATE TABLE statement.
Note: This topic includes a demo. To view this demo, please refer to the online course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 71 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using the DROP DATABASE Statement
The DROP DATABASE statement is used to delete an existing database.
The syntax to delete a database is:
DROP DATABASE <database_name>
Consider the query:
DROP DATABASE mydatabase
This query deletes mydatabase.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 72 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 9: Manipulating Data in Tables
What will you learn in this module?
At the end of this module, you will be able to:
Add rows to a table
Update rows in a table
Delete rows from a table
Delete all rows from a table
Using the INSERT INTO Statement
The INSERT statement is used to add new rows of data to a table. You can insert data in a
table in two ways:
Insert a new row containing values for all the columns of a table
Insert a new row containing values for only some columns of a table
If you are adding a new row with data for all columns in a table, you do not have to specify the column names. However, you must ensure that the order of the values is the same as that of the columns they are meant for.
The syntax to insert a new row with data for all columns is:
INSERT INTO <table_name>
VALUES (‘value1’, ‘value2’, ‘value3’,…, ‘valueN’)
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 73 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
You can also add data to only specific columns of a table, by specifying the column names and the associated values.
The syntax to insert a new row with values for specific columns in a table is:
INSERT INTO <table_name> (column1, column2, column3,…,columnN)
VALUES (‘value1’, ‘value2’, ‘value3’,…, ‘valueN’)
If you do not specify a value for a column, SQL uses NULL or the default value for that
column, if any. If the column does not allow NULL and has no default value, then the INSERT
statement fails.
Note: This topic includes a demo. To view this demo, please refer to the online course.
Using the UPDATE INTO Statement
The UPDATE statement is used to modify the existing rows in a table. You can modify just
one row, some rows or all rows in a table.
The syntax to update rows in a table is:
UPDATE <table_name>
SET <column_name1>= ‘<value1>’, <column_name2>=
‘<value2>’,…<column>= ‘<valueN>’
WHERE<condition>
The SET keyword specifies the new values while the WHERE clause identifies the records to
be updated. If you do not specify the WHERE condition, all the records in the table will be
updated.
Note: This topic includes a demo. To view this demo, please refer to the online course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 74 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using the DELETE Statement
The DELETE statement is used to delete rows from a table. You can choose which rows to
delete.
The syntax to delete specific rows from a table is:
DELETE FROM <table_name>
WHERE <condition>
The WHERE condition specifies the rows to be deleted in a table. If you do not specify the
WHERE condition, all the rows in the table are deleted.
It is important to note that only the rows of the table are deleted. The table itself remains intact. If you delete all rows, then you have an empty table.
Note: This topic includes a demo. To view this demo, please refer to the online course.
Using the TRUNCATE Statement
The TRUNCATE TABLE statement deletes all the rows of a table. The TRUNCATE TABLE
statement does the same thing as a DELETE statement without the WHERE clause. However,
the TRUNCATE TABLE is faster as compared to the DELETE statement without the WHERE
clause.
Also, the DELETE statement only deletes the rows from a table but does not free the space
used by the table. Whereas, the TRUNCATE TABLE statement deletes all the rows from the
table and also frees the space containing the table.
The syntax to delete all the rows from a table is:
TRUNCATE TABLE <table_name>
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 75 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Note: This topic includes a demo. To view this demo, please refer to the online course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 76 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Module 10: Working with Programming Objects
What will you learn in this module?
At the end of this module, you will be able to:
Understand what is a view
Create a view
Access a view
Modify a view
Delete a view
Rename a view
Work with an indexed view
Understand what is a stored procedure
Create a stored procedure
Execute a stored procedure
Modify a stored procedure
Delete a stored procedure
Understanding what is a View
Rewriting complex queries can be time consuming and prone to errors. With views, you can create complex queries, save and reuse them in the future. A view is a virtual table that consists of columns from one or more tables. The tables from which the columns are taken in a view are known as the base or underlying tables. A view is simply stored as a SELECT
statement in the database.
Note: A view does not occupy the physical space in a database as tables do. When the SELECT statement is executed, the view returns a virtual table.
Listing the Advantages of a View
Some advantages of using views:
Restrict access to rows and columns – Users can retrieve or modify only the data that they have been given access to.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 77 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Simplify query execution – Complex queries can be stored in the view and data from the view can be retrieved using simple SQL statements.
Retrieve data from multiple tables as one – Join columns of two tables to retrieve data as one.
Data security – Confidential information can be excluded from a view.
Using the CREATE VIEW Statement
A view is an alternate method to represent data from one or more tables in a database. The
CREATE VIEW statement creates a view in the database in the form of a virtual table.
The syntax for creating a simple view is:
CREATE VIEW <view_name>
AS
<SQL Statements>
For example, you can create a simple view using the syntax:
CREATE VIEW <view_name>
AS
SELECT <column1,column2,…,columnN>
FROM <table_name>
<WHERE condition>
Note: The SQL statements in the CREATE VIEW statement can be any SELECT, INSERT,
UPDATE, or DELETE statements.
Consider a query that creates a view to retrieve the date on which customers have placed orders and their corresponding date of shipping.
CREATE VIEW CustomerOrders
AS
SELECT OrderID,CustomerID,OrderDate,ShippedDate FROM Orders
WHERE OrderID BETWEEN '10251' AND '10263'
Note: This topic includes a demo. To view this demo, please refer to the online course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 78 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using the SELECT Statement to Access a view
The CREATE VIEW statement creates a virtual table based on the result set of the SELECT
statement. A view can be accessed using the SELECT statement.
The syntax for accessing a view is:
SELECT * FROM <view_name>
Note: You cannot rename the columns in a view as the view is only a virtual table in the database.
Modifying a View
The ALTER VIEW statement is used to modify an existing view in a database.
The syntax for the ALTER VIEW statement is:
ALTER VIEW <view_name>
AS
<SQL Statements>
For example, you can modify a view using the syntax:
ALTER VIEW <view_name>
AS
SELECT <column1,column2,…,columnN>
FROM <table_name>
<WHERE condition>
Consider a query that modifies the view CustomerOrders to exclude the order date for
each customer and include the date of shipping, ship name and country.
ALTER VIEW CustomerOrders
AS
SELECT OrderID, ShippedDate, ShipName, ShipCountry FROM Orders
WHERE OrderID > 10254
Note: This topic includes a demo. To view this demo, please refer to the online course.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 79 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Deleting a View
The DROP VIEW statement is used to delete a view from a database.
The syntax of the DROP VIEW statement is:
DROP VIEW <view name>
Renaming a View
An existing view in a database can be renamed without deleting or creating the view again.
The syntax for renaming a view is:
sp_rename <view_name>, <new_view_name>
Consider the query that renames the view CustomerOrders:
sp_rename CustomerOrders, OrdersShippingDetails
After renaming a view, you can access the view using the SELECT statement with the new
view name.
What is an Index?
Due to vast information in tables, it takes a long time to retrieve all information. Hence, indexes are created on columns of existing tables to retrieve data quickly.
You can consider an index in SQL similar to an index that appears at the end of a book which helps to locate information quickly. The same principle applies to indexes in SQL. You can create an index on views that contain a single column or a group of columns from a table. The two types of indexes you can create are clustered and non-clustered indexes.
What is an Indexed View?
A view is stored as a query in the database. In addition, a view can contain joined tables which can significantly reduce the performance as compared to a single table. To improve the performance of a view, you can create an indexed view.
After you create a view, you can create an index on that view. However, you must first create a clustered index on a view. A clustered index sorts the rows in the view. Each table or view can only have one clustered index. Hence, a clustered index is built on columns which contain a high percentage of unique data.
Listing the Rules for Creating an Indexed View
While creating an indexed view, you must keep the following points in mind:
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 80 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Create indexed views using the SCHEMABINDING option. The SCHEMABINDING
option locks the tables and prevents any changes that may affect the table structure.
List the column names of a table in the SELECT statement of a view. You
cannot use the asterisk character to retrieve all columns from a table.
Use only inner joins while retrieving data from two tables in a view. Outer joins cannot be included in an indexed view.
Select columns in a view only from the base tables. The tables mentioned in a view must be in the same database as the view.
Creating an Indexed View
The CREATE VIEW statement with the WITH SCHEMABINDING clause is used to create an
indexed view. The steps to create an indexed view are:
1. Create a simple view along with the SCHEMABINDING option.
2. Create a unique clustered index on the view. This index will store data in the view and update it whenever the data in the base table is changed.
The syntax to create a view with the SCHEMABINDING option is:
CREATE VIEW <view_name>
WITH SCHEMABINDING
AS
<SQL Statements>
The syntax to create a unique clustered index on the view is:
CREATE UNIQUE CLUSTERED INDEX <index_name>
ON <view_name>
(
<Name of the column on which the index is created>
)
Note: This topic includes a demo. To view this demo, please refer to the online course.
What is a Stored Procedure
A stored procedure is a predefined block of SQL statements used to perform a specific task. It is saved in a database and executed as a single unit. Stored procedures are beneficial when groups of SQL statements are reused multiple times.
SQL statements are grouped under one name and saved in the database in the form of a stored procedure.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 81 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Listing the Benefits of a Stored Procedure
The benefits of using a stored procedure are:
Enhance security – Restricts data access to specific users by granting or denying permissions. In this way, only authorized users can execute the stored procedures.
Code reusability – Groups blocks of SQL statements once and use the block again whenever needed. Stored procedures eliminate the task of rewriting the statements again and again.
Reduced network traffic - Reduces the amount of data transmitted over the network. In other words, stored procedures perform tasks within the database without sending unnecessary data on to the network
What are Parameters in a Stored Procedure?
A parameter is a special kind of variable that prompts a user to enter specific information in the form of an input. A stored procedure can have zero, one or more parameters.
A parameter in a stored procedure consists of:
The name of the parameter
Data type of the parameter
Length of the data type
The name of the parameter is always prefixed with the @ sign. If a stored procedure has two or more parameters, each parameter is separated by a comma.
Listing the Types of Parameters in a Stored Procedure
The types of parameters in a stored procedure are:
Input parameter - Accepts data from the user as an input. This parameter is used to execute SQL statements in the stored procedure that produces some result.
Output parameter – Executes and passes the data from the stored procedure back to the user.
Using the CREATE PROCEDURE Statement
The CREATE PROCEDURE statement is used to create a stored procedure.
The syntax for creating a stored procedure with parameters is:
CREATE PROCEDURE <procedure_name>
@parameter1 datatype1, @parameter2 datatype2,…
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 82 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
AS
<SQL Statements>
The syntax for creating a stored procedure without parameters is :
CREATE PROCEDURE <procedure_name>
AS
<SQL Statements>
Note: You can also write PROCEDURE as PROC while writing the CREATE PROCEDURE
statement.
Consider the query below; it creates a stored procedure in which parameters are not specified.
CREATE PROCEDURE MyCustomerDetails
AS
SELECT CompanyName, ContactName, ContactTitle FROM Customers
WHERE CompanyName LIKE 'C%'
This statement will create a stored procedure named MyCustomerDetails.
Note: This topic includes a demo. To view this demo, please refer to the online course.
Consider the query below; it creates a stored procedure in which parameters are specified.
CREATE PROCEDURE ProductTotalOrders
@ProductID int
AS
SELECT Products.ProductID,Products.ProductName,
SUM(Quantity) AS ‘Total Quantity Ordered’
FROM [Order Details],Products
WHERE Products.ProductID = @ProductID
AND Products.ProductID = [Order Details].ProductID
GROUP BY Products.ProductID,Products.ProductName
This statement creates a stored procedure named ProductTotalOrders with parameters.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 83 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Note: This topic includes a demo. To view this demo, please refer to the online course.
Using the EXECUTE Statement
The EXECUTE PROCEDURE statement is used to execute a stored procedure. A stored
procedure can be executed only in a database in which it is created. When the stored procedure is executed, it produces a result set. The stored procedure also displays output parameters, if specified.
The syntax for creating a stored procedure with parameters is:
EXECUTE <procedure_name>
[variable1, variable2,…,]
Note: Variables denote the input parameters of the stored procedure.
The syntax for executing a stored procedure without any parameters is :
EXECUTE <procedure_name>
Consider the following query and its results:
EXECUTE MyCustomerDetails
This statement executes a stored procedure named MyCustomerDetails which does not
specify any parameters.
This stored procedure displays the details of customers whose company name starts with the letter C.
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 84 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Consider the following query and its results:
EXECUTE ProductTotalOrders 19
This query executes a stored procedure named ProductTotalOrders which contains a
parameter @ProductID and an input 19 which is passed to the stored procedure. This
stored procedure retrieves the ProductID and ProductName from the Products table
and the corresponding total quantity ordered from the Order Details table for the
specified ProductID.
Using the ALTER PROCEDURE Statement
The ALTER PROCEDURE statement is used to modify an existing stored procedure.
The syntax for modifying an existing stored procedure with parameters is:
ALTER PROCEDURE <procedure_name>
@parameter1 datatype1, @parameter2 datatype2,…
AS
<SQL Statements>
The syntax to modify an existing stored procedure without parameters is:
ALTER PROCEDURE <procedure_name>
AS
<SQL Statements>
427 N Tatnall St #70385 Wilmington, Delaware 19801-2230 USA • Suite 1A Level 2 802 Pacific Hwy Gordon NSW 2072 Australia • Dalton House 60 Windsor Avenue London SW19 2RR England
Page 85 of 85 Copyright 2010 www.SQLSteps.com a division of ViSteps Pty Ltd
www.SQLSteps.com
SQLSteps is a business wholly owned by ViSteps Pty Ltd.
Using the DROP PROCEDURE statement
The DROP PROCEDURE statement is used to delete a procedure permanently from a
database.
The syntax for deleting a stored procedure is:
DROP PROCEDURE <procedure_name>
Consider the example:
DROP PROCEDURE MyCustomerDetails
This query deletes the MyCustomerDetails procedure