0% found this document useful (0 votes)
3 views135 pages

SQL101_148

This document is an introduction to SQL, covering its history, structure of relational databases, and common SQL statements. It includes lessons on basic SQL operations such as SELECT, INSERT, UPDATE, and DELETE, as well as advanced topics like joins and subqueries. The content is designed for learners to understand and manipulate data using SQL in various relational database management systems.

Uploaded by

Jimmy Pak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views135 pages

SQL101_148

This document is an introduction to SQL, covering its history, structure of relational databases, and common SQL statements. It includes lessons on basic SQL operations such as SELECT, INSERT, UPDATE, and DELETE, as well as advanced topics like joins and subqueries. The content is designed for learners to understand and manipulate data using SQL in various relational database management systems.

Uploaded by

Jimmy Pak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 135

Introduction to SQL

(SQL101 version 1.4.8)

Copyright Information
© Copyright 2017 Webucator. All rights reserved.

The Author

Nat Dunn
Nat Dunn founded Webucator in 2003 to combine his passion for web development
with his business expertise and to help companies benefit from both.

Accompanying Class Files


This manual comes with accompanying class files, which your instructor or sales
representative will point out to you. Most code samples and exercise and solution
files found in the manual can also be found in the class files at the locations indicated
at the top of the code listings.
Due to space limitations, the code listings sometimes have line wrapping, where
no line wrapping occurs in the actual code sample. This is indicated in the manual
using three greater than signs: >>> at the beginning of each wrapped line.
In other cases, the space limitations are such that we have inserted a forced line
break in the middle of a word. When this occurs, we append the following symbol
at the end of the line before the actual break: »»
Table of Contents

Table of Contents
1. Relational Database Basics..................................................................1
Brief History of SQL..........................................................................................1
Relational Databases........................................................................................1
Tables........................................................................................................1
Rows.........................................................................................................1
Columns....................................................................................................2
Relationships............................................................................................2
Datatypes..................................................................................................2
Primary Keys.............................................................................................2
Foreign Keys.............................................................................................2
Relational Database Management System...............................................2
Popular Databases...........................................................................................3
Commercial Databases.............................................................................3
Popular Open Source Databases.............................................................3
SQL Statements...............................................................................................4
Database Manipulation Language (DML).................................................4
Database Definition Language (DDL).......................................................4
Database Control Language (DCL)..........................................................4

Version: 1.4.8. Printed: 2017-02-16. i


Table of Contents

2. Simple SELECTs...................................................................................5
Introduction to the Northwind Database...........................................................5
Some Basics.....................................................................................................6
Comments.................................................................................................6
Whitespace and Semi-colons...................................................................7
Case Sensitivity........................................................................................7
SELECTing All Columns in All Rows................................................................8
Exercise 1: Exploring the Tables.......................................................................9
SELECTing Specific Columns........................................................................11
Exercise 2: SELECTing Specific Columns......................................................12
Sorting Records..............................................................................................15
Sorting by a Single Column....................................................................15
Sorting By Multiple Columns...................................................................16
Ascending and Descending Sorts...........................................................17
Exercise 3: Sorting Results.............................................................................19
The WHERE Clause and Logical Operator Symbols......................................21
Checking for Equality..............................................................................21
Checking for Inequality............................................................................22
Exercise 4: Using the WHERE Clause to Check for Equality or Inequality.....23
Checking for Greater or Less Than.........................................................25
Exercise 5: Using the WHERE Clause to Check for Greater or Less Than....26
Checking for NULL..................................................................................29
Exercise 6: Checking for NULL.......................................................................31
WHERE and ORDER BY........................................................................33
Exercise 7: Using WHERE and ORDER BY Together....................................34
Checking Multiple Conditions with Boolean Operators...................................37
AND........................................................................................................37
OR...........................................................................................................37
Order of Evaluation.................................................................................38
Exercise 8: Writing SELECTs with Multiple Conditions...................................40
The WHERE Clause and Logical Operator Keywords....................................43
The BETWEEN Operator........................................................................43
The IN Operator......................................................................................44
The LIKE Operator..................................................................................45
The NOT Operator..................................................................................47
Exercise 9: More SELECTs with WHERE.......................................................48

ii © Copyright 2017 Webucator. All rights reserved.


Table of Contents

3. Advanced SELECTs............................................................................53
Calculated Fields............................................................................................53
Concatenation.........................................................................................53
Mathematical Calculations......................................................................54
Aliases....................................................................................................56
Exercise 10: Calculating Fields.......................................................................57
Aggregate Functions and Grouping................................................................59
Aggregate Functions...............................................................................59
Grouping Data.........................................................................................61
Exercise 11: Working with Aggregate Functions.............................................64
Selecting Distinct Records......................................................................67
Built-in Data Manipulation Functions..............................................................67
Common Math Functions........................................................................67
Common String Functions......................................................................71
Common Date Functions........................................................................73
Exercise 12: Data Manipulation Functions......................................................77

4. Subqueries, Joins and Unions...........................................................81


Subqueries......................................................................................................81
Exercise 13: Subqueries.................................................................................84
Joins...............................................................................................................87
Table Aliases...........................................................................................88
Multi-table Joins......................................................................................89
Exercise 14: Using Joins.................................................................................92
Outer Joins.....................................................................................................96
Unions...........................................................................................................101
UNION ALL...........................................................................................102
UNION Rules........................................................................................103
Exercise 15: Working with Unions.................................................................104

5. Conditional Processing with CASE.................................................109


Using CASE..................................................................................................109
Exercise 16: Working with CASE..................................................................114

Appendix 1. Inserting, Updating and Deleting Records....................119


INSERT.........................................................................................................119
Exercise 17: Inserting Records.....................................................................121
UPDATE........................................................................................................124
DELETE........................................................................................................124
Exercise 18: Updating and Deleting Records...............................................126

Version: 1.4.8. Printed: 2017-02-16. iii


Relational Database Basics

1. Relational Database Basics


In this lesson, you will learn...
1. About the history of SQL and relational databases.
2. How relational databases are structured.
3. About some of the most popular relational databases.
4. About the major SQL statements.
SQL stands for Structured Query Language and is pronounced either ess-que-el or
sequel. It is the language used by relational database management systems (RDBMS)
to access and manipulate data and to create, structure and destroy databases and
database objects.

1.1 Brief History of SQL


In 1970, Dr. E.F. Codd published "A Relational Model of Data for Large Shared
Data Banks," an article that outlined a model for storing and manipulating data using
tables. Shortly after Codd's article was published, IBM began working on creating
a relational database. Between 1979 and 1982, Oracle (then Relational Software,
Inc.), Relational Technology, Inc. (later acquired by Computer Associates), and
IBM all put out commercial relational databases, and by 1986 they all were using
SQL as the data query language.
In 1986, the American National Standards Institute (ANSI) standardized SQL. This
standard was updated in 1989, in 1992 (called SQL2), in 1999 (called SQL3), in
2003 (called SQL 2003), in 2006 (called SQL 2006), in 2008 (called SQL 2008),
and in 2011 (called SQL 2011). Standard SQL is sometimes called ANSI SQL. All
major relational databases support this standard but each has its own proprietary
extensions. Unless otherwise noted, the SQL taught in this course is the standard
ANSI SQL.

1.2 Relational Databases


A relational database at its simplest is a set of tables used for storing data. Each table
has a unique name and may relate to one or more other tables in the database through
common values.

Tables
A table in a database is a collection of rows and columns. Tables are also known as
entities or relations.

Version: 1.4.8. Printed: 2017-02-16. Page 1 of 129


Relational Database Basics

Rows
A row contains data pertaining to a single item or record in a table. Rows are also
known as records, instances, or tuples.

Columns
A column contains data representing a specific characteristic of the records in the
table. Columns are also known as fields, properties, or attributes.

Relationships
A relationship is a link between two tables (i.e, relations). Relationships make it
possible to find data in one table that pertains to a specific record in another table.

Datatypes
Each of a table's columns has a defined datatype that specifies the type of data that
can exist in that column. For example, the FirstName column might be defined
as varchar(20), indicating that it can contain a string of up to 20 characters.
Unfortunately, datatypes vary widely between databases.

Primary Keys
Most tables have a column or group of columns that can be used to identify records.
For example, an Employees table might have a column called EmployeeID that
is unique for every row. This makes it easy to keep track of a record over time and
to associate a record with records in other tables.

Foreign Keys
Foreign key columns are columns that link to primary key columns in other tables,
thereby creating a relationship. For example, the Customers table might have a
foreign key column called SalesRep that links to EmployeeID, the primary key
in the Employees table.

Relational Database Management System


A Relational Database Management System (RDBMS), commonly (but incorrectly)
called a database, is software for creating, manipulating, and administering a database.
For simplicity, we will often refer to RDBMSs as databases.

Page 2 of 129 © Copyright 2017 Webucator. All rights reserved.


Relational Database Basics

1.3 Popular Databases

Commercial Databases
Oracle

Oracle is the most popular relational database. It runs on both Unix and Windows.
It used to be many times more expensive than SQL Server and DB2, but it has come
down a lot in price. Oracle now offers a scaled down version that is free for personal
or business use: Oracle XE (Extended Edition).

SQL Server

SQL Server is Microsoft's database and, not surprisingly, only runs on Windows.
It has only a slightly higher market share than Oracle on Windows machines. Many
people find it easier to use than Oracle.

DB2

IBM's DB2 was one of the earliest players in the database market. It is still very
commonly used on mainframes and runs on both Windows and Unix.

Popular Open Source Databases


MySQL

Because of its small size, its speediness, and its very good documentation, MySQL
has quickly become the most popular open source database. MySQL is available on
both Windows and Unix, but it lacks some key features such as support for stored
procedures.

PostgreSQL

Until recently, PostgreSQL was the most popular open source database until that
spot was taken over by MySQL. PostgreSQL now calls itself "the world's most
advanced Open Source database software." It is certainly a featureful and robust
database management system and a good choice for people who want some of the
advanced features that MySQL doesn't yet have. Originally only available on Unix,
it became available on Windows in 2005.

Version: 1.4.8. Printed: 2017-02-16. Page 3 of 129


Relational Database Basics

1.4 SQL Statements

Database Manipulation Language (DML)


DML statements are used to work with data in an existing database. The most
common DML statements are:
• SELECT
• INSERT
• UPDATE
• DELETE

Database Definition Language (DDL)


DDL statements are used to structure objects in a database. The most common DDL
statements are:
• CREATE
• ALTER
• DROP

Database Control Language (DCL)


DCL statements are used for database administration. The most common DCL
statements are:
• GRANT
• DENY (SQL Server Only)
• REVOKE

1.5 Conclusion
We have covered a little bit of the history of SQL, how databases work, and the
common SQL statements. Now we will get into learning how to work with SQL.

Page 4 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

2. Simple SELECTs
In this lesson, you will learn...
1. About the database we'll be using in class.
2. To comment your SQL code.
3. To understand SQL syntax.
4. To select all rows from a table.
5. To sort record sets.
6. To filter records.
The SELECT statement is used to retrieve data from tables. SELECT statements
can be used to perform simple tasks such as retrieving records from a single table
or complicated tasks such as retrieving data from multiple tables with record grouping
and sorting. In this lesson, we will look at several of the more basic ways to retrieve
data from a single table.

2.1 Introduction to the Northwind Database


The Northwind database is a sample database used by Microsoft to demonstrate the
features of some of its products, including SQL Server and Microsoft Access. The
database contains the sales data for Northwind Traders, a fictitious specialty foods
export-import company.
Although the code taught in this class is not specific to Microsoft products, we use
the Northwind database for many of our examples because many people are already

Version: 1.4.8. Printed: 2017-02-16. Page 5 of 129


Simple SELECTs

familiar with it and because there are many resources for related learning that make
use of the same database.
The diagram below shows the table structure of the Northwind database.

The Northwind database has additional tables, but we will only be using the ones
shown above. In this lesson, we will explore some of these tables.

2.2 Some Basics

Comments
The standard SQL comment is two hyphens (--). However, some databases use
other forms of comments as shown in the table below.

Page 6 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

SQL Comments
-- # /* */
Example -- Comment # Comment /* Comment */
ANSI YES NO YES
SQL Server YES NO YES
Oracle YES NO YES
MySQL YES YES YES

The code sample below shows some sample comments. Note that MYSQL requires
a space after the -- but the other databases do not.
Code Sample
SimpleSelects/Demos/Comments.sql

1. -- Single-line comment
2. /*
3. Multi-line comment used in:
4. -SQL Server
5. -Oracle
6. -MySQL
7. */

Whitespace and Semi-colons


Whitespace is ignored in SQL statements. Multiple statements are separated with
semi-colons. The two statements in the sample below are equally valid.
Code Sample
SimpleSelects/Demos/WhiteSpace.sql

1. SELECT * FROM Employees;


2.
3. SELECT *
4. FROM Employees;

Case Sensitivity
SQL is not case sensitive. It is common practice to write reserved words in all capital
letters. User-defined names, such as table names and column names may or may
not be case sensitive depending on the operating system used.

Version: 1.4.8. Printed: 2017-02-16. Page 7 of 129


Simple SELECTs

2.3 SELECTing All Columns in All Rows


The following syntax is used to retrieve all declared columns in all rows of a table.

Syntax
SELECT table.*
FROM table;

-- OR

SELECT *
FROM table;

Code Sample
SimpleSelects/Demos/SelectAll.sql

1. -- Retrieve all columns in the Region table


2. SELECT *
3. FROM Region;

Code Explanation
The above SELECT statement will return the following results:

As you can see, the Region table has only two columns, RegionID and
RegionDescription, and four rows.

Page 8 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Exercise 1 Exploring the Tables


10 to 20 minutes

In this exercise, you will explore all the data in the Northwind database by selecting
all the rows of each of the tables.
1. Using your SQL editor, execute the necessary SQL queries to select all columns
of all rows from the tables below.
2. The number of records that should be returned is indicated in parentheses next
to the table name.
A. Categories (8)
B. Customers (91)
C. Employees (9)
D. Orders (830)
E. Products (81)
F. Shippers (3)
G. Suppliers (29)

Version: 1.4.8. Printed: 2017-02-16. Page 9 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/SelectAll.sql

1. SELECT * FROM Categories;


2. SELECT * FROM Customers;
3. SELECT * FROM Employees;
4. SELECT * FROM Orders;
5. SELECT * FROM Products;
6. SELECT * FROM Shippers;
7. SELECT * FROM Suppliers;

Page 10 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

2.4 SELECTing Specific Columns


While using SELECT * seems like a handy way to display all of the columns in a
table, its use is considered a poor practice in a production environment because of
potential performance problems. The following syntax is used to retrieve specific
columns in all rows of a table.

Syntax
SELECT table_name.column_name, table_name.column_name
FROM table;

-- OR

SELECT column, column


FROM table;

Code Sample
SimpleSelects/Demos/SelectCols.sql

1. /*
2. Select the FirstName and LastName columns from the Employees table.
3. */
4. SELECT FirstName, LastName
5. FROM Employees;

Code Explanation
The above SELECT statement will return the following results:

Version: 1.4.8. Printed: 2017-02-16. Page 11 of 129


Simple SELECTs

Exercise 2 SELECTing Specific Columns


5 to 15 minutes

In this exercise, you will practice selecting specific columns from tables in the
Northwind database.
1. Select CategoryName and Description from the Categories table.
2. Select ContactName, CompanyName, ContactTitle and Phone from
the Customers table.
3. Select EmployeeID, Title, FirstName, LastName, and Region from
the Employees table.
4. Select RegionID and RegionDescription from the Region table.
5. Select CompanyName, Fax, Phone and HomePage from the Suppliers
table.

Page 12 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Version: 1.4.8. Printed: 2017-02-16. Page 13 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/SelectCols.sql

1. SELECT CategoryName, Description


2. FROM Categories;
3.
4. SELECT ContactName, CompanyName, ContactTitle, Phone
5. FROM Customers;
6.
7. SELECT EmployeeID, Title, FirstName, LastName, Region
8. FROM Employees;
9.
10. SELECT RegionID, RegionDescription
11. FROM Region;
12.
13. SELECT CompanyName, Fax, Phone, HomePage
14. FROM Suppliers;

Page 14 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

2.5 Sorting Records


The ORDER BY clause of the SELECT statement is used to sort records.

Sorting by a Single Column


To sort by a single column, simply name that column in the ORDER BY clause.

Syntax
SELECT column, column
FROM table
ORDER BY column;

Note that columns in the ORDER BY clause do not have to appear in the SELECT
clause.
Code Sample
SimpleSelects/Demos/OrderBy1.sql

1. /*
2. Select the FirstName and LastName columns from the Employees table.
3. Sort by LastName.
4. */
5.
6. SELECT FirstName, LastName
7. FROM Employees
8. ORDER BY LastName;

Version: 1.4.8. Printed: 2017-02-16. Page 15 of 129


Simple SELECTs

Code Explanation
The above SELECT statement will return the following results:

Sorting By Multiple Columns


To sort by multiple columns, comma-delimit the column names in the ORDER BY
clause.

Syntax
SELECT column, column
FROM table
ORDER BY column, column;

Code Sample
SimpleSelects/Demos/OrderBy2.sql

1. /*
2. Select the Title, FirstName and LastName columns from the Employees
table.
3. Sort first by Title and then by LastName.
4. */
5.
6. SELECT Title, FirstName, LastName
7. FROM Employees
8. ORDER BY Title, LastName;

Page 16 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Code Explanation
The above SELECT statement will return the following results:

Ascending and Descending Sorts


By default, when an ORDER BY clause is used, records are sorted in ascending
order. This can be explicitly specified with the ASC keyword. To sort records in
descending order, use the DESC keyword.

Syntax
SELECT column, column
FROM table
ORDER BY column_position DESC, column_position ASC;

Code Sample
SimpleSelects/Demos/OrderBy4.sql

1. /*
2. Select the Title, FirstName and LastName columns from the Employees
table.
3. Sort first by Title in ascending order and then by LastName
4. in descending order.
5. */
6.
7. SELECT Title, FirstName, LastName
8. FROM Employees
9. ORDER BY Title ASC, LastName DESC;

Version: 1.4.8. Printed: 2017-02-16. Page 17 of 129


Simple SELECTs

Code Explanation
The above SELECT statement will return the following results:

Page 18 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Exercise 3 Sorting Results


5 to 15 minutes

In this exercise, you will practice sorting results in SELECT statements.


1. Select CategoryName and Description from the Categories table
sorted by CategoryName.
2. Select ContactName, CompanyName, ContactTitle, and Phone from
the Customers table sorted by Phone.
3. Create a report showing employees' first and last names and hire dates sorted
from newest to oldest employee. Note the way your database displays dates.
This display is quite often different from database to database.
4. Create a report showing Northwind's orders sorted by Freight from most
expensive to cheapest. Show OrderID, OrderDate, ShippedDate,
CustomerID, and Freight.
5. Select CompanyName, Fax, Phone, HomePage and Country from the
Suppliers table sorted by Country in descending order and then by
CompanyName in ascending order.
6. Create a list of employees showing title, first name, and last name. Sort by
Title in ascending order and then by LastName in descending order.

Version: 1.4.8. Printed: 2017-02-16. Page 19 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/Sorting.sql

1. SELECT CategoryName, Description


2. FROM Categories
3. ORDER BY CategoryName;
4.
5. SELECT ContactName, CompanyName, ContactTitle, Phone
6. FROM Customers
7. ORDER BY Phone;
8.
9. SELECT FirstName, LastName, HireDate
10. FROM Employees
11. ORDER BY HireDate DESC;
12.
13. SELECT OrderID, OrderDate, ShippedDate, CustomerID, Freight
14. FROM Orders
15. ORDER BY Freight DESC;
16.
17. SELECT CompanyName, Fax, Phone, HomePage, Country
18. FROM Suppliers
19. ORDER BY Country DESC, CompanyName;
20.
21. SELECT Title, FirstName, LastName
22. FROM Employees
23. ORDER BY Title ASC, LastName DESC;

Page 20 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

2.6 The WHERE Clause and Logical Operator Symbols


The WHERE clause is used to retrieve specific rows from tables. The WHERE clause
can contain one or more conditions that specify which rows should be returned.

Syntax
SELECT column, column
FROM table
WHERE conditions;

The following table shows the symbolic operators used in WHERE conditions.
SQL Symbol Operators
Operator Description
= Equals
<> Not Equal
> Greater Than
< Less Than
>= Greater Than or Equal To
<= Less Than or Equal To

Note that non-numeric values (e.g, dates and strings) in the WHERE clause must be
enclosed in single quotes. Some databases, like Oracle, treat all character data as
case sensitive. Other databases only treat character data as case sensitive in a handful
of functions. It's always easier to pretend all data is case sensitive in those databases
so you don't have to remember when it is and when it isn't. Examples are shown
below.

Checking for Equality


Code Sample
SimpleSelects/Demos/Where-Equal.sql

1. /*
2. Create a report showing the title and the first and last name
3. of all sales representatives.
4. */
5.
6. SELECT Title, FirstName, LastName
7. FROM Employees
8. WHERE Title = 'Sales Representative';

Version: 1.4.8. Printed: 2017-02-16. Page 21 of 129


Simple SELECTs

Code Explanation
The above SELECT statement will return the following results:

Checking for Inequality


Code Sample
SimpleSelects/Demos/Where-NotEqual.sql

1. /*
2. Create a report showing the first and last name of all employees
3. excluding sales representatives.
4. */
5.
6. SELECT FirstName, LastName
7. FROM Employees
8. WHERE Title <> 'Sales Representative';

Code Explanation
The above SELECT statement will return the following results:

Page 22 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Exercise 4 Using the WHERE Clause to Check for Equality or


Inequality
5 to 15 minutes

In this exercise, you will practice using the WHERE clause to check for equality and
inequality.
1. Create a report showing all the company names and contact names of
Northwind's customers in Buenos Aires.
2. Create a report showing the product name, unit price and quantity per unit of
all products that are out of stock.
3. Create a report showing the order date, shipped date, customer id, and freight
of all orders placed on May 19, 1997.
• Oracle users will have to use following date format: 'dd-mmm-yyyy'
(e.g, '19-May-1997').
• MySQL users will have to use following date format: 'yyyy-mm-dd'
(e.g, '1997-05-19').
• Microsoft users may use either of the above formats.
4. Create a report showing the first name, last name, and country of all employees
not in the United States.

Version: 1.4.8. Printed: 2017-02-16. Page 23 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/EqualityAndInequality.sql

1. SELECT CompanyName, ContactName


2. FROM Customers
3. WHERE City = 'Buenos Aires';
4.
5. SELECT ProductName, UnitPrice, QuantityPerUnit
6. FROM Products
7. WHERE UnitsInStock=0;
8.
9. /******************************
10. For the third problem, both of the solutions below will work in SQL
Server
11.
12. Oracle Solution
13. ******************************/
14. SELECT OrderDate, ShippedDate, CustomerID, Freight
15. FROM Orders
16. WHERE OrderDate = '19-May-1997';
17.
18. /******************************
19. MySQL Solution
20. ******************************/
21. SELECT OrderDate, ShippedDate, CustomerID, Freight
22. FROM Orders
23. WHERE OrderDate = '1997-05-19';
24.
25. SELECT FirstName, LastName, Country
26. FROM Employees
27. WHERE Country <> 'USA';

Page 24 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Checking for Greater or Less Than


The less than (<) and greater than (>) signs are used to compare numbers, dates,
and strings.
Code Sample
SimpleSelects/Demos/Where-GreaterThanOrEqual.sql

1. /*
2. Create a report showing the first and last name of all employees whose

3. last names start with a letter in the last half of the alphabet.
4. */
5.
6. SELECT FirstName, LastName
7. FROM Employees
8. WHERE LastName >= 'N';

Code Explanation
The above SELECT statement will return the following results:

Version: 1.4.8. Printed: 2017-02-16. Page 25 of 129


Simple SELECTs

Exercise 5 Using the WHERE Clause to Check for Greater or Less


Than
5 to 15 minutes

In this exercise, you will practice using the WHERE clause to check for values greater
than or less than a specified value.
1. Create a report that shows the employee id, order id, customer id, required date,
and shipped date of all orders that were shipped later than they were required.
2. Create a report that shows the city, company name, and contact name of all
customers who are in cities that begin with "A" or "B."
3. Create a report that shows all orders that have a freight cost of more than
$500.00.
4. Create a report that shows the product name, units in stock, units on order, and
reorder level of all products that are up for reorder.

Page 26 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Version: 1.4.8. Printed: 2017-02-16. Page 27 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/GreaterThanLessThan.sql

1. SELECT EmployeeID, OrderID, CustomerID, RequiredDate, ShippedDate


2. FROM Orders
3. WHERE ShippedDate > RequiredDate;
4.
5. SELECT City, CompanyName, ContactName
6. FROM Customers
7. WHERE City < 'C';
8.
9. SELECT OrderID, OrderDate, Freight
10. FROM Orders
11. WHERE Freight > 500;
12.
13. SELECT ProductName, UnitsInStock, UnitsOnOrder, ReorderLevel
14. FROM Products
15. WHERE UnitsInStock <= ReorderLevel;

Page 28 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Checking for NULL


When a field in a row has no value, it is said to be NULL. This is not the same as
having an empty string or a 0. Rather, it means that the field contains no value at
all. When checking to see if a field is NULL, you cannot use the equals sign (=);
rather, use the IS NULL expression.
Code Sample
SimpleSelects/Demos/Where-Null.sql

1. /*
2. Create a report showing the first and last names of
3. all employees whose region is unspecified.
4. */
5.
6. SELECT FirstName, LastName
7. FROM Employees
8. WHERE Region IS NULL;

Code Explanation
The above SELECT statement will return the following results:

Code Sample
SimpleSelects/Demos/Where-NotNull.sql

1. /*
2. Create a report showing the first and last names of all
3. employees who have a region specified.
4. */
5.
6. SELECT FirstName, LastName
7. FROM Employees
8. WHERE Region IS NOT NULL;

Version: 1.4.8. Printed: 2017-02-16. Page 29 of 129


Simple SELECTs

Code Explanation
The above SELECT statement will return the following results:

Page 30 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Exercise 6 Checking for NULL


5 to 15 minutes

In this exercise, you will practice selecting records with fields that have NULL values.
1. Create a report that shows the company name, contact name and fax number
of all customers that have a fax number.
2. Create a report that shows the first and last name of all employees who do not
report to anybody.

Version: 1.4.8. Printed: 2017-02-16. Page 31 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/Null.sql

1. SELECT CompanyName, ContactName, Fax


2. FROM Customers
3. WHERE Fax IS NOT NULL;
4.
5. SELECT FirstName, LastName
6. FROM Employees
7. WHERE ReportsTo IS NULL;

Page 32 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

WHERE and ORDER BY


When using WHERE and ORDER BY together, the WHERE clause must come before
the ORDER BY clause.
Code Sample
SimpleSelects/Demos/Where-OrderBy.sql

1. /*
2. Create a report showing the first and last name of all employees whose

3. last names start with a letter in the last half of the alphabet.
4. Sort by LastName in descending order.
5. */
6.
7. SELECT FirstName, LastName
8. FROM Employees
9. WHERE LastName >= 'N'
10. ORDER BY LastName DESC;

Code Explanation
The above SELECT statement will return the following results:

Version: 1.4.8. Printed: 2017-02-16. Page 33 of 129


Simple SELECTs

Exercise 7 Using WHERE and ORDER BY Together


5 to 15 minutes

In this exercise, you will practice writing SELECT statements that use both WHERE
and ORDER BY.
1. Create a report that shows the company name, contact name and fax number
of all customers that have a fax number. Sort by company name.
2. Create a report that shows the city, company name, and contact name of all
customers who are in cities that begin with "A" or "B." Sort by contact name
in descending order.

Page 34 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Version: 1.4.8. Printed: 2017-02-16. Page 35 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/Where-OrderBy.sql

1. SELECT CompanyName, ContactName, Fax


2. FROM Customers
3. WHERE Fax IS NOT NULL
4. ORDER BY CompanyName;
5.
6. SELECT City, CompanyName, ContactName
7. FROM Customers
8. WHERE City < 'C'
9. ORDER BY ContactName DESC;

Page 36 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

2.7 Checking Multiple Conditions with Boolean Operators

AND
AND can be used in a WHERE clause to find records that match more than one
condition.
Code Sample
SimpleSelects/Demos/Where-And.sql

1. /*
2. Create a report showing the first and last name of all
3. sales representatives whose title of courtesy is "Mr.".
4. */
5.
6. SELECT FirstName, LastName
7. FROM Employees
8. WHERE Title = 'Sales Representative'
9. AND TitleOfCourtesy = 'Mr.';

Code Explanation
The above SELECT statement will return the following results:

OR
OR can be used in a WHERE clause to find records that match at least one of several
conditions.

Version: 1.4.8. Printed: 2017-02-16. Page 37 of 129


Simple SELECTs

Code Sample
SimpleSelects/Demos/Where-Or.sql

1. /*
2. Create a report showing the first and last name and the city of all
3. employees who are from Seattle or Redmond.
4. */
5.
6. SELECT FirstName, LastName, City
7. FROM Employees
8. WHERE City = 'Seattle' OR City = 'Redmond';

Code Explanation
The above SELECT statement will return the following results:

Order of Evaluation
By default, SQL processes AND operators before it processes OR operators. To
illustrate how this works, take a look at the following example.
Code Sample
SimpleSelects/Demos/Where-AndOrPrecedence.sql

1. /*
2. Create a report showing the first and last name of all sales
3. representatives who are from Seattle or Redmond.
4. */
5.
6. SELECT FirstName, LastName, City, Title
7. FROM Employees
8. WHERE City = 'Seattle' OR City = 'Redmond'
9. AND Title = 'Sales Representative';

Page 38 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Code Explanation
The above SELECT statement will return the following results:

Notice that Laura Callahan is returned by the query even though she is not a sales
representative. This is because this query is looking for employees from Seattle OR
sales representatives from Redmond.
This can be fixed by putting the OR portion of the clause in parentheses.
Code Sample
SimpleSelects/Demos/Where-AndOrPrecedence2.sql

1. /*
2. Create a report showing the first and last name of all sales
3. representatives who are from Seattle or Redmond.
4. */
5.
6. SELECT FirstName, LastName, City, Title
7. FROM Employees
8. WHERE (City = 'Seattle' OR City = 'Redmond')
9. AND Title = 'Sales Representative';

Code Explanation
The parentheses specify that the OR portion of the clause should be evaluated first,
so the above SELECT statement will return the same results minus Laura Callahan.

If only to make the code more readable, it's a good idea to use parentheses whenever
the order of precedence might appear ambiguous.

Version: 1.4.8. Printed: 2017-02-16. Page 39 of 129


Simple SELECTs

Exercise 8 Writing SELECTs with Multiple Conditions


5 to 15 minutes

In this exercise, you will practice writing SELECT statements that filter records
based on multiple conditions.
1. Create a report that shows the first and last names and cities of employees from
cities other than Seattle in the state of Washington.
2. Create a report that shows the company name, contact title, city and country
of all customers in Mexico or in any city in Spain except Madrid.

Page 40 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Version: 1.4.8. Printed: 2017-02-16. Page 41 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/MultipleConditions.sql

1. SELECT FirstName, LastName, City


2. FROM Employees
3. WHERE Region = 'WA' AND City <> 'Seattle';
4.
5. SELECT CompanyName, ContactTitle, City, Country
6. FROM Customers
7. WHERE Country = 'Mexico' OR (Country = 'Spain'
8. AND City <> 'Madrid');

Page 42 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

2.8 The WHERE Clause and Logical Operator Keywords


The following table shows the word operators used in WHERE conditions.
SQL Word Operators
Operator Description
BETWEEN Returns values in an inclusive range
IN Returns values in a specified subset
LIKE Returns values that match a simple pattern
NOT Negates an operation

The BETWEEN Operator


The BETWEEN operator is used to check if field values are within a specified inclusive
range.
Code Sample
SimpleSelects/Demos/Where-Between.sql

1. /*
2. Create a report showing the first and last name of all employees
3. whose last names start with a letter between "J" and "M".
4. */
5.
6. SELECT FirstName, LastName
7. FROM Employees
8. WHERE LastName BETWEEN 'J' AND 'M';
9.
10. -- The above SELECT statement is the same as the one below.
11.
12. SELECT FirstName, LastName
13. FROM Employees
14. WHERE LastName >= 'J' AND LastName <= 'M';

Version: 1.4.8. Printed: 2017-02-16. Page 43 of 129


Simple SELECTs

Code Explanation
The above SELECT statements will both return the following results:

Note that a person with the last name "M" would be included in this report.

The IN Operator
The IN operator is used to check if field values are included in a specified
comma-delimited list.
Code Sample
SimpleSelects/Demos/Where-In.sql

1. /*
2. Create a report showing the title of courtesy and the first and
3. last name of all employees whose title of courtesy is "Mrs." or "Ms.".

4. */
5.
6. SELECT TitleOfCourtesy, FirstName, LastName
7. FROM Employees
8. WHERE TitleOfCourtesy IN ('Ms.','Mrs.');
9.
10. -- The above SELECT statement is the same as the one below
11.
12. SELECT TitleOfCourtesy, FirstName, LastName
13. FROM Employees
14. WHERE TitleOfCourtesy = 'Ms.' OR TitleOfCourtesy = 'Mrs.';

Page 44 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Code Explanation
The above SELECT statements will both return the following results:

The LIKE Operator


The LIKE operator is used to check if field values match a specified pattern.

The Percent Sign (%)

The percent sign (%) is used to match any zero or more characters.
Code Sample
SimpleSelects/Demos/Where-Like1.sql

1. /*
2. Create a report showing the title of courtesy and the first
3. and last name of all employees whose title of courtesy begins with "M".

4. */
5.
6. SELECT TitleOfCourtesy, FirstName, LastName
7. FROM Employees
8. WHERE TitleOfCourtesy LIKE 'M%';

Version: 1.4.8. Printed: 2017-02-16. Page 45 of 129


Simple SELECTs

Code Explanation
The above SELECT statement will return the following results:

The Underscore (_)

The underscore (_) is used to match any single character.


Code Sample
SimpleSelects/Demos/Where-Like2.sql

1. /*
2. Create a report showing the title of courtesy and the first and
3. last name of all employees whose title of courtesy begins with "M" and

4. is followed by any character and a period (.).


5. */
6.
7. SELECT TitleOfCourtesy, FirstName, LastName
8. FROM Employees
9. WHERE TitleOfCourtesy LIKE 'M_.';

Page 46 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Code Explanation
The above SELECT statement will return the following results:

Wildcards and Performance

Using wildcards can slow down performance, especially if they are used at the
beginning of a pattern. You should use them sparingly.

The NOT Operator


The NOT operator is used to negate an operation.
Code Sample
SimpleSelects/Demos/Where-Not.sql

1. /*
2. Create a report showing the title of courtesy and the first and last
name
3. of all employees whose title of courtesy is not "Ms." or "Mrs.".
4. */
5.
6. SELECT TitleOfCourtesy, FirstName, LastName
7. FROM Employees
8. WHERE NOT TitleOfCourtesy IN ('Ms.','Mrs.');

Code Explanation
The above SELECT statement will return the following results:

Version: 1.4.8. Printed: 2017-02-16. Page 47 of 129


Simple SELECTs

Exercise 9 More SELECTs with WHERE


5 to 15 minutes

In this exercise, you will practice writing SELECT statements that use WHERE with
word operators.
1. Create a report that shows the first and last names and birth date of all employees
born in the 1950s.
2. Create a report that shows the product name and supplier id for all products
supplied by Exotic Liquids, Grandma Kelly's Homestead, and Tokyo Traders.
Hint: you will need to first do a separate SELECT on the Suppliers table to find
the supplier ids of these three companies. You will need to escape the apostrophe
in "Grandma Kelly's Homestead" in the first separate SELECT. To do so, please
place another apostrophe in front of it.
3. Create a report that shows the shipping postal code, order id, and order date
for all orders with a ship postal code beginning with "02389".
4. Create a report that shows the contact name and title and the company name
for all customers whose contact title does not contain the word "Sales".

Page 48 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

Version: 1.4.8. Printed: 2017-02-16. Page 49 of 129


Simple SELECTs

Exercise Solution
SimpleSelects/Solutions/WordOperators.sql

1. /******************************
2. For the first problem, both of the solutions below will work in SQL
Server
3.
4. Oracle Solution
5. ******************************/
6. SELECT FirstName, LastName, BirthDate
7. FROM Employees
8. WHERE BirthDate BETWEEN '1-Jan-1950' AND '31-Dec-1959 23:59:59';
9.
10. /******************************
11. MySQL Solution
12. ******************************/
13. SELECT FirstName, LastName, BirthDate
14. FROM Employees
15. WHERE BirthDate BETWEEN '1950-01-01' AND '1959-12-31 23:59:59';
16.
17. /* The result of the following "HINT" query must be obtained first in
order to write the solution query for #2 */
18. select supplierid
19. from suppliers
20. where companyname in ('Exotic Liquids',
21. 'Grandma Kelly"s Homestead',
22. 'Tokyo Traders');
23.
24.
25. SELECT ProductName, SupplierID
26. FROM Products
27. WHERE SupplierID IN (1,3,4);
28.
29. SELECT ShipPostalCode, OrderID, OrderDate
30. FROM Orders
31. WHERE ShipPostalCode LIKE '02389%';
32.
33. SELECT ContactName, ContactTitle, CompanyName
34. FROM Customers
35. WHERE NOT ContactTitle LIKE '%Sales%';

Page 50 of 129 © Copyright 2017 Webucator. All rights reserved.


Simple SELECTs

2.9 Conclusion
In this lesson, you have learned a lot about creating reports with SELECT. However,
this is just the tip of the iceberg. SELECT statements can get a lot more powerful
and, of course, a lot more complicated.

Version: 1.4.8. Printed: 2017-02-16. Page 51 of 129


Simple SELECTs

Page 52 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

3. Advanced SELECTs
In this lesson, you will learn...
1. To use SELECT statements to retrieve calculated values.
2. To work with aggregate functions and grouping.
3. To work with SQL's data manipulation functions.

3.1 Calculated Fields


Calculated fields are fields that do not exist in a table, but are created in the SELECT
statement. For example, you might want to create FullName from FirstName
and LastName.

Concatenation
Concatenation is a fancy word for stringing together different words or characters.
SQL Server, Oracle and MySQL each has its own way of handling concatenation.
All three of the code samples below will return the following results:

In SQL Server, the plus sign (+) is used as the concatenation operator.

Version: 1.4.8. Printed: 2017-02-16. Page 53 of 129


Advanced SELECTs

Code Sample
AdvancedSelects/Demos/Concatenate-SqlServer.sql

1. -- Select the full name of all employees. SQL SERVER.


2.
3. SELECT FirstName + ' ' + LastName
4. FROM Employees;

In Oracle, the double pipe (||) is used as the concatenation operator, which is also
the ANSI/ISO concatenation operator.
Code Sample
AdvancedSelects/Demos/Concatenate-Oracle.sql

1. -- Select the full name of all employees. Oracle.


2.
3. SELECT FirstName || ' ' || LastName
4. FROM Employees;

MySQL does this in yet another way. There is no concatenation operator. Instead,
MySQL uses the CONCAT() function 1.
Code Sample
AdvancedSelects/Demos/Concatenate-MySQL.sql

1. -- Select the full name of all employees. MySQL.


2. SELECT CONCAT(FirstName, ' ', LastName)
3. FROM Employees;

Note that concatenation only works with strings. To concatenate other data types,
you must first convert them to strings. 2

Mathematical Calculations
Mathematical calculations in SQL are similar to those in other languages.

1. We'll look at functions more in Built-in Data Manipulation Functions (see page 67).
2. Conversion is covered briefly in Built-in Data Manipulation Functions (see page 67).

Page 54 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Mathematical Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Oracle does not support the modulus operator. Instead use
the MOD Function. My SQL supports both.)

Code Sample
AdvancedSelects/Demos/MathCalc.sql

1. /*
2. If the cost of freight is greater than or equal to $500.00,
3. it will now be taxed by 10%. Create a report that shows the
4. order id, freight cost, freight cost with this tax for all
5. orders of $500 or more.
6. */
7.
8. SELECT OrderID, Freight, Freight * 1.1
9. FROM Orders
10. WHERE Freight >= 500;

Version: 1.4.8. Printed: 2017-02-16. Page 55 of 129


Advanced SELECTs

Code Explanation
The above SELECT statement will return the following results:

Aliases
You will notice in the examples above for Microsoft SQL Server that the calculated
columns have the header "(No column name)". MySQL and Oracle display the
expression as the column header. Regardless, the keyword AS is used to provide a
named header for the column.
Note: you cannot use aliases in a WHERE clause!
Code Sample
AdvancedSelects/Demos/Alias.sql

1. SELECT OrderID, Freight, Freight * 1.1 AS FreightTotal


2. FROM Orders
3. WHERE Freight >= 500;

Code Explanation
As you can see, the third column now has the title "FreightTotal".

Page 56 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Exercise 10 Calculating Fields


10 to 20 minutes

In this exercise, you will practice writing SELECT statements with calculated fields.
1. Create a report that shows the unit price, quantity, discount, and the calculated
total price using these three fields. Using the appropriate columns from the
appropriate table, you'll find the total price of each item by using this formula:
unitprice * quantity * (1 - discount)
• Note for SQL Server users only: You will be using the Order Details
table. Because this table name has a space in it, you will need to put it in
double quotes in the FROM clause (e.g, FROM "Order Details").
2. Write a SELECT statement that outputs the following. It's okay if your result
set's rows are in a different order.

Version: 1.4.8. Printed: 2017-02-16. Page 57 of 129


Advanced SELECTs

Exercise Solution
AdvancedSelects/Solutions/Calculations.sql

1. /******************************
2. SQL Server Solutions
3. ******************************/
4. SELECT UnitPrice, Quantity, Discount, UnitPrice * Quantity * (1-Discount)
AS TotalPrice
5. FROM "Order Details";
6.
7. SELECT FirstName + ' ' + LastName + ' can be reached at x' + Extension
+ '.' AS ContactInfo
8. FROM Employees;
9.
10. /******************************
11. Oracle Solutions
12. ******************************/
13. SELECT UnitPrice, Quantity, Discount, UnitPrice * Quantity * (1-Discount)
AS TotalPrice
14. FROM Order_Details;
15.
16. SELECT FirstName || ' ' || LastName || ' can be reached at x' || Exten »»
sion || '.' AS ContactInfo
17. FROM Employees;
18.
19. /******************************
20. MySQL Solutions
21. ******************************/
22. SELECT UnitPrice, Quantity, Discount, UnitPrice * Quantity * (1-Discount)
AS TotalPrice
23. FROM Order_Details;
24.
25. SELECT CONCAT(FirstName, ' ', LastName, ' can be reached at x', Exten »»
sion, '.') AS ContactInfo
26. FROM Employees;

Page 58 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

3.2 Aggregate Functions and Grouping

Aggregate Functions
Aggregate functions are used to calculate results using field values from multiple
records. There are five common aggregate functions.
Common Aggregate Functions
Aggregate Function Description
COUNT() Returns the number of rows containing non-NULL values
in the specified field.
COUNT(*) Returns the number of rows in the intermediate result set.
SUM() Returns the sum of the non-NULL values in the specified
field.
AVG() Returns the average of the non-NULL values in the specified
field.
MAX() Returns the maximum of the non-NULL values in the
specified field.
MIN() Returns the minimum of the non-NULL values in the
specified field.

Code Sample
AdvancedSelects/Demos/Aggregate-Count.sql

1. -- Find the Number of Employees


2.
3. SELECT COUNT(*) AS NumEmployees
4. FROM Employees;

Code Explanation
Returns 9.

Version: 1.4.8. Printed: 2017-02-16. Page 59 of 129


Advanced SELECTs

Code Sample
AdvancedSelects/Demos/Aggregate-Sum.sql

1. -- Find the Total Number of Units Ordered of Product ID 3


2.
3. /******************************
4. SQL Server
5. ******************************/
6. SELECT SUM(Quantity) AS TotalUnits
7. FROM "Order Details"
8. WHERE ProductID=3;
9.
10. /******************************
11. Oracle and MySQL
12. ******************************/
13. SELECT SUM(Quantity) AS TotalUnits
14. FROM Order_Details
15. WHERE ProductID=3;

Code Explanation
Returns 328.
Code Sample
AdvancedSelects/Demos/Aggregate-Avg.sql

1. -- Find the Average Unit Price of Products


2.
3. SELECT AVG(UnitPrice) AS AveragePrice
4. FROM Products;

Code Explanation
Returns 28.8663.
Code Sample
AdvancedSelects/Demos/Aggregate-MinMax.sql

1. -- Find the Earliest and Latest Dates of Hire


2.
3. SELECT MIN(HireDate) AS FirstHireDate,
4. MAX(HireDate) AS LastHireDate
5. FROM Employees;

Page 60 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Code Explanation
The above SELECT statement will return April 1, 1992 and November 15, 1994 as
the FirstHireDate and LastHireDate, respectively. The date format will
vary from database to database.

Grouping Data
GROUP BY

With the GROUP BY clause, aggregate functions can be applied to groups of records
based on column values. Whenever the SELECT clause of your SELECT statement
includes column values and aggregate functions, you must include the GROUP BY
clause. The GROUP BY clause must list all of the column values used in the SELECT
clause. For example, the following code will return the number of employees in
each city (a column value).
Code Sample
AdvancedSelects/Demos/Aggregate-GroupBy.sql

1. -- Retrieve the number of employees in each city


2.
3. SELECT City, COUNT(EmployeeID) AS NumEmployees
4. FROM Employees
5. GROUP BY City;

The above SELECT statement will return the following results:

HAVING

The HAVING clause is used to filter grouped data. Therefore, whenever you want
to filter data based on an aggregate function, you do so in the HAVING clause. For

Version: 1.4.8. Printed: 2017-02-16. Page 61 of 129


Advanced SELECTs

example, the following code specifies that we only want information on cities that
have more than one employee.
Code Sample
AdvancedSelects/Demos/Aggregate-Having.sql

1. /*
2. Retrieve the number of employees in each city
3. in which there are at least 2 employees.
4. */
5.
6. SELECT City, COUNT(EmployeeID) AS NumEmployees
7. FROM Employees
8. GROUP BY City
9. HAVING COUNT(EmployeeID) > 1;

The above SELECT statement will return the following results:

Order of Clauses

1. SELECT
2. FROM
3. WHERE
4. GROUP BY
5. HAVING
6. ORDER BY

Page 62 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Code Sample
AdvancedSelects/Demos/Aggregate-OrderOfClauses.sql

1. /*
2. Find the number of sales representatives in each city that contains
3. at least 2 sales representatives. Order by the number of employees.
4. */
5.
6. SELECT City, COUNT(EmployeeID) AS NumEmployees
7. FROM Employees
8. WHERE Title = 'Sales Representative'
9. GROUP BY City
10. HAVING COUNT(EmployeeID) > 1
11. ORDER BY NumEmployees;

The above SELECT statement will return the following results:

Grouping Rules

• Every non-aggregate column that appears in the SELECT clause must also
appear in the GROUP BY clause.
• You may not use aliases in the HAVING clause.3
• You may use aliases in the ORDER BY clause.
• When you want to filter out rows from your result set based on aggregate
functions, you must use the HAVING clause.
• You should declare column alilases for any calculated fields in the SELECT
clause.
• You may not use aggregate functions in the WHERE clause.

3. MySQL allows usage of aliases in the HAVING clause, but you may want to avoid this to keep your code as cross-database
compatible as possible.

Version: 1.4.8. Printed: 2017-02-16. Page 63 of 129


Advanced SELECTs

Exercise 11 Working with Aggregate Functions


10 to 20 minutes

In this exercise, you will practice working with aggregate functions. For all of these
questions, it's okay if your result set's rows are in a different order.
1. Create a report that returns the following from the Order_Details table.

The report should only return rows for which TotalUnits is less than 200.
2. Create a report that returns the following from the Products table.

The report should only return rows for which the average unit price of a product
is greater than 70.
3. Create a report that returns the following from the Orders table.

NumOrders represents the number of orders placed by a certain customer.


Only return rows where NumOrders is greater than 15.
Query number 2 above has something strange about it. It is, in fact, a ridiculous
query. Why? Try to get the exact same results without using an aggregate function.

Page 64 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Version: 1.4.8. Printed: 2017-02-16. Page 65 of 129


Advanced SELECTs

Exercise Solution
AdvancedSelects/Solutions/Grouping.sql

1. SELECT ProductID, SUM(Quantity) AS TotalUnits


2. FROM Order_Details /* SQL Server users should use "Order Details" */
3. GROUP BY ProductID
4. HAVING SUM(Quantity) < 200;
5.
6. SELECT ProductID, AVG(UnitPrice) AS AveragePrice
7. FROM Products
8. GROUP BY ProductID
9. HAVING AVG(UnitPrice) > 70
10. ORDER BY AveragePrice;
11.
12. SELECT CustomerID, COUNT(OrderID) AS NumOrders
13. FROM Orders
14. GROUP BY CustomerID
15. HAVING COUNT(OrderID) > 15
16. ORDER BY NumOrders DESC;
17.
18. /*CHALLENGE ANSWER:*/
19. SELECT ProductID, UnitPrice
20. FROM Products
21. WHERE UnitPrice > 70
22. ORDER BY UnitPrice;

Page 66 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Selecting Distinct Records


The DISTINCT keyword is used to select distinct combinations of column values
from the intermediate result set. For example, the following example shows how
you would find all the distinct cities in which Northwind has employees.
Code Sample
AdvancedSelects/Demos/Distinct.sql

1. /*
2. Find all the distinct cities in which Northwind has employees.
3. */
4.
5. SELECT DISTINCT City
6. FROM Employees
7. ORDER BY City

DISTINCT is often used with aggregate functions. The following example shows
how DISTINCT can be used to find out in how many different cities Northwind
has employees.
Code Sample
AdvancedSelects/Demos/Distinct-Count.sql

1. /*
2. Find out in how many different cities Northwind has employees.
3. */
4.
5. SELECT COUNT(DISTINCT City) AS NumCities
6. FROM Employees

3.3 Built-in Data Manipulation Functions


In this section, we will discuss some of the more common built-in data manipulation
functions. Unfortunately, the functions differ greatly between databases, so you
should be sure to check your database documentation when using these functions.
The tables below show some of the more common math, string, and date functions.

Version: 1.4.8. Printed: 2017-02-16. Page 67 of 129


Advanced SELECTs

Common Math Functions


Common Math Functions
Description SQL Server Oracle MySQL
Absolute value ABS ABS ABS
Smallest integer >= CEILING CEIL CEILING
value
Round down to FLOOR FLOOR FLOOR
nearest integer
Power POWER POWER POWER
Round ROUND ROUND ROUND
Square root SQRT SQRT SQRT
Formatting numbers CAST(num AS CAST(num AS FORMAT(num,2)
to two decimal decimal(8,2)) decimal(8,2)) or CAST(num AS
places decimal(8,2))

Code Sample
AdvancedSelects/Demos/Functions-Math1.sql

1. /*
2. Select freight as is and
3. freight rounded to the first decimal (e.g, 1.150 becomes 1.200)
4. from the Orders tables
5. */
6.
7. SELECT Freight, ROUND(Freight,1) AS ApproxFreight
8. FROM Orders;

Page 68 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Code Explanation
The above SELECT statement will return the following results (not all rows shown):

Version: 1.4.8. Printed: 2017-02-16. Page 69 of 129


Advanced SELECTs

Code Sample
AdvancedSelects/Demos/Functions-Math2.sql

1. /*
2. Select the unit price as is and
3. unit price as a CHAR(10)
4. from the Products tables
5. */
6. SELECT UnitPrice, CAST(UnitPrice AS CHAR(10))
7. FROM Products;
8.
9. /******************************
10. ADD CONCATENATION
11. ******************************/
12. /******************************
13. SQL Server
14. ******************************/
15. SELECT UnitPrice, '$' + CAST(UnitPrice AS CHAR(10))
16. FROM Products;
17.
18. /******************************
19. Oracle
20. ******************************/
21. SELECT UnitPrice, '$' || CAST(UnitPrice AS CHAR(10))
22. FROM Products;
23.
24. /******************************
25. MySQL
26. ******************************/
27. SELECT UnitPrice, CONCAT('$',CAST(UnitPrice AS CHAR(10)))
28. FROM Products;

Page 70 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Code Explanation
The above SELECT statement will return the following results (not all rows shown):

Note that you would round to a whole number by passing 0 as the second parameter:
ROUND(field,0); and to the tens place by passing -1: ROUND(field,-1).

Common String Functions


Common String Functions
Description SQL Server Oracle MySQL
Convert characters to lowercase LOWER LOWER LOWER
Convert characters to uppercase UPPER UPPER UPPER
Remove trailing blank spaces RTRIM RTRIM RTRIM
Remove leading blank spaces LTRIM LTRIM LTRIM
Returns part of a string SUBSTRING SUBSTR SUBSTRING

Code Sample
AdvancedSelects/Demos/Functions-String1.sql

1. /*
2. Select first and last name from employees in all uppercase letters
3. */
4. SELECT UPPER(FirstName), UPPER(LastName)
5. FROM Employees;

Version: 1.4.8. Printed: 2017-02-16. Page 71 of 129


Advanced SELECTs

Code Explanation
The above SELECT statement will return the following results:

Code Sample
AdvancedSelects/Demos/Functions-String2.sql

1. -- Select the first 10 characters, starting at position 1 of the string,


of each customer's address
2.
3. /******************************
4. SQL Server and MySQL
5. ******************************/
6. SELECT SUBSTRING(Address,1,10)
7. FROM Customers;
8.
9. /******************************
10. Oracle
11. ******************************/
12. SELECT SUBSTR(Address,1,10)
13. FROM Customers;

Page 72 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Code Explanation
The above SELECT statement will return the following results (not all rows shown):

Common Date Functions


Common Date Functions
Description SQL Server Oracle MySQL
Date addition DATEADD (use +) DATE_ADD
Date subtraction DATEDIFF (use -) DATEDIFF
Convert date to DATENAME TO_CHAR DATE_FORMAT
string
Convert date to DATEPART TO_NUMBER(TO_CHAR) EXTRACT
number
Get current date and GETDATE() SYSDATE NOW()
time
Get current date CURRENT_DATE CURRENT_DATE
Get date as number TO_DAYS
of days since the
year 0

Version: 1.4.8. Printed: 2017-02-16. Page 73 of 129


Advanced SELECTs

Code Sample
AdvancedSelects/Demos/Functions-Date1.sql

1. -- Find the hiring age of each employee


2.
3. /******************************
4. SQL Server
5. ******************************/
6. SELECT LastName, BirthDate, HireDate, DATEDIFF(year,BirthDate,HireDate)
AS HireAge
7. FROM Employees
8. ORDER BY HireAge;
9.
10. /******************************
11. Oracle
12. ******************************/
13. SELECT LastName, BirthDate, HireDate, FLOOR((HireDate - Birth »»
Date)/365.25) AS HireAge
14. FROM Employees
15. ORDER BY HireAge;
16.
17. /******************************
18. MySQL
19. ******************************/
20. -- Find the hiring age of each employee
21. -- in versions of MySQL prior to 4.1.1
22. SELECT LastName, BirthDate, HireDate, YEAR(HireDate)-YEAR(BirthDate)
AS HireAge
23. FROM Employees;
24.
25. -- In MySQL 4.1.1 and later, DATEDIFF() returns the number of days be »»
tween
26. -- two dates. You can then divide and floor to get age.
27. SELECT LastName, BirthDate, HireDate, FLOOR(DATEDIFF(HireDate,Birth »»
Date)/365) AS HireAge
28. FROM Employees
29. ORDER BY HireAge;

Page 74 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Code Explanation
The above SELECT statement will return the following results in SQL Server:

And like this in Oracle:

Note for SQL Server users: SQL Server is subtracting the year the employee was
born from the year (s)he was hired. This does not give us an accurate age. We'll fix
this in an upcoming exercise. The same note applies to MySQL users who are using
prior to version 4.1.1.

Version: 1.4.8. Printed: 2017-02-16. Page 75 of 129


Advanced SELECTs

Code Sample
AdvancedSelects/Demos/Functions-Date2.sql

1. -- Find the Birth month for every employee


2.
3. /******************************
4. SQL Server
5. ******************************/
6. SELECT FirstName, LastName, DATENAME(month,BirthDate) AS BirthMonth
7. FROM Employees
8. ORDER BY DATEPART(month,BirthDate);
9.
10. /******************************
11. Oracle
12. ******************************/
13. SELECT FirstName, LastName, TO_CHAR(BirthDate, 'Month') AS BirthMonth
14. FROM Employees
15. ORDER BY TO_NUMBER(TO_CHAR(BirthDate,'MM'));
16.
17. /******************************
18. MySQL
19. ******************************/
20. SELECT FirstName, LastName, DATE_FORMAT(BirthDate, '%M') AS BirthMonth

21. FROM Employees


22. ORDER BY EXTRACT(MONTH FROM BirthDate);

Code Explanation
The above SELECT statement will return the following results:

Page 76 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

Exercise 12 Data Manipulation Functions


10 to 20 minutes

In this exercise, you will practice using data manipulation functions.


1. Create a report that shows the units in stock, unit price, the total price value of
all units in stock, the total price value of all units in stock rounded down, and
the total price value of all units in stock rounded up. Sort by the total price
value descending.
2. SQL SERVER AND MYSQL (if using PRIOR to 4.1.1) USERS ONLY: In
an earlier demo (see page 74), you saw a report that returned the age of each
employee when hired. That report was not entirely accurate as it didn't account
for the month and day the employee was born. Fix that report, showing both
the original (inaccurate) hire age and the actual hire age. The result will look
like this.

3. Create a report that shows the first and last names and birth month (as a string)
for each employee born in the current month. Note: if the current month is
April, June, October, or November, you should get no results.
4. Create a report that shows the contact title in all lowercase letters of each
customer contact.

Version: 1.4.8. Printed: 2017-02-16. Page 77 of 129


Advanced SELECTs

Exercise Solution
AdvancedSelects/Solutions/Functions.sql

1. /******************************
2. SQL Server
3. ******************************/
4. SELECT UnitsInStock, UnitPrice,
5. UnitsInStock * UnitPrice AS TotalPrice,
6. FLOOR(UnitsInStock * UnitPrice) AS TotalPriceDown,
7. CEILING(UnitsInStock * UnitPrice) AS TotalPriceUp
8. FROM Products
9. ORDER BY TotalPrice DESC;
10.
11. SELECT DATEDIFF(day,BirthDate,HireDate)/365.25 AS HireAgeAccurate,
12. DATEDIFF(year,BirthDate,HireDate) AS HireAgeInaccurate
13. FROM Employees;
14.
15. SELECT FirstName, LastName, DATENAME(month,BirthDate) AS BirthMonth
16. FROM Employees
17. WHERE DATEPART(month,BirthDate) = DATEPART(month,GETDATE());
18.
19. SELECT LOWER(ContactTitle) AS Title
20. FROM Customers;
21.
22. /******************************
23. Oracle
24. ******************************/
25. SELECT UnitsInStock, UnitPrice,
26. UnitsInStock * UnitPrice AS TotalPrice,
27. FLOOR(UnitsInStock * UnitPrice) AS TotalPriceDown,
28. CEIL(UnitsInStock * UnitPrice) AS TotalPriceUp
29. FROM Products
30. ORDER BY TotalPrice DESC;
31.
32. SELECT FLOOR((HireDate - BirthDate)/365.25) AS HireAgeInAccurate,
33. (HireDate - BirthDate)/365.25 AS HireAgeAccurate
34. FROM Employees;
35.
36.
37. SELECT FirstName, LastName, TO_CHAR(BirthDate,'MONTH') AS BirthMonth
38. FROM Employees
39. WHERE TO_CHAR(BirthDate,'MM') = TO_CHAR(SYSDATE,'MM');

Page 78 of 129 © Copyright 2017 Webucator. All rights reserved.


Advanced SELECTs

40.
41. SELECT LOWER(ContactTitle) AS Title
42. FROM Customers;
43.
44. /******************************
45. MySQL
46. ******************************/
47. SELECT UnitsInStock, UnitPrice,
48. UnitsInStock * UnitPrice AS TotalPrice,
49. FLOOR(UnitsInStock * UnitPrice) AS TotalPriceDown,
50. CEILING(UnitsInStock * UnitPrice) AS TotalPriceUp
51. FROM Products
52. ORDER BY TotalPrice DESC;
53.
54. SELECT (TO_DAYS(HireDate)-TO_DAYS(BirthDate))/365.25 AS HireAgeAccurate,

55. YEAR(HireDate)-YEAR(BirthDate) AS HireAgeInaccurate


56. FROM Employees;
57.
58. SELECT FirstName, LastName, DATE_FORMAT(BirthDate, '%M') AS BirthMonth

59. FROM Employees


60. WHERE EXTRACT(MONTH FROM BirthDate) = EXTRACT(MONTH FROM NOW());
61.
62. SELECT LOWER(ContactTitle) AS Title
63. FROM Customers;

Version: 1.4.8. Printed: 2017-02-16. Page 79 of 129


Advanced SELECTs

3.4 Conclusion
In this lesson, you have continued to use SELECT to create reports from data stored
in a single table. In the next lesson, you will learn to create reports from data in
multiple tables.

Page 80 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

4. Subqueries, Joins and Unions


In this lesson, you will learn...
1. To write queries with subqueries.
2. To select columns from multiple tables with joins.
3. To select records from multiple result sets with unions.

4.1 Subqueries
Subqueries are queries embedded in queries. They are used to retrieve data from
one table based on data in another table. They generally are used when tables have
some kind of relationship. For example, in the Northwind database, the Orders
table has a CustomerID field, which references a customer in the Customers
table. Retrieving the CustomerID for a specific order is pretty straightforward.
Code Sample
SubqueriesJoinsUnions/Demos/Subquery-SelectCustomerID.sql

1. /*
2. Find the CustomerID of the company that placed order 10290.
3. */
4.
5. SELECT CustomerID
6. FROM Orders
7. WHERE OrderID = 10290;

Code Explanation
This will return COMMI, which is very likely meaningless to the people reading
the report. The next query uses a subquery to return a meaningful result.
Code Sample
SubqueriesJoinsUnions/Demos/Subquery-SelectCompanyName.sql

1. -- Find the name of the company that placed order 10290.


2.
3. SELECT CompanyName
4. FROM Customers
5. WHERE CustomerID = (SELECT CustomerID
6. FROM Orders
7. WHERE OrderID = 10290);

Version: 1.4.8. Printed: 2017-02-16. Page 81 of 129


Subqueries, Joins and Unions

Code Explanation
The above code returns Comércio Mineiro, which is a lot more useful than
COMMI.
The subquery can contain any valid SELECT statement, but it must return a single
column with the expected number of results. For example, if the subquery returns
only one result, then the main query can check for equality, inequality, greater than,
less than, etc. On the other hand, if the subquery returns more than one record, the
main query must check to see if a field value is (or is NOT) IN the set of values
returned.
Code Sample
SubqueriesJoinsUnions/Demos/Subquery-IN.sql

1. -- Find the Companies that placed orders in 1997


2.
3. /******************************
4. Both of the queries below will work in SQL Server
5.
6. Oracle
7. ******************************/
8. SELECT CompanyName
9. FROM Customers
10. WHERE CustomerID IN (SELECT CustomerID
11. FROM Orders
12. WHERE OrderDate BETWEEN '1-Jan-1997' AND '31-Dec-1997');
13.
14. /******************************
15. MySQL
16. ******************************/
17. SELECT CompanyName
18. FROM Customers
19. WHERE CustomerID IN (SELECT CustomerID
20. FROM Orders
21. WHERE OrderDate BETWEEN '1997-01-01' AND '1997-12-31');

Page 82 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

Code Explanation
The above SELECT statement will return the following results:

Version: 1.4.8. Printed: 2017-02-16. Page 83 of 129


Subqueries, Joins and Unions

Exercise 13 Subqueries
20 to 30 minutes

In this exercise, you will practice writing subqueries.


1. Create a report that shows the product name and supplier id for all products
supplied by Exotic Liquids, Grandma Kelly's Homestead, and Tokyo Traders.
• You will need to escape the apostrophe in "Grandma Kelly's Homestead."
To do so, place another apostrophe in front of it. For example,
SELECT *
FROM Suppliers
WHERE CompanyName='Grandma Kelly''s Homestead';

2. Create a report that shows all products by name that are in the Seafood category.
3. Create a report that shows all companies by name that sell products in
CategoryID 8.
4. Create a report that shows all companies by name that sell products in the
Seafood category.

Page 84 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

Version: 1.4.8. Printed: 2017-02-16. Page 85 of 129


Subqueries, Joins and Unions

Exercise Solution
SubqueriesJoinsUnions/Solutions/Subqueries.sql

1. SELECT ProductName, SupplierID


2. FROM Products
3. WHERE SupplierID IN (SELECT SupplierID
4. FROM Suppliers
5. WHERE CompanyName IN
6. ('Exotic Liquids', 'Grandma Kelly''s Homestead', 'Tokyo Traders'));

7.
8. SELECT ProductName
9. FROM Products
10. WHERE CategoryID = (SELECT CategoryID
11. FROM Categories
12. WHERE CategoryName = 'Seafood');
13.
14. SELECT CompanyName
15. FROM Suppliers
16. WHERE SupplierID IN (SELECT SupplierID
17. FROM Products
18. WHERE CategoryID = 8);
19.
20. SELECT CompanyName
21. FROM Suppliers
22. WHERE SupplierID IN (SELECT SupplierID
23. FROM Products
24. WHERE CategoryID = (SELECT CategoryID
25. FROM Categories
26. WHERE CategoryName = 'Seafood'));

Page 86 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

4.2 Joins
How can we find out
• Which products are provided by which suppliers?
• Which customers placed which orders?
• Which customers are buying which products?
Such reports require data from multiple tables. Enter joins.

Syntax
SELECT table1.column, table2.column
FROM table1 JOIN table2
ON (table1.column=table2.column)
WHERE conditions

Creating a report that returns the employee id and order id from the Orders table
is not difficult.
Code Sample
SubqueriesJoinsUnions/Demos/Joins-NoJoin.sql

1. -- Find the EmployeeID and OrderID for all orders


2.
3. SELECT EmployeeID, OrderID
4. FROM Orders;

But this is not very useful as we cannot tell who the employee is that got this order.
The next sample shows how we can use a join to make the report more useful.
Code Sample
SubqueriesJoinsUnions/Demos/Joins-EmployeeOrders.sql

1. -- Create a report showing employee orders.


2.
3. SELECT Employees.EmployeeID, Employees.FirstName,
4. Employees.LastName, Orders.OrderID, Orders.OrderDate
5. FROM Employees JOIN Orders ON
6. (Employees.EmployeeID = Orders.EmployeeID)
7. ORDER BY Orders.OrderDate;

Version: 1.4.8. Printed: 2017-02-16. Page 87 of 129


Subqueries, Joins and Unions

Code Explanation
The above SELECT statement will return the following results:

Table names are used as prefixes of the column names to identify the table in which
to find the column. Although this is only required when the column name exists in
both tables, it is always a good idea to include the prefixes as it makes the code more
efficient and easier to read. Some people and books call these prefixes "qualifiers".

Table Aliases
Using full table names as prefixes can make SQL queries unnecessarily wordy.
Table aliases can make the code a little more concise. The example below, which
is identical in functionality to the query above, illustrates the use of table aliases.

Page 88 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

Code Sample
SubqueriesJoinsUnions/Demos/Joins-Aliases.sql

1. -- Create a report showing employee orders using Aliases.


2.
3. SELECT e.EmployeeID, e.FirstName, e.LastName,
4. o.OrderID, o.OrderDate
5. FROM Employees e JOIN Orders o ON
6. (e.EmployeeID = o.EmployeeID)
7. ORDER BY o.OrderDate;

Multi-table Joins
Multi-table joins can get very complex and may also take a long time to process,
but the syntax is relatively straightforward.

Syntax
SELECT table1.column, table2.column, table3.column
FROM table1
JOIN table2 ON (table1.column=table2.column)
JOIN table3 ON (table2.column=table3.column)
WHERE conditions

Note that, to join with a table, that table must be in the FROM clause or must already
be joined with the table in the FROM clause. Consider the following.

SELECT table1.column, table2.column, table3.column


FROM table1
JOIN table3 ON (table2.column=table3.column)
JOIN table2 ON (table1.column=table2.column)
WHERE conditions

The above code would break because it attempts to join table3 with table2
before table2 has been joined with table1.

Version: 1.4.8. Printed: 2017-02-16. Page 89 of 129


Subqueries, Joins and Unions

Code Sample
SubqueriesJoinsUnions/Demos/Joins-MultiTable.sql

1. /*
2. Create a report showing the Order ID, the name of the company that
placed the order,
3. and the first and last name of the associated employee.
4. Only show orders placed after January 1, 1998 that shipped after they
were required.
5. Sort by Company Name.
6. */
7.
8. /******************************
9. Both of the queries below will work in SQL Server
10.
11. Oracle
12. ******************************/
13. SELECT o.OrderID, c.CompanyName, e.FirstName, e.LastName
14. FROM Orders o
15. JOIN Employees e ON (e.EmployeeID = o.EmployeeID)
16. JOIN Customers c ON (c.CustomerID = o.CustomerID)
17. WHERE o.ShippedDate > o.RequiredDate AND o.OrderDate > '1-Jan-1998'
18. ORDER BY c.CompanyName;
19.
20. /******************************
21. MySQL
22. ******************************/
23. SELECT o.OrderID, c.CompanyName, e.FirstName, e.LastName
24. FROM Orders o
25. JOIN Employees e ON (e.EmployeeID = o.EmployeeID)
26. JOIN Customers c ON (c.CustomerID = o.CustomerID)
27. WHERE o.ShippedDate > o.RequiredDate AND o.OrderDate > '1998-01-01'
28. ORDER BY c.CompanyName;

Page 90 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

Code Explanation
The above SELECT statement will return the following results:

Version: 1.4.8. Printed: 2017-02-16. Page 91 of 129


Subqueries, Joins and Unions

Exercise 14 Using Joins


25 to 40 minutes

In this exercise, you will practice using joins.


1. Create a report that shows the order ids and the associated employee names for
orders that shipped after the required date. It should return the following. There
should be 37 rows returned.

2. Create a report that shows the total quantity of products (from the
Order_Details table) ordered. Only show records for products for which

Page 92 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

the quantity ordered is fewer than 200. The report should return the following
5 rows.

3. Create a report that shows the total number of orders by Customer since
December 31, 1996. The report should only return rows for which the
NumOrders is greater than 15. The report should return the following 5 rows.

4. Create a report that shows the company name, order id, and total price of all
products of which Northwind has sold more than $10,000 worth. There is no
need for a GROUP BY clause in this report.

Version: 1.4.8. Printed: 2017-02-16. Page 93 of 129


Subqueries, Joins and Unions

Exercise Solution
SubqueriesJoinsUnions/Solutions/Joins.sql

1. SELECT e.FirstName, e.LastName, o.OrderID


2. FROM Employees e JOIN Orders o ON
3. (e.EmployeeID = o.EmployeeID)
4. WHERE o.RequiredDate < o.ShippedDate
5. ORDER BY e.LastName, e.FirstName;
6.
7. SELECT p.ProductName, SUM(od.Quantity) AS TotalUnits
8. FROM Order_Details od JOIN Products p ON
9. (p.ProductID = od.ProductID)
10. GROUP BY p.ProductName
11. HAVING SUM(Quantity) < 200;
12.
13. /******************************
14. For the third problem, both of the solutions below will work in SQL
Server
15.
16. Oracle Solution
17. ******************************/
18. SELECT c.CompanyName, COUNT(o.OrderID) AS NumOrders
19. FROM Customers c JOIN Orders o ON
20. (c.CustomerID = o.CustomerID)
21. WHERE OrderDate > '31-Dec-1996'
22. GROUP BY c.CompanyName
23. HAVING COUNT(o.OrderID) > 15
24. ORDER BY NumOrders DESC;
25.
26. /******************************
27. MySQL
28. ******************************/
29. SELECT c.CompanyName, COUNT(o.OrderID) AS NumOrders
30. FROM Customers c JOIN Orders o ON
31. (c.CustomerID = o.CustomerID)
32. WHERE OrderDate > '1996-12-31'
33. GROUP BY c.CompanyName
34. HAVING COUNT(o.OrderID) > 15
35. ORDER BY NumOrders DESC;
36.
37. SELECT c.CompanyName, o.OrderID,
38. od.UnitPrice * od.Quantity * (1-od.Discount) AS TotalPrice

Page 94 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

39. FROM Order_Details od


40. JOIN Orders o ON (o.OrderID = od.OrderID)
41. JOIN Customers c ON (c.CustomerID = o.CustomerID)
42. WHERE od.UnitPrice * od.Quantity * (1-od.Discount) > 10000
43. ORDER BY TotalPrice DESC;
44.
45. /*
46. SQL Server users will replace Order_Details with "Order Details"
47. */

Version: 1.4.8. Printed: 2017-02-16. Page 95 of 129


Subqueries, Joins and Unions

4.3 Outer Joins


So far, all the joins we have worked with are inner joins, meaning that rows are only
returned that have matches in both tables. For example, when doing an inner join
between the Employees table and the Orders table, only employees that have
matching orders and orders that have matching employees will be returned.
As a point of comparison, let's first look at another inner join. List the number of
employees and customers from each city that has both employees and customers in
it.
Code Sample
SubqueriesJoinsUnions/Demos/OuterJoins-Inner.sql

1. /*
2. Create a report that shows the number of
3. employees and customers from each city that has employees in it.
4. */
5.
6. SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,
7. COUNT(DISTINCT c.CustomerID) AS numCompanies,
8. e.City, c.City
9. FROM Employees e JOIN Customers c ON
10. (e.City = c.City)
11. GROUP BY e.City, c.City
12. ORDER BY numEmployees DESC;

Code Explanation
The above SELECT statement will return the following results:

Left Joins

A LEFT JOIN (also called a LEFT OUTER JOIN) returns all the records from
the first table even if there are no matches in the second table.

Page 96 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

Syntax
SELECT table1.column, table2.column
FROM table1
LEFT [OUTER] JOIN table2 ON (table1.column=table2.column)
WHERE conditions

All rows in table1 will be returned even if they do not have matches in table2.
Code Sample
SubqueriesJoinsUnions/Demos/OuterJoins-Left.sql

1. /*
2. Create a report that shows the number of
3. employees and customers from each city that has employees in it.
4. */
5.
6. SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,
7. COUNT(DISTINCT c.CustomerID) AS numCompanies,
8. e.City, c.City
9. FROM Employees e LEFT JOIN Customers c ON
10. (e.City = c.City)
11. GROUP BY e.City, c.City
12. ORDER BY numEmployees DESC;

Code Explanation
All records in the Employees table will be counted whether or not there are
matching cities in the Customers table. The results are shown below:

Right Joins

A RIGHT JOIN (also called a RIGHT OUTER JOIN) returns all the records from
the second table even if there are no matches in the first table.

Version: 1.4.8. Printed: 2017-02-16. Page 97 of 129


Subqueries, Joins and Unions

Syntax
SELECT table1.column, table2.column
FROM table1
RIGHT [OUTER] JOIN table2 ON (table1.column=table2.column)
WHERE conditions

All rows in table2 will be returned even if they do not have matches in table1.
Code Sample
SubqueriesJoinsUnions/Demos/OuterJoins-Right.sql

1. /*
2. Create a report that shows the number of
3. employees and customers from each city that has customers in it.
4. */
5.
6. SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,
7. COUNT(DISTINCT c.CustomerID) AS numCompanies,
8. e.City, c.City
9. FROM Employees e RIGHT JOIN Customers c ON
10. (e.City = c.City)
11. GROUP BY e.City, c.City
12. ORDER BY numEmployees DESC;

Page 98 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

Code Explanation
All records in the Customers table will be counted whether or not there are matching
cities in the Employees table. The results are shown below (not all records shown):

Full Outer Joins

A FULL JOIN (also called a FULL OUTER JOIN) returns all the records from
each table even if there are no matches in the joined table.
Full outer joins are not supported in MySQL 5.x and earlier.

Syntax
SELECT table1.column, table2.column
FROM table1
FULL [OUTER] JOIN table2 ON (table1.column=table2.column)
WHERE conditions

All rows in table1 and table2 will be returned.

Version: 1.4.8. Printed: 2017-02-16. Page 99 of 129


Subqueries, Joins and Unions

Code Sample
SubqueriesJoinsUnions/Demos/OuterJoins-Full.sql

1. /*
2. Create a report that shows the number of
3. employees and customers from each city.
4.
5. Note that MySQL 5.x does NOT support full outer joins.
6. */
7.
8. SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,
9. COUNT(DISTINCT c.CustomerID) AS numCompanies,
10. e.City, c.City
11. FROM Employees e FULL JOIN Customers c ON
12. (e.City = c.City)
13. GROUP BY e.City, c.City
14. ORDER BY numEmployees DESC;

Page 100 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

Code Explanation
All records in each table will be counted whether or not there are matching cities in
the other table. The results are shown below (not all records shown):

4.4 Unions
Unions are used to retrieve records from multiple tables or to get multiple record
sets from a single table.
In the last section, we noted that MySQL 5.x does not support full outer joins.
However, we can simulate a full outer join in MySQL with the help of the UNION
operator.

Version: 1.4.8. Printed: 2017-02-16. Page 101 of 129


Subqueries, Joins and Unions

Code Sample
SubqueriesJoinsUnions/Demos/MySQLSimulatedFullJoin.sql

1. SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,


2. COUNT(DISTINCT c.CustomerID) AS numCompanies,
3. e.City, c.City
4. FROM Employees e LEFT OUTER JOIN Customers c ON
5. (e.City = c.City)
6. GROUP BY e.City,c.City
7. UNION
8. SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,
9. COUNT(DISTINCT c.CustomerID) AS numCompanies,
10. e.City, c.City
11. FROM Employees e RIGHT OUTER JOIN Customers c ON
12. (e.City = c.City)
13. GROUP BY e.City, c.City
14. ORDER BY numEmployees DESC, numCompanies DESC;

Code Explanation
This query returns the same result in MySQL as the full outer join code sample does
in SQL Server and Oracle.
Code Sample
SubqueriesJoinsUnions/Demos/Unions.sql

1. /*
2. Get the phone numbers of all shippers, customers, and suppliers
3. */
4.
5. SELECT CompanyName, Phone
6. FROM Shippers
7. UNION
8. SELECT CompanyName, Phone
9. FROM Customers
10. UNION
11. SELECT CompanyName, Phone
12. FROM Suppliers
13. ORDER BY CompanyName;

Code Explanation
This query will return the company name and phone number of all shippers,
customers and suppliers.

Page 102 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

UNION ALL
By default, all duplicates are removed in UNIONs. To include duplicates, use UNION
ALL in place of UNION.

UNION Rules
• Each query must return the same number of columns.
• The columns must be in the same order.
• Column datatypes must be compatible.
• In Oracle, you can only ORDER BY columns that have the same name in every
SELECT clause in the UNION if the column is displaying a literal value.

Version: 1.4.8. Printed: 2017-02-16. Page 103 of 129


Subqueries, Joins and Unions

Exercise 15 Working with Unions


10 to 20 minutes

In this exercise, you will practice using UNION.


1. Create a report showing the contact name and phone numbers for all employees,
customers, and suppliers.

Page 104 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

Version: 1.4.8. Printed: 2017-02-16. Page 105 of 129


Subqueries, Joins and Unions

Exercise Solution
SubqueriesJoinsUnions/Solutions/Unions.sql

1. /******************************
2. SQL Server Solution
3. ******************************/
4. SELECT FirstName + ' ' + LastName AS Contact, HomePhone As Phone
5. FROM Employees
6. UNION
7. SELECT ContactName, Phone
8. FROM Customers
9. UNION
10. SELECT ContactName, Phone
11. FROM Suppliers
12. ORDER BY Contact;
13.
14. /******************************
15. Oracle Solution
16. ******************************/
17. SELECT FirstName || ' ' || LastName AS Contact, HomePhone As Phone
18. FROM Employees
19. UNION
20. SELECT ContactName AS Contact, Phone
21. FROM Customers
22. UNION
23. SELECT ContactName AS Contact, Phone
24. FROM Suppliers
25. ORDER BY Contact;
26.
27. /******************************
28. MySQL Solution
29. ******************************/
30. SELECT CONCAT(FirstName, ' ', LastName) AS Contact, HomePhone As Phone

31. FROM Employees


32. UNION
33. SELECT ContactName, Phone
34. FROM Customers
35. UNION
36. SELECT ContactName, Phone
37. FROM Suppliers
38. ORDER BY Contact;

Page 106 of 129 © Copyright 2017 Webucator. All rights reserved.


Subqueries, Joins and Unions

4.5 Conclusion
In this lesson, you have learned to create reports using data from multiple tables.

Version: 1.4.8. Printed: 2017-02-16. Page 107 of 129


Subqueries, Joins and Unions

Page 108 of 129 © Copyright 2017 Webucator. All rights reserved.


Conditional Processing with CASE

5. Conditional Processing with CASE


In this lesson, you will learn...
1. To use the CASE function to display different values depending on the values
of a column or columns.

5.1 Using CASE


CASE functions contain one or more WHEN clauses as shown below.

Syntax
-- OPTION 1: The Simple or Selected Case
SELECT CASE column
WHEN VALUE THEN RETURN_VALUE
WHEN VALUE THEN RETURN_VALUE
WHEN VALUE THEN RETURN_VALUE
WHEN VALUE THEN RETURN_VALUE
ELSE RETURN_VALUE
END
AS ColumnName
FROM table

-- OPTION 2: The Searched Case


SELECT CASE
WHEN EXPRESSION THEN RETURN_VALUE
WHEN EXPRESSION THEN RETURN_VALUE
WHEN EXPRESSION THEN RETURN_VALUE
WHEN EXPRESSION THEN RETURN_VALUE
ELSE RETURN_VALUE
END
AS ColumnName
FROM table

Version: 1.4.8. Printed: 2017-02-16. Page 109 of 129


Conditional Processing with CASE

Code Sample
Case/Demos/Case.sql

1. /*
2. Create a report showing the customer ID and company name,
3. employee id, firstname and lastname, and the order id
4. and a conditional column called "Shipped" that displays "On Time"
5. if the order was shipped on time and "Late" if the order was shipped
late.
6. */
7.
8. SELECT c.CustomerID, c.CompanyName, e.EmployeeID, e.FirstName, e.Last »»
Name, OrderID,
9. (CASE
10. WHEN ShippedDate < RequiredDate
11. THEN 'On Time'
12. ELSE 'Late'
13. END) AS Shipped
14. FROM Orders o
15. JOIN Employees e ON (e.EmployeeID = o.EmployeeID)
16. JOIN Customers c ON (c.CustomerID = o.CustomerID)
17. ORDER BY Shipped;

Page 110 of 129 © Copyright 2017 Webucator. All rights reserved.


Conditional Processing with CASE

Code Explanation
The above SELECT statement will return the following results (not all rows shown).

Version: 1.4.8. Printed: 2017-02-16. Page 111 of 129


Conditional Processing with CASE

Code Sample
Case/Demos/Case-GroupBy.sql

1. /*
2. Create a report showing the employee firstname and lastname,
3. a "NumOrders" column with a count of the orders taken, and a
4. conditional column called "Shipped" that displays "On Time" if
5. the order shipped on time and "Late" if the order shipped late.
6. Group records by employee firstname and lastname and then by the
7. "Shipped" status. Order by employee lastname, then by firstname,
8. and then descending by number of orders.
9. */
10.
11. SELECT e.FirstName, e.LastName, COUNT(o.OrderID) As NumOrders,
12. (CASE
13. WHEN o.ShippedDate < o.RequiredDate
14. THEN 'On Time'
15. ELSE 'Late'
16. END)
17. AS Shipped
18. FROM Orders o
19. JOIN Employees e ON (e.EmployeeID = o.EmployeeID)
20. GROUP BY e.FirstName, e.LastName,
21. (CASE
22. WHEN o.ShippedDate < o.RequiredDate
23. THEN 'On Time'
24. ELSE 'Late'
25. END)
26. ORDER BY e.LastName, e.FirstName, NumOrders DESC;

Page 112 of 129 © Copyright 2017 Webucator. All rights reserved.


Conditional Processing with CASE

Code Explanation
The above SELECT statement will return the following results.

Notice how the GROUP BY clause contains the same CASE statement that is in the
SELECT clause. This is required because all non-aggregate columns in the SELECT
clause must also be in the GROUP BY clause and the GROUP BY clause cannot
contain aliases defined in the SELECT clause.

Version: 1.4.8. Printed: 2017-02-16. Page 113 of 129


Conditional Processing with CASE

Exercise 16 Working with CASE


10 to 15 minutes

In this exercise you will practice using CASE.


1. Create a report that shows the company names and faxes for all customers. If
the customer doesn't have a fax, the report should show "No Fax" in that field
as shown below.

Page 114 of 129 © Copyright 2017 Webucator. All rights reserved.


Conditional Processing with CASE

Version: 1.4.8. Printed: 2017-02-16. Page 115 of 129


Conditional Processing with CASE

Exercise Solution
Case/Solutions/Case.sql

1. SELECT CompanyName,
2. (CASE
3. WHEN Fax IS NULL
4. THEN 'No Fax'
5. ELSE Fax
6. END)
7. AS Fax
8. FROM Customers;

Page 116 of 129 © Copyright 2017 Webucator. All rights reserved.


Conditional Processing with CASE

5.2 Conclusion
In this lesson, you learned about using CASE to output different values in reports
based on data contained in table fields.

Version: 1.4.8. Printed: 2017-02-16. Page 117 of 129


Conditional Processing with CASE

Page 118 of 129 © Copyright 2017 Webucator. All rights reserved.


Inserting, Updating and Deleting Records

A1. Inserting, Updating and Deleting Records


In this lesson, you will learn...
1. To insert records into a table.
2. To update records in a table.
3. To delete records from a table.
Inserting new records into a table is not difficult. Dangerously, it is even easier to
update and delete records.

A1.1 INSERT
To insert a record into a table, you must specify values for all fields that do not have
default values and cannot be NULL.

Syntax
INSERT INTO table
(columns)
VALUES (values);

The second line of the above statement can be excluded if all required columns are
inserted and the values are listed in the same order as the columns in the table. We
recommend you include the second line all the time though as the code will be easier
to read and update and less likely to break as the database is modified.

Version: 1.4.8. Printed: 2017-02-16. Page 119 of 129


Inserting, Updating and Deleting Records

Code Sample
InsertsUpdatesDeletes/Demos/Insert.sql

1. -- Insert a New Employee


2.
3. /******************************
4. Both of the inserts below will work in SQL Server
5.
6. Oracle
7. ******************************/
8. INSERT INTO Employees
9. (LastName, FirstName, Title, TitleOfCourtesy,
10. BirthDate, HireDate, Address, City, Region,
11. PostalCode, Country, HomePhone, Extension)
12. VALUES ('Dunn','Nat','Sales Representative','Mr.','19-Feb-1970',
13. '15-Jan-2004','4933 Jamesville Rd.','Jamesville','NY',
14. '13078','USA','315-555-5555','130');
15.
16. /******************************
17. MySQL
18. ******************************/
19. INSERT INTO Employees
20. (LastName, FirstName, Title, TitleOfCourtesy,
21. BirthDate, HireDate, Address, City, Region,
22. PostalCode, Country, HomePhone, Extension)
23. VALUES ('Dunn','Nat','Sales Representative','Mr.','1970-02-19',
24. '2004-01-15','4933 Jamesville Rd.','Jamesville','NY',
25. '13078','USA','315-555-5555','130');

Code Explanation
If the INSERT is successful, the output will read something to this effect:

(1 row(s) affected)

Page 120 of 129 © Copyright 2017 Webucator. All rights reserved.


Inserting, Updating and Deleting Records

Exercise 17 Inserting Records


5 to 15 minutes

In this exercise, you will practice inserting records.


1. Insert yourself into the Employees table.
• Include the following fields: LastName, FirstName, Title,
TitleOfCourtesy, BirthDate, HireDate, City, Region,
PostalCode, Country, HomePhone, ReportsTo
2. Insert an order for yourself in the Orders table.
• Include the following fields: CustomerID, EmployeeID, OrderDate,
RequiredDate
3. Insert order details in the Order_Details table.
• Include the following fields: OrderID, ProductID, UnitPrice,
Quantity, Discount

Version: 1.4.8. Printed: 2017-02-16. Page 121 of 129


Inserting, Updating and Deleting Records

Exercise Solution
InsertsUpdatesDeletes/Solutions/Inserts.sql

1. /******************************
2. Oracle Solution
3. ******************************/
4. INSERT INTO Employees
5. (EmployeeID, LastName, FirstName, Title, TitleOfCourtesy,
6. BirthDate, HireDate, City, Region,
7. PostalCode, Country, HomePhone, ReportsTo)
8. VALUES(10, 'Dunn','Nat','Trainer','Mr.',
9. '01-Feb-1970','04-Mar-1997','Jamesville','NY',
10. '13078','USA','315-555-5555','1');
11.
12. /******************************
13.
14. SQL Server & MySQL Solution
15. ******************************/
16. INSERT INTO Employees
17. (LastName, FirstName, Title, TitleOfCourtesy,
18. BirthDate, HireDate, City, Region,
19. PostalCode, Country, HomePhone, ReportsTo)
20. VALUES('Dunn','Nat','Trainer','Mr.',
21. '1970-02-01','1997-03-04','Jamesville','NY',
22. '13078','USA','315-555-5555','1');
23.
24. /******************************
25.
26. Oracle Solution
27. ******************************/
28. INSERT INTO Orders
29. (OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate)
30. VALUES(11078, 'COMMI',10,'24-May-2004','12-Jul-2005');
31.
32. /******************************
33. SQL Server & MySQL Solution
34. ******************************/
35. INSERT INTO Orders
36. (CustomerID, EmployeeID, OrderDate, RequiredDate)
37. VALUES('COMMI',10,'2005-05-24','2005-07-12');
38.
39. INSERT INTO Order_Details

Page 122 of 129 © Copyright 2017 Webucator. All rights reserved.


Inserting, Updating and Deleting Records

40. (OrderID, ProductID, UnitPrice, Quantity, Discount)


41. VALUES(11078, 3, 10, 100, .1);
42.
43. /*
44. SQL Server users will replace Order_Details with "Order Details"
45.
46. */

Version: 1.4.8. Printed: 2017-02-16. Page 123 of 129


Inserting, Updating and Deleting Records

A1.2 UPDATE
The UPDATE statement allows you to update one or more fields for any number of
records in a table. You must be very careful not to update more records than you
intend to!

Syntax
UPDATE table
SET field = value,
field = value,
field = value
WHERE conditions;

Code Sample
InsertsUpdatesDeletes/Demos/Update.sql

1. -- Update an Employee
2.
3. UPDATE Employees
4. SET FirstName = 'Nathaniel'
5. WHERE FirstName = 'Nat';

Code Explanation
If the UPDATE is successful, the output will read something to this effect:

(1 row(s) affected)

A1.3 DELETE
The DELETE statement allows you to delete one or more records in a table. Like
with UPDATE, you must be very careful not to delete more records than you intend
to!

Syntax
DELETE FROM Employees
WHERE conditions;

Page 124 of 129 © Copyright 2017 Webucator. All rights reserved.


Inserting, Updating and Deleting Records

Code Sample
InsertsUpdatesDeletes/Demos/Delete.sql

1. -- Delete an Employee
2.
3. DELETE FROM Employees
4. WHERE FirstName = 'Nathaniel';

Code Explanation
If the DELETE is successful, the output will read something to this effect:

(1 row(s) affected)

Version: 1.4.8. Printed: 2017-02-16. Page 125 of 129


Inserting, Updating and Deleting Records

Exercise 18 Updating and Deleting Records


5 to 15 minutes

In this exercise, you will practice updating and deleting records.


1. Update your record in the Employees table to include some Notes.
2. Raise the unit price of all products in the Products table by 10% for all
products that are out of stock. This should affect 5 rows.
3. Try to delete yourself from the Employees table. Could you?
4. If you were not allowed to delete yourself from the Employees table, figure
out what other records you have to delete so that you can.

Page 126 of 129 © Copyright 2017 Webucator. All rights reserved.


Inserting, Updating and Deleting Records

Version: 1.4.8. Printed: 2017-02-16. Page 127 of 129


Inserting, Updating and Deleting Records

Exercise Solution
InsertsUpdatesDeletes/Solutions/UpdateDelete.sql

1. UPDATE Employees
2. SET Notes = 'Nat does not really work here.'
3. WHERE FirstName = 'Nathaniel' AND LastName = 'Dunn';
4.
5. UPDATE Products
6. SET UnitPrice = UnitPrice * 1.1
7. WHERE UnitsInStock = 0;
8.
9. DELETE FROM "Order Details"
10. WHERE OrderID = 11078;
11. -- Note that your OrderID might be different
12.
13. DELETE FROM Orders
14. WHERE OrderID = 11078;
15. -- Note that your OrderID might be different
16.
17. DELETE FROM Employees
18. WHERE FirstName = 'Nathaniel' AND LastName = 'Dunn';

Page 128 of 129 © Copyright 2017 Webucator. All rights reserved.


Inserting, Updating and Deleting Records

A1.4 Conclusion
In this lesson, you have learned how to insert, update, and delete records. Remember
to be careful with updates and deletes. If you forget or mistype the WHERE clause,
you could lose a lot of data.

Version: 1.4.8. Printed: 2017-02-16. Page 129 of 129

You might also like