SQL101_148
SQL101_148
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.
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
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
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
Tables
A table in a database is a collection of rows and columns. Tables are also known as
entities or relations.
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.
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.
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.
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.
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.
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.
Comments
The standard SQL comment is two hyphens (--). However, some databases use
other forms of comments as shown in the table below.
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. */
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.
Syntax
SELECT table.*
FROM table;
-- OR
SELECT *
FROM table;
Code Sample
SimpleSelects/Demos/SelectAll.sql
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.
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)
Exercise Solution
SimpleSelects/Solutions/SelectAll.sql
Syntax
SELECT table_name.column_name, table_name.column_name
FROM table;
-- OR
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:
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.
Exercise Solution
SimpleSelects/Solutions/SelectCols.sql
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;
Code Explanation
The above SELECT statement will return the following results:
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;
Code Explanation
The above SELECT statement will return the following results:
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;
Code Explanation
The above SELECT statement will return the following results:
Exercise Solution
SimpleSelects/Solutions/Sorting.sql
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.
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';
Code Explanation
The above SELECT statement will return the following results:
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:
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.
Exercise Solution
SimpleSelects/Solutions/EqualityAndInequality.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:
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.
Exercise Solution
SimpleSelects/Solutions/GreaterThanLessThan.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;
Code Explanation
The above SELECT statement will return the following results:
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.
Exercise Solution
SimpleSelects/Solutions/Null.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:
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.
Exercise Solution
SimpleSelects/Solutions/Where-OrderBy.sql
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.
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';
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.
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.
Exercise Solution
SimpleSelects/Solutions/MultipleConditions.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';
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.';
Code Explanation
The above SELECT statements will both return the following results:
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%';
Code Explanation
The above SELECT statement will return the following results:
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
Code Explanation
The above SELECT statement will return the following results:
Using wildcards can slow down performance, especially if they are used at the
beginning of a pattern. You should use them sparingly.
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:
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".
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%';
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.
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.
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.
Code Sample
AdvancedSelects/Demos/Concatenate-SqlServer.sql
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
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
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).
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;
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
Code Explanation
As you can see, the third column now has the title "FreightTotal".
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.
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;
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
Code Explanation
Returns 9.
Code Sample
AdvancedSelects/Demos/Aggregate-Sum.sql
Code Explanation
Returns 328.
Code Sample
AdvancedSelects/Demos/Aggregate-Avg.sql
Code Explanation
Returns 28.8663.
Code Sample
AdvancedSelects/Demos/Aggregate-MinMax.sql
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
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
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;
Order of Clauses
1. SELECT
2. FROM
3. WHERE
4. GROUP BY
5. HAVING
6. ORDER BY
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;
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.
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.
Exercise Solution
AdvancedSelects/Solutions/Grouping.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
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;
Code Explanation
The above SELECT statement will return the following results (not all rows shown):
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;
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).
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;
Code Explanation
The above SELECT statement will return the following results:
Code Sample
AdvancedSelects/Demos/Functions-String2.sql
Code Explanation
The above SELECT statement will return the following results (not all rows shown):
Code Sample
AdvancedSelects/Demos/Functions-Date1.sql
Code Explanation
The above SELECT statement will return the following results in SQL Server:
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.
Code Sample
AdvancedSelects/Demos/Functions-Date2.sql
Code Explanation
The above SELECT statement will return the following results:
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.
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');
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,
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.
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
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
Code Explanation
The above SELECT statement will return the following results:
Exercise 13 Subqueries
20 to 30 minutes
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.
Exercise Solution
SubqueriesJoinsUnions/Solutions/Subqueries.sql
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'));
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
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
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.
Code Sample
SubqueriesJoinsUnions/Demos/Joins-Aliases.sql
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.
The above code would break because it attempts to join table3 with table2
before table2 has been joined with table1.
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;
Code Explanation
The above SELECT statement will return the following results:
2. Create a report that shows the total quantity of products (from the
Order_Details table) ordered. Only show records for products for which
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.
Exercise Solution
SubqueriesJoinsUnions/Solutions/Joins.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.
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.
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;
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):
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
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;
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.
Code Sample
SubqueriesJoinsUnions/Demos/MySQLSimulatedFullJoin.sql
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.
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.
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
4.5 Conclusion
In this lesson, you have learned to create reports using data from multiple tables.
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
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;
Code Explanation
The above SELECT statement will return the following results (not all rows shown).
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;
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.
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;
5.2 Conclusion
In this lesson, you learned about using CASE to output different values in reports
based on data contained in table fields.
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.
Code Sample
InsertsUpdatesDeletes/Demos/Insert.sql
Code Explanation
If the INSERT is successful, the output will read something to this effect:
(1 row(s) affected)
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
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;
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)
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';
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.