SQL Practice Problems: Mysql Version
SQL Practice Problems: Mysql Version
MySQL version
All rights reserved. This book or any portion thereof may not be reproduced
or used in any manner whatsoever without the express written permission
of the publisher except for the use of brief quotations in a book review.
Ordering Information:
Special discounts are available on quantity purchases by corporations, associations, and others.
For details, contact the publisher at info@SQLPracticeProblems.com.
Table of Contents
How to use this book ................................................................................................................... 7
Setup ............................................................................................................................................ 9
Introductory Problems ............................................................................................................... 10
1. Which shippers do we have? .......................................................................................... 10
2. Certain fields from Categories ........................................................................................ 10
3. Sales Representatives ...................................................................................................... 11
4. Sales Representatives in the United States ..................................................................... 11
5. Orders placed by specific EmployeeID .......................................................................... 11
6. Suppliers and ContactTitles ............................................................................................ 12
7. Products with “queso” in ProductName ......................................................................... 13
8. Orders shipping to France or Belgium ............................................................................ 14
9. Orders shipping to any country in Latin America .......................................................... 14
10. Employees, in order of age.......................................................................................... 16
11. Showing only the Date with a DateTime field ............................................................ 16
12. Employees full name ................................................................................................... 17
13. OrderDetails amount per line item .............................................................................. 17
14. How many customers? ................................................................................................ 18
15. When was the first order? ........................................................................................... 18
16. Countries where there are customers .......................................................................... 19
17. Contact titles for customers ......................................................................................... 20
18. Products with associated supplier names .................................................................... 20
19. Orders and the Shipper that was used ......................................................................... 22
Intermediate Problems ............................................................................................................... 25
20. Categories, and the total products in each category .................................................... 25
21. Total customers per country/city................................................................................. 25
22. Products that need reordering...................................................................................... 26
23. Products that need reordering, continued .................................................................... 27
24. Customer list by region ............................................................................................... 27
25. High freight charges .................................................................................................... 29
26. High freight charges—2015 ........................................................................................ 29
27. High freight charges with between ............................................................................. 29
28. High freight charges—last year .................................................................................. 30
29. Employee/Order Detail report ..................................................................................... 31
30. Customers with no orders ........................................................................................... 31
31. Customers with no orders for EmployeeID 4 ............................................................. 32
Advanced Problems ................................................................................................................... 34
32. High-value customers.................................................................................................. 34
33. High-value customers—total orders ........................................................................... 34
34. High-value customers—with discount ........................................................................ 35
35. Month-end orders ........................................................................................................ 36
36. Orders with many line items ....................................................................................... 37
37. Orders—random assortment ....................................................................................... 37
38. Orders—accidental double-entry ................................................................................ 38
39. Orders—accidental double-entry details ..................................................................... 39
40. Orders—accidental double-entry details, derived table .............................................. 39
41. Late orders................................................................................................................... 40
42. Late orders—which employees? ................................................................................. 41
43. Late orders vs. total orders .......................................................................................... 41
44. Late orders vs. total orders—missing employee ......................................................... 42
45. Late orders vs. total orders—fix null .......................................................................... 42
46. Late orders vs. total orders—percentage ..................................................................... 43
47. Late orders vs. total orders—fix decimal .................................................................... 43
48. Customer grouping ...................................................................................................... 44
49. Customer grouping—fix null ...................................................................................... 45
50. Customer grouping with percentage ........................................................................... 45
51. Customer grouping—flexible...................................................................................... 46
52. Countries with suppliers or customers ........................................................................ 47
53. Countries with suppliers or customers, version 2 ....................................................... 48
54. Countries with suppliers or customers, version 3 ....................................................... 48
55. First order in each country .......................................................................................... 49
56. Customers with multiple orders in 5 day period ......................................................... 50
57. Customers with multiple orders in 5 day period, version 2 ........................................ 51
ANSWERS ................................................................................................................................ 54
Introductory Problems ............................................................................................................... 54
1. Which shippers do we have? .......................................................................................... 54
2. Certain fields from Categories ........................................................................................ 55
3. Sales Representatives ...................................................................................................... 55
4. Sales Representatives in the United States ..................................................................... 56
5. Orders placed by specific EmployeeID .......................................................................... 56
6. Suppliers and ContactTitles ............................................................................................ 57
7. Products with “queso” in ProductName ......................................................................... 58
8. Orders shipping to France or Belgium ............................................................................ 58
9. Orders shipping to any country in Latin America .......................................................... 59
10. Employees, in order of age.......................................................................................... 60
11. Showing only the Date with a DateTime field ............................................................ 60
12. Employees full name ................................................................................................... 61
13. OrderDetails amount per line item .............................................................................. 62
14. How many customers? ................................................................................................ 62
15. When was the first order? ........................................................................................... 63
16. Countries where there are customers .......................................................................... 63
17. Contact titles for customers ......................................................................................... 64
18. Products with associated supplier names .................................................................... 64
19. Orders and the Shipper that was used ......................................................................... 65
Intermediate Problems ............................................................................................................... 67
20. Categories, and the total products in each category .................................................... 67
21. Total customers per country/city................................................................................. 67
22. Products that need reordering...................................................................................... 68
23. Products that need reordering, continued .................................................................... 69
24. Customer list by region ............................................................................................... 70
25. High freight charges .................................................................................................... 71
26. High freight charges—2015 ........................................................................................ 71
27. High freight charges with between ............................................................................. 72
28. High freight charges—last year .................................................................................. 73
29. Employee/Order Detail report ..................................................................................... 73
30. Customers with no orders ........................................................................................... 74
31. Customers with no orders for EmployeeID 4 ............................................................. 75
Advanced Problems ................................................................................................................... 76
32. High-value customers.................................................................................................. 76
33. High-value customers—total orders ........................................................................... 77
34. High-value customers—with discount ........................................................................ 78
35. Month-end orders ........................................................................................................ 79
36. Orders with many line items ....................................................................................... 79
37. Orders—random assortment ....................................................................................... 80
38. Orders—accidental double-entry ................................................................................ 80
39. Orders—accidental double-entry details ..................................................................... 81
40. Orders—accidental double-entry details, derived table .............................................. 81
41. Late orders................................................................................................................... 82
42. Late orders—which employees? ................................................................................. 83
43. Late orders vs. total orders .......................................................................................... 83
44. Late orders vs. total orders—missing employee ......................................................... 84
45. Late orders vs. total orders—fix null .......................................................................... 85
46. Late orders vs. total orders—percentage ..................................................................... 86
47. Late orders vs. total orders—fix decimal .................................................................... 87
48. Customer grouping ...................................................................................................... 89
49. Customer grouping—fix null ...................................................................................... 90
50. Customer grouping with percentage ........................................................................... 91
51. Customer grouping—flexible...................................................................................... 92
52. Countries with suppliers or customers ........................................................................ 94
53. Countries with suppliers or customers, version 2 ....................................................... 94
54. Countries with suppliers or customers, version 3 ....................................................... 95
55. First order in each country .......................................................................................... 96
56. Customers with multiple orders in 5 day period ......................................................... 97
57. Customers with multiple orders in 5 day period, version 2 ........................................ 98
How to use this book
This book assumes that you have some basic background knowledge about relational
databases. However, I’ve added some beginner level questions to gradually introduce the
various parts of the SQL Select statement for those with less experience in SQL.
A note on the database used: it is not the standard Northwind database that was the sample
included with several Microsoft database products. There have been many changes made to it,
including additional tables, and modified data, to support the problems in this book. Do not try
to use the standard Northwind sample database, many of the problems will not work.
Do you need to finish all the problems? Absolutely not. The introductory problems are fairly
simple, so you may want to skip directly to the Intermediate Problems section. If you’re not a
beginner, but not sure where you should start, look at the problems and expected results in the
Introductory Problems section, and make sure you completely understand the concepts and
answers, then you could try skipping to the Intermediate problems.
If you’re uncertain about how to start on a problem, the hints are designed to gradually walk
you through how to approach the problem. Try hard to solve the problems first without the
hints! It’s best to start out using the “no hint” version of this document. Then, only open the
main document (with hints) if you really need it. But if you’re stuck, the hints will get you
started.
If possible, don’t look at the answers (in the back of the book), until you’ve solved the problem
to the best of your ability on your own. You will learn and remember much more.
Should you search online for answers, examples, etc.? Absolutely. I expect you to do research
online as you work through the problems. I do not include all the syntax in this book. In my
day-to-day work as a data engineer, I would be lost without being able to do online research.
Sometimes I search online for a reminder of a certain syntax, sometimes for examples of a
particular type of code, and sometimes for approaches to specific problems. Learning to find
answers online effectively can cut your problem-solving time dramatically.
Once you finish all the questions, you’ll have some extremely useful skills in data analysis and
data mining. The ability to use SQL is the foundation of data engineering, and (thankfully)
does not change very frequently at all. This is useful because the SQL that you learned 10
years ago will probably be just as useful 10 years in the future! And it’s a relatively rare skill.
7
I’ve interviewed many people who rated themselves a “9 or 10” on a 1-10 scale of SQL
knowledge, who could not even do a simple Group by in a SQL statement.
Select statements aren’t all there is to SQL, of course. There’s also the syntax that lets you
modify data (update, insert, delete), and create and modify database objects), as well as
programming concepts such as stored procedures, and of course many other topics.
In this book, I’m only presenting problems involving retrieving data with Select statements,
because that’s by far the most common need, and it’s also an area where it’s very difficult for
people to get solid practice with real life data problems, unless they’re already working as a
data engineer or programmer. And it’s a critical first step for almost any other database topics.
Thank you for purchasing this book! Any feedback would be greatly appreciated. For any
questions or issues, please send email to feedback@SQLPracticeProblems.com and I will be
happy to respond.
8
Setup
This section will help you with the install of MySQL 8.0, and will walk you through the setup
of the practice database.
MySQL 8.0 is a big leap in functionality from previous versions. It includes many very useful
features that other DBMS systems (such as Microsoft SQL Server) have had for a long time,
such as Window functions and CTEs (Common Table Expressions). The problems in this book
are dependent on having MySQL 8.0 instead of previous versions.
Installing MySQL 8.0
To download and install MySQL 8.0, visit this website:
https://dev.mysql.com/downloads/
It’s a straightforward setup. Make sure you install version 8.0 (MySQL 8.0 Generally
Available (GA) Release ) and not an earlier version. You can choose the operating system you
wish to use, such as Microsoft Windows, macOS, Linux, etc.
Make sure you also install MySQL Workbench or a similar tool, in order to actually run SQL
against the database. MySQL Workbench is included in the default installation, and that’s the
tool I use to walk through the setup of the practice database.
If you have any issues, the install documentation is online here:
https://dev.mysql.com/doc/refman/8.0/en/installing.html
Setting up the practice database
This video will walk you through the setup of the practice database used for the problems.
https://youtu.be/490vum3jyyU
It assumes that you have installed MySQL version 8.0.
9
Introductory Problems
Expected Results
…will return 4 columns. We only want to see two columns, CategoryName and Description.
Expected Results
CategoryName Description
Beverages Soft drinks, coffees, teas, beers, and ales
Condiments Sweet and savory sauces, relishes, spreads, and seasonings
Confections Desserts, candies, and sweet breads
Dairy Products Cheeses
Grains/Cereals Breads, crackers, pasta, and cereal
Meat/Poultry Prepared meats
Produce Dried fruit and bean curd
Seafood Seaweed and fish
10
3. Sales Representatives
We’d like to see just the FirstName, LastName, and HireDate of all the employees with the
Title of Sales Representative. Write a SQL statement that returns only those employees.
Expected Results
Expected Results
11
Expected Results
OrderID OrderDate
10248 2014-07-04 08:00:00.000
10254 2014-07-11 02:00:00.000
10269 2014-07-31 00:00:00.000
10297 2014-09-04 21:00:00.000
10320 2014-10-03 12:00:00.000
10333 2014-10-18 18:00:00.000
10358 2014-11-20 05:00:00.000
10359 2014-11-21 14:00:00.000
10372 2014-12-04 10:00:00.000
10378 2014-12-10 00:00:00.000
10397 2014-12-27 17:00:00.000
10463 2015-03-04 13:00:00.000
10474 2015-03-13 16:00:00.000
10477 2015-03-17 02:00:00.000
10529 2015-05-07 01:00:00.000
10549 2015-05-27 03:00:00.000
10569 2015-06-16 15:00:00.000
10575 2015-06-20 22:00:00.000
10607 2015-07-22 09:00:00.000
(some result rows were not included, the total should be 42)
Expected Results
12
6 Mayumi Ohno Marketing Representative
8 Peter Wilson Sales Representative
9 Lars Peterson Sales Agent
11 Petra Winkler Sales Manager
12 Martin Bein International Marketing Mgr.
13 Sven Petersen Coordinator Foreign Markets
14 Elio Rossi Sales Representative
16 Cheryl Saylor Regional Account Rep.
17 Michael Björn Sales Representative
18 Guylène Nodier Sales Manager
19 Robb Merchant Wholesale Account Agent
20 Chandra Leka Owner
21 Niels Petersen Sales Manager
22 Dirk Luchte Accounting Manager
23 Anne Heikkonen Product Manager
24 Wendy Mackenzie Sales Representative
26 Giovanni Giudici Order Administrator
27 Marie Delamare Sales Manager
28 Eliane Noz Sales Representative
29 Chantal Goulet Accounting Manager
Expected Results
ProductID ProductName
11 Queso Cabrales
12 Queso Manchego La Pastora
13
8. Orders shipping to France or Belgium
Looking at the Orders table, there’s a field called ShipCountry. Write a query that shows the
OrderID, CustomerID, and ShipCountry for the orders where the ShipCountry is either France
or Belgium.
Expected Results
14
Argentina
Venezuela
It doesn’t make sense to use multiple Or statements anymore. Use the In statement.
Note:
By default, MySQL only returns 100 rows in the result window. In order to show all of the
rows, click the drop-down at the top of your query tab that says “Limit to 100 rows”. Choose a
higher number, or choose “Don’t Limit”.
Expected Results
15
10. Employees, in order of age
For all the employees in the Employees table, show the FirstName, LastName, Title, and
BirthDate. Order the results by BirthDate, so we have the oldest employees first.
Expected Results
Expected Results
16
12. Employees full name
Show the FirstName and LastName columns from the Employees table, and then create a new
column called FullName, showing FirstName and LastName joined together in one column,
with a space in-between.
Expected Results
Expected Results
17
10251 22 16.80 6 100.80
10251 57 15.60 15 234.00
10251 65 16.80 20 336.00
10252 20 64.80 40 2592.00
10252 33 2.00 25 50.00
10252 60 27.20 40 1088.00
10253 31 10.00 20 200.00
10253 39 14.40 42 604.80
10253 49 16.00 40 640.00
10254 24 3.60 15 54.00
10254 55 19.20 21 403.20
10254 74 8.00 21 168.00
10255 2 15.20 20 304.00
10255 16 13.90 35 486.50
Expected Results
TotalCustomers
91
18
Expected Results
FirstOrder
2014-07-04 08:00:00.000
Expected Results
Country
Argentina
Austria
Belgium
Brazil
Canada
Denmark
Finland
France
Germany
Ireland
Italy
Mexico
Norway
Poland
Portugal
Spain
Sweden
Switzerland
UK
USA
Venezuela
19
17. Contact titles for customers
Show a list of all the different values in the Customers table for ContactTitles. Also include a
count for each ContactTitle.
This is similar in concept to the previous question “Countries where there are customers”,
except we now want a count for each ContactTitle.
Expected Results
ContactTitle TotalContactTitle
Owner 17
Sales Representative 17
Marketing Manager 12
Sales Manager 11
Accounting Manager 10
Sales Associate 7
Marketing Assistant 6
Sales Agent 5
Assistant Sales Agent 2
Order Administrator 2
Assistant Sales Representative 1
Owner/Marketing Assistant 1
20
Expected Results
21
19 Teatime Chocolate Biscuits Specialty Biscuits, Ltd.
20 Sir Rodney's Marmalade Specialty Biscuits, Ltd.
21 Sir Rodney's Scones Specialty Biscuits, Ltd.
Expected Results
22
10268 2014-07-30 Federal Shipping
10269 2014-07-31 Speedy Express
23
Congratulations! You've completed the introductory problems.
Any questions or feedback on the problems, hints, or answers? I'd like to hear from you. Please
email me at feedback@SQLPracticeProblems.com.
24
Intermediate Problems
Expected Results
CategoryName TotalProducts
Confections 13
Beverages 12
Condiments 12
Seafood 12
Dairy Products 10
Grains/Cereals 7
Meat/Poultry 6
Produce 5
Expected Results
25
Argentina Buenos Aires 3
France Paris 2
USA Portland 2
France Nantes 2
Portugal Lisboa 2
Finland Oulu 1
Italy Reggio Emilia 1
France Reims 1
Brazil Resende 1
Austria Salzburg 1
Venezuela San Cristóbal 1
USA San Francisco 1
USA Seattle 1
Expected Results
26
43 Ipoh Coffee 17 25
45 Rogede sild 5 15
48 Chocolade 15 25
49 Maxilaku 10 15
53 Perth Pasties 0 0
56 Gnocchi di nonna Alice 21 30
64 Wimmers gute Semmelknödel 22 30
66 Louisiana Hot Spiced Okra 4 20
68 Scottish Longbreads 6 15
70 Outback Lager 15 30
74 Longlife Tofu 4 5
Expected Results
27
However, he wants the customers with no region (null in the Region field) to be at the end,
instead of at the top, where you’d normally find the null values. Within the same region,
companies should be sorted by CustomerID.
Expected Results
28
25. High freight charges
Some of the countries we ship to have very high freight charges. We'd like to investigate some
more shipping options for our customers, to be able to offer them lower freight charges. Return
the three ship countries with the highest average freight overall, in descending order by
average freight.
Expected Results
ShipCountry AverageFreight
Austria 184.7875
Ireland 145.0126
USA 112.8794
Expected result
ShipCountry AverageFreight
Austria 178.3642
Switzerland 117.1775
France 113.991
29
Select
ShipCountry
,avg(freight) as AverageFreight
From Orders
Where
OrderDate between '2015-01-01' and '2015-12-31'
Group By ShipCountry
Order By AverageFreight desc
Limit 3;
Notice when you run this, it gives Sweden as the ShipCountry with the third highest freight
charges. However, this is wrong—it should be France.
Find the OrderID that is causing the SQL statement above to be incorrect.
Expected Result
(no expected results this time—we’re looking for one specific OrderID)
Expected Results
ShipCountry AverageFreight
Ireland 200.21
Austria 186.4596
USA 119.3032
30
29. Employee/Order Detail report
We're doing inventory, and need to show Employee and Order Detail information like the
below, for all orders. Sort by OrderID and Product ID.
Expected Results
31
Expected Results
Customers_CustomerID Orders_CustomerID
FISSA NULL
PARIS NULL
Expected Result
CustomerID CustomerID
SEVES NULL
THEBI NULL
LAZYK NULL
GROSR NULL
PARIS NULL
FISSA NULL
SPECD NULL
LAUGB NULL
PRINI NULL
VINET NULL
FRANR NULL
CONSH NULL
NORTS NULL
PERIC NULL
DUMON NULL
SANTG NULL
32
Congratulations! You've completed the intermediate problems.
Any questions or feedback on the problems, hints, or answers? I'd like to hear from you. Please
email me at feedback@SQLPracticeProblems.com.
33
Advanced Problems
Expected Result
34
Expected Result
Expected Result
35
35. Month-end orders
At the end of the month, salespeople are likely to try much harder to get orders, to meet their
month-end quotas. Show all orders made on the last day of the month. Order by EmployeeID
and OrderID
Expected Result
36
36. Orders with many line items
The Northwind mobile app developers are testing an app that customers will use to show
orders. In order to make sure that even the largest orders will show up correctly on the app,
they'd like some samples of orders that have lots of individual line items.
Show the 10 orders with the most line items, in order of total line items.
Expected Result
OrderID TotalOrderDetails
11077 25
10847 6
10657 6
10979 6
10294 5
10382 5
10406 5
10558 5
10670 5
10607 5
37
Expected Result
Expected Result
OrderID
10263
10263
10658
10990
11030
38
39. Orders—accidental double-entry details
Based on the previous question, we now want to show details of the order, for orders that
match the above criteria.
Expected Result
39
Join (
Select
OrderID
From OrderDetails
Where Quantity >= 60
Group By OrderID, Quantity
Having Count(*) > 1
) PotentialProblemOrders
on PotentialProblemOrders.OrderID = OrderDetails.OrderID
Order by OrderID, ProductID;
Expected Result
40
42. Late orders—which employees?
Some salespeople have more orders arriving late than others. Maybe they're not following up
on the order process, and need more training. Which salespeople have the most orders arriving
late?
Expected Result
Expected Result
41
44. Late orders vs. total orders—missing employee
There's an employee missing in the answer from the problem above. Fix the SQL to show all
employees who have taken orders.
Expected Result
Expected Result
42
46. Late orders vs. total orders—percentage
Now we want to get the percentage of late orders over total orders.
Expected Result
Employee ID Last Name All Orders Late Orders Percent Late Orders
1 Davolio 123 3 0.0244
2 Fuller 96 4 0.0417
3 Leverling 127 5 0.0394
4 Peacock 156 10 0.0641
5 Buchanan 42 0 0.0000
6 Suyama 67 3 0.0448
7 King 72 4 0.0556
8 Callahan 104 5 0.0481
9 Dodsworth 43 5 0.1163
Expected Result
Employee ID Last Name All Orders Late Orders Percent Late Orders
1 Davolio 123 3 0.02
2 Fuller 96 4 0.04
3 Leverling 127 5 0.04
4 Peacock 156 10 0.06
5 Buchanan 42 0 0.00
6 Suyama 67 3 0.04
7 King 72 4 0.06
8 Callahan 104 5 0.05
9 Dodsworth 43 5 0.12
43
48. Customer grouping
Andrew Fuller, the VP of sales at Northwind, would like to do a sales campaign for existing
customers. He'd like to categorize customers into groups, based on how much they ordered in
2016. Then, depending on which group the customer is in, he will target the customer with
different sales materials.
The customer grouping categories are 0 to 1,000, 1,000 to 5,000, 5,000 to 10,000, and over
10,000. So, if the total dollar amount of the customer’s purchases in that year were between 0
to 1,000, they would be in the “Low” group. A customer with purchase from 1,000 to 5,000
would be in the “Medium” group, and so on.
A good starting point for this query is the answer from the problem “High-value customers—
total orders”. Also, we only want to show customers who have ordered in 2016.
Order the results by CustomerID.
Expected Result
44
49. Customer grouping—fix null
There's a problem with the answer for the previous question. The CustomerGroup value for
one of the rows is null.
Fix the SQL so that there are no nulls in the CustomerGroup field.
Expected Result
(The total output is still 81 rows, but here we’re only showing the row which had a null
CustomerGroup value in the answer to the previous problem.)
Expected Result
45
51. Customer grouping—flexible
Andrew, the VP of Sales is still thinking about how best to group customers, and define low,
medium, high, and very high value customers. He now wants complete flexibility in grouping
the customers, based on the dollar amount they've ordered. He doesn’t want to have to edit
SQL in order to change the boundaries of the customer groups.
How would you write the SQL?
There's a table called CustomerGroupThreshold that you will need to use. Use only orders
from 2016.
Expected Result
(The expected results are the same as for the original problem, it’s just that we’re getting the
answer differently. The total rows returned will still be 81, we’re just showing a subset here.)
46
52. Countries with suppliers or customers
Some Northwind employees are planning a business trip, and would like to visit as many
suppliers and customers as possible. For their planning, they’d like to see a list of all countries
where suppliers and/or customers are based.
Expected Results
Country
Argentina
Australia
Austria
Belgium
Brazil
Canada
Denmark
Finland
France
Germany
Ireland
Italy
Japan
Mexico
Netherlands
Norway
Poland
Portugal
Singapore
Spain
Sweden
Switzerland
UK
USA
Venezuela
47
53. Countries with suppliers or customers, version 2
The employees going on the business trip don’t want just a raw list of countries, they want
more details. We’d like to see output like the below, in the Expected Results.
Expected Result
SupplierCountry CustomerCountry
NULL Argentina
Australia NULL
NULL Austria
NULL Belgium
Brazil Brazil
Canada Canada
Denmark Denmark
Finland Finland
France France
Germany Germany
NULL Ireland
Italy Italy
Japan NULL
NULL Mexico
Netherlands NULL
Norway Norway
NULL Poland
NULL Portugal
Singapore NULL
Spain Spain
Sweden Sweden
NULL Switzerland
UK UK
USA USA
NULL Venezuela
48
Expected Result
49
Expected Results
50
Expected Result
Expected Results
51
BONAP 2016-02-05 2016-02-09 4
BONAP 2016-03-06 2016-03-11 5
BOTTM 2015-01-10 2015-01-10 0
BOTTM 2016-03-12 2016-03-13 1
BOTTM 2016-03-25 2016-03-27 2
BOTTM 2016-04-23 2016-04-24 1
BSBEV 2015-05-15 2015-05-16 1
BSBEV 2016-03-11 2016-03-13 2
EASTC 2016-04-24 2016-04-28 4
ERNSH 2015-01-02 2015-01-03 1
ERNSH 2015-12-10 2015-12-11 1
ERNSH 2015-12-11 2015-12-15 4
ERNSH 2016-03-23 2016-03-26 3
ERNSH 2016-04-08 2016-04-13 5
FOLKO 2016-03-26 2016-03-27 1
FOLKO 2016-03-27 2016-04-01 5
FOLKO 2016-04-01 2016-04-06 5
FRANK 2015-09-16 2015-09-19 3
52
Congratulations! You've completed the advanced problems.
Any questions or feedback on the problems, hints, or answers? I'd like to hear from you. Please
email me at feedback@SQLPracticeProblems.com.
53
ANSWERS
Introductory Problems
Discussion
This is a basic select statement, returning all rows, just to get you warmed up.
Most of the time, a simple select statement like this is written all on one line, like this:
Select * From Shippers
But because we’ll be getting more complex quickly, we’ll start out with formatting it with
separate lines for each clause, which we’ll be doing in future questions.
54
2. Certain fields from Categories
Select
CategoryName
,Description
from Categories;
Discussion
Instead of doing a “Select *”, we specify the column names, and only get those columns
returned.
3. Sales Representatives
Select
FirstName
,LastName
,HireDate
From Employees
Where
Title = 'Sales Representative';
Discussion
This is a simple filter against a string datatype. When comparing a value to a string datatype,
you need to enclose the value in single quotes.
What happens when you don’t? Try running the following:
Select
FirstName
,LastName
,HireDate
From Employees
Where
Title = Sales Representative
55
What if you compare against a number? Try the following:
Select
FirstName
,LastName
,HireDate
From Employees
Where
Title = 1;
In some database systems you’ll get an error (because a number does not match the character
datatype in the table) but MySQL does not return an error.
Discussion
You can have as many filters in the where clause as you need. I usually indent all the filters,
and put them on new lines, in order to make it easier to read.
56
Where
EmployeeID = 5;
Discussion
This simple query filters for one value in the EmployeeID field, using the “=” comparison
operator.
Here’s another set of very commonly used comparison operators that you’re probably familiar
with from math class:
Discussion
57
ContactTitle != 'Marketing Manager';
Discussion
The “Like” operator is always used with wildcards, such as the percent symbol (%), which
substitutes for any number of characters.
Note that even though the search string used a lowercase “q” with the Like clause
ProductName like '%queso%'
Queso Cabrales
Queso Manchego La Pastora
This is because by default MySQL is case insensitive, although it is also possible to have a
case-sensitive installation, or to specify that a certain column is always case-sensitiv.
58
,ShipCountry
From Orders
where
ShipCountry = 'France'
or ShipCountry = 'Belgium';
Discussion
This is a very simple example, but in many situations you will have multiple where clauses,
with combined “Or” and “And” sections.
In this situation, an alternative would have been to use the “In” operator. We’ll do that in a
future problem.
Discussion
Using the In statement like this is a very common scenario when writing SQL. Whenever
there’s more than just a few—say 2 or 3—values that we’re filtering for, I will generally put
them on separate lines. It’s easier to read, understand, and modify.
Also, many times the list of items you’re filtering for will be coming from somewhere else—
for instance, a spreadsheet—and will already be on separate lines.
59
10. Employees, in order of age
Select
FirstName
,LastName
,Title
,BirthDate
From Employees
Order By Birthdate;
Discussion
Discussion
What we’re using here is called a computed column, also sometimes called a calculated
column. Anytime you’re doing something besides just returning the column, as it is stored in
60
the database, you’re using a computed column. In this case, we’re applying a function to
convert the datatype returned to a Date.
Note that we’ve added a name, DateOnlyBirthDate, for our computed column. This is called an
“alias”.
Date(BirthDate) as DateOnlyBirthDate
Run the following SQL, which does not have an alias name. What shows up as the column
headers?
Select
FirstName
,LastName
,Title
,Date(BirthDate)
From Employees
Order By Birthdate;
Discussion
This is another example of a computed column. In this case, instead of applying a function to a
field, we’re concatenating two fields.
61
13. OrderDetails amount per line item
Select
OrderID
,ProductID
,UnitPrice
,Quantity
, UnitPrice * Quantity as TotalPrice
From OrderDetails
Order by
OrderID
,ProductID;
Discussion
Here we have another example of a computed column, this time using the arithmetic operator
“*”for multiplication.
Discussion
Aggregates functions and grouping are very important when retrieving data. In almost all
cases, when doing data analysis, you’ll be using multiple groupings and aggregates.
62
15. When was the first order?
Select
min(OrderDate) as FirstOrder
From Orders;
Discussion
For the aggregate function Count, you don’t need to specify a column name—just count(*) will
work.
However, for other aggregate functions such as Min, Avg, Sum, etc., you will need to specify a
column name since you’re not just counting all rows.
Discussion
The Group By clause is a cornerstone of SQL. With most data analysis of any complexity at
all, you’ll be using multiple Group By clauses, so they’re important to understand.
Another way of getting the same results is to use the Distinct keyword, as below:
Select distinct
Country
From Customers
Order by
Country;
63
It looks simpler, and works well for queries that are very straightforward. But in everyday use,
you’ll use Group By more often than of Distinct, because you’ll need to use additional
aggregate functions such as Count, and Sum.
Discussion
This particular construction, with a grouping, and then a count of the total in each group, is
very common both on its own, and as a part of other queries.
64
Discussion
Joins can range from the very simple, which we have here, to the very complex. You need to
understand them thoroughly, as they’re critical in writing anything but the simplest SQL.
One thing you’ll see when reading SQL code is, instead of something like the answer above,
something like this:
Select
ProductID
,ProductName
,CompanyName as Supplier
From Products P -- Aliased table
Join Suppliers S -- Aliased table
on P.SupplierID = S.SupplierID;
Notice that the Products table and Suppliers table is aliased, or renamed, with one letter
aliases—P and S. If this is done, the P and S need to be used in the On clause as well.
I’m not a fan of this type of aliasing, although it’s common. The only benefit is avoiding some
typing, which is trivial. But the downside is that the code is harder to read and understand.
It’s not so much a problem in small chunks of SQL like this one. However, in long, convoluted
SQL, you’ll find yourself wondering what the one-letter aliases mean, always needing to refer
back to the From clause, and translate in your head.
The only time I use tables aliases is if the table name is extremely long. And then, I use table
alias names that are understandable, just shortened.
65
Discussion
As the SQL you write gets more complex, it’s even more important to format it so that it’s
easily readable.
66
Intermediate Problems
Discussion
We’re expanding our knowledge of grouping here with a very common scenario—grouping
across two joined tables. In this case, the tables have what’s called a parent-child relationship.
The parent table is Categories, and the child table is Products.
67
Discussion
Note that once you have a Group by clause in a SQL statement, every field that appears in the
Select statement needs to either appear in the Group by clause, or needs to have some kind of
aggregate function applied to it.
If you don’t do this, you will get incorrect results. For instance, try running the following SQL,
with the City commented out in the Group by clause:
Select
Country
,City
,Count(*) as TotalCustomers
From Customers
Group by
Country
-- ,City
Order by
count(*) desc;
Most database systems would give you an error, but in MySQL, it will just give you the
incorrect results.
SQL Server will give the following error message:
68
Discussion
This is a straightforward query on one table. Instead of using a specific string or numeric value
to filter, we’re using another field.
Discussion
Instead of writing
and Discontinued = 0
…you can also write the following if you find it easier to read:
and Discontinued = 'false'
69
24. Customer list by region
Select
CustomerID
,CompanyName
,Region
From Customers
Order By
Case
when Region is null then 1
else 0
End
,Region
,CustomerID
Discussion
Once we have the Case expression set up correctly, you just need to create an Order By clause
for it, and add the additional fields for sorting (Region and CustomerID).
If we had wanted to include the sorting field in the output , you could write this:
Select
CustomerID
,CompanyName
,Region
,Case
when Region is null then 1
else 0
End
as RegionOrder
From Customers
Order By
RegionOrder
,Region
,CustomerID;
You would not need to repeat the case statement in the Order By, you can just refer to the alias
RegionOrder.
70
25. High freight charges
Select
ShipCountry
, Avg(freight) as AverageFreight
From Orders
Group By ShipCountry
Order By AverageFreight desc
Limit 3
Discussion
In MySQL, the keyword Limit is the easiest and most commonly used method of showing only
a certain number of records.
SQL Server uses the keyword Top to do the same thing.
Discussion
71
year(OrderDate) = 2015 -- using Year function
Group By ShipCountry
Order By AverageFreight desc
Limit 3;
This looks straightforward and is easy to read. However, when you put a function such as Year
on the OrderDate field, any indexes that exist won’t be used anymore, so it will potentially be
much slower.
Also, you can only filter for specific calendar years instead of a date range, so it’s not very
flexible.
Discussion
There’s an order made on December 31, 2015 with a really high value in the Freight field. This
would have skewed the results, and put France in third place for highest freight charges, but
only if it were included in the Where clause.
This SQL would have worked fine if OrderDate were a Date field, instead of DateTime.
However, since it’s a DateTime field, it gives an incorrect answer because it's not taking into
account records where the OrderDate is during the day on December 31, 2015.
Note that for a DateTime field, the value
2015-12-31'
is equivalent only to
2015-12-31 00:00:00.000
…and not to values that have a time component.
72
28. High freight charges—last year
Select
ShipCountry
,Avg(freight) as AverageFreight
From Orders
Where
OrderDate >=
DATE_ADD((Select max(OrderDate) from Orders) , INTERVAL -1 year)
Group by ShipCountry
Order by AverageFreight desc
Limit 3;
Discussion
Using SQL like this, that can generate a dynamic date range, is critical for most data analysis
work. Most reports and queries will need to be flexible, without hard-coded date values.
73
Discussion
This problem is more practice with basic joins and multiple tables.
You can replace Join with Inner Join, but mostly people just use Join.
Discussion
There are many ways of getting the same results. The main options are the Left Join with Is
Null, Not In, and Not Exists.
Above, we used the Left Join option. When performance is equivalent, I prefer the Not In
method, shown below.
Select CustomerID
From Customers
Where
CustomerID not in (select CustomerID from Orders);
74
);
Performance for the different options can be affected by whether or not the fields are indexed
or nullable. For additional reading on the pros and cons of each method, do some research
online.
Discussion
Because the filters in the Where clause are applied after the results of the Join, we need the
EmployeeID = 4 filter in the Join clause, instead of the Where clause.
Run the below query and review the results. It should give you a better sense of how the left
join with “is null” works. Note that the Where clause is commented out.
Select
Customers.CustomerID
,Orders.CustomerID
,Orders.EmployeeID
From Customers
left join Orders
on Orders.CustomerID = Customers.CustomerID
and Orders.EmployeeID = 4
-- Where
-- Orders.CustomerID is null;
The most common way to solve this kind of problem is as above, with a left join. However,
here are some alternatives using Not In and Not Exists.
75
Select CustomerID
From Customers
Where
CustomerID not in (select CustomerID from Orders where EmployeeID = 4);
Select CustomerID
From Customers
Where Not Exists
(
Select CustomerID
from Orders
where Orders.CustomerID = Customers.CustomerID
and EmployeeID = 4
);
Advanced Problems
Select
Customers.CustomerID
,Customers.CompanyName
,Orders.OrderID
,SUM(Quantity * UnitPrice) as TotalOrderAmount
From Customers
Join Orders
on Orders.CustomerID = Customers.CustomerID
Join OrderDetails
on Orders.OrderID = OrderDetails.OrderID
Where
OrderDate >= '2016-01-01'
and OrderDate < '2017-01-01'
Group by
Customers.CustomerID
,Customers.CompanyName
76
,Orders.Orderid
Having Sum(Quantity * UnitPrice) > 10000
Order by TotalOrderAmount DESC;
Discussion
Aggregate functions can only be used to filter (with some exceptions) in the Having clause, not
the Where clause.
77
Discussion
All that was necessary here was to comment out references in the Select clause and the Group
By clause to OrderID. By doing that, we're grouping at the Customer level, and not at the
Order level.
Discussion
Note that you need to use the new calculation for order totals with discounts in the Select
clause, the Having clause, and also the Order by clause.
In MySQL, you can just re-use the field via the column alias in the Having clause, like this:
However, in other database systems (such as SQL Server), you must repeat the calculation in
the Having clause, and can’t just re-use it.
78
35. Month-end orders
Select
EmployeeID
,OrderID
,OrderDate
From Orders
Where OrderDate = Last_Day(OrderDate )
Order by
EmployeeID
,OrderID;
Discussion
Very frequently the end of the month will be needed in queries and reports. The Last_Day
function is very useful in these cases.
Here’s a bonus question for you. There are actually 2 more orders where the OrderDate is the
end of the month. They are OrderID 10806 and 10807.
Why are they not showing up in the results? Can you modify the SQL to show these 2 orders
as well?
Discussion
79
37. Orders—random assortment
Select
OrderID
From Orders
Order By Rand()
Limit 10;
Discussion
Using the Rand() function, and then ordering by it and limiting the result, is a reasonable way
of getting a random set of records from a table. However, it may be slow if the table is large.
There are other techniques that can be used if performance is an issue. You can do research
online to find some better, more complex techniques.
Discussion
This SQL shows orders that have at least 1 order detail with a quantity of 60 or more (the
Where clause), and the quantity is duplicated within the order (the Group by and Having
clause). This occurs because we're grouping on both OrderID and Quantity.
80
39. Orders—accidental double-entry details
with PotentialDuplicates as (
Select
OrderID
From OrderDetails
Where Quantity >= 60
Group By OrderID, Quantity
Having Count(*) > 1
)
Select
OrderID
,ProductID
,UnitPrice
,Quantity
,Discount
From OrderDetails
Where
OrderID in (Select OrderID from PotentialDuplicates)
Order by
OrderID
,Quantity;
Discussion
There are quite a few different ways of getting the same results for this problem. Based on
years of painful troubleshooting caused by poorly-written, tangled SQL, I suggest that writing
easily understandable, straightforward code is one of the most important things to strive for.
Using a well thought-out CTE is one way of doing this.
In the next problem, we'll look at another way of getting the same result.
81
Join (
Select distinct
OrderID
From OrderDetails
Where Quantity >= 60
Group By OrderID, Quantity
Having Count(*) > 1
) PotentialProblemOrders
on PotentialProblemOrders.OrderID = OrderDetails.OrderID
Order by OrderID, ProductID;
Discussion
Note the Distinct keyword, added after the Select in the derived table. This gives us only
distinct rows in the output, which avoids the problem with duplicate OrderIDs.
Discussion
This is a straight-forward query that we'll use as a base for future problems.
82
42. Late orders—which employees?
Select
Employees.EmployeeID
,LastName
,Count(*) as TotalLateOrders
From Orders
Join Employees
on Employees.EmployeeID = Orders.EmployeeID
Where
RequiredDate <= ShippedDate
Group By
Employees.EmployeeID
,Employees.LastName
Order by TotalLateOrders desc;
Discussion
In many database systems (such as SQL Server), when a query has a Group By clause, each
column in the Select statement needs to either also be grouped by, or have an aggregate (sum,
count) applied to it.
MySQL does not require this. A column in a query that has a Group By clause does not have to
be in the Group by clause, or have an aggregate.
In SQL Server, you would get the following error:
Msg 8120, Level 16, State 1, Line 3
Column 'Employees.LastName' is invalid in the select list because it is not contained
in either an aggregate function or the GROUP BY clause.
In MySQL, you would not get an error. However, you may not get the results you’re looking
for, since it will just by default apply a “Min” to the field.
83
From Orders
Where
RequiredDate <= ShippedDate
Group By
EmployeeID
)
, AllOrders as (
Select
EmployeeID
,Count(*) as TotalOrders
From Orders
Group By
EmployeeID
)
Select
Employees.EmployeeID
,LastName
,AllOrders.TotalOrders as AllOrders
,LateOrders.TotalOrders as LateOrders
From Employees
Join AllOrders
on AllOrders.EmployeeID = Employees.EmployeeID
Join LateOrders
on LateOrders.EmployeeID = Employees.EmployeeID
Order by Employees.EmployeeID;
Discussion
The above query is almost correct, but if you're paying careful attention, you'll realize it has a
slight problem. We'll learn more in the next problem.
84
Group By
EmployeeID
)
, AllOrders as (
Select
EmployeeID
,Count(*) as TotalOrders
From Orders
Group By
EmployeeID
)
Select
Employees.EmployeeID
,LastName
,AllOrders.TotalOrders as AllOrders
,LateOrders.TotalOrders as LateOrders
From Employees
Join AllOrders
on AllOrders.EmployeeID = Employees.EmployeeID
Left Join LateOrders
on LateOrders.EmployeeID = Employees.EmployeeID;
Discussion
The above SQL shows all employees who have made orders, even if they have no late orders.
What would we need to do if we wanted to show all employees, even if they have not been the
sales person (EmployeeID) for an Order?
85
Select
EmployeeID
,Count(*) as TotalOrders
From Orders
Group By
EmployeeID
)
Select
Employees.EmployeeID
,LastName
,AllOrders.TotalOrders as AllOrders
,IfNull(LateOrders.TotalOrders, 0) as LateOrders
From Employees
Join AllOrders
on AllOrders.EmployeeID = Employees.EmployeeID
Left Join LateOrders
on LateOrders.EmployeeID = Employees.EmployeeID;
Discussion
Using a straightforward IfNull on LateOrder is the best way to solve this problem.
Another way to write it would be using a Case statement
,Case
When LateOrders.TotalOrders is null Then 0
Else LateOrders.TotalOrders
End as LateOrders
But when you don’t need any other logic besides a test for null, IfNull is the way to go.
86
EmployeeID
)
, AllOrders as (
Select
EmployeeID
,Count(*) as TotalOrders
From Orders
Group By
EmployeeID
)
Select
Employees.EmployeeID
,LastName
,AllOrders.TotalOrders as AllOrders
,IfNull(LateOrders.TotalOrders, 0) as LateOrders
,IfNull(LateOrders.TotalOrders, 0)/ AllOrders.TotalOrders
as PercentLateOrders
From Employees
Join AllOrders
on AllOrders.EmployeeID = Employees.EmployeeID
Left Join LateOrders
on LateOrders.EmployeeID = Employees.EmployeeID;
Discussion
87
Group By
EmployeeID
)
, AllOrders as (
Select
EmployeeID
,Count(*) as TotalOrders
From Orders
Group By
EmployeeID
)
Select
Employees.EmployeeID
,LastName
,AllOrders.TotalOrders as AllOrders
,IfNull(LateOrders.TotalOrders, 0) as LateOrders
,Cast(
IfNull(LateOrders.TotalOrders, 0)/ AllOrders.TotalOrders
as Decimal (4,2)
)
as PercentLateOrders
From Employees
Join AllOrders
on AllOrders.EmployeeID = Employees.EmployeeID
Left Join LateOrders
on LateOrders.EmployeeID = Employees.EmployeeID;
Discussion
Rounding, truncating, and converting data types can get complicated, and there are many ways
that you could get unexpected results. Always check your results carefully, and know whether
you want rounding, or truncation.
Frequently, when creating this kind of query, you’ll put the output into a tool like Excel, and
do any additional formatting such as setting the decimal precision there. However, it’s good to
at least know how to do it in SQL.
You may have noticed that I added multiple lines in the calculation to make it easier to read.
This isn’t necessary—you could put everything on one line—but it’s good programming
practice, and easier to read and troubleshoot.
88
48. Customer grouping
with Orders2016 as (
Select
Customers.CustomerID
,Customers.CompanyName
,SUM(Quantity * UnitPrice) as TotalOrderAmount
From Customers
Join Orders
on Orders.CustomerID = Customers.CustomerID
Join OrderDetails
on Orders.OrderID = OrderDetails.OrderID
Where
OrderDate >= '2016-01-01'
and OrderDate < '2017-01-01'
Group by
Customers.CustomerID
,Customers.CompanyName
)
Select
CustomerID
,CompanyName
,TotalOrderAmount
,Case
when TotalOrderAmount between 0 and 1000 then 'Low'
when TotalOrderAmount between 1001 and 5000 then 'Medium'
when TotalOrderAmount between 5001 and 10000 then 'High'
when TotalOrderAmount > 10000 then 'Very High'
End
as CustomerGroup
from Orders2016
Order by CustomerID;
Discussion
(Note—there's a small bug in the above SQL, which we'll review in the next problem.)
A CTE works well for this problem, but it's not strictly necessary. You could also use SQL like
this:
Select
Customers.CustomerID
,Customers.CompanyName
,SUM(Quantity * UnitPrice) as TotalOrderAmount
,Case
when SUM(Quantity * UnitPrice) between 0 and 1000 then 'Low'
when SUM(Quantity * UnitPrice) between 1001 and 5000 then 'Medium'
when SUM(Quantity * UnitPrice) between 5001 and 10000 then 'High'
89
when SUM(Quantity * UnitPrice) > 10000 then 'Very High'
End as CustomerGroup
From Customers
Join Orders
on Orders.CustomerID = Customers.CustomerID
Join OrderDetails
on Orders.OrderID = OrderDetails.OrderID
Where
OrderDate >= '2016-01-01'
and OrderDate < '2017-01-01'
Group By
Customers.CustomerID
,Customers.CompanyName;
This gives the same result, but notice that the calculation for getting the TotalOrderAmount
was repeated 5 times, including the 4 times in the Case statement.
It's far better to avoid repeating calculations like this. The calculations will usually be quite
complex and difficult to read, and you want to have them only in one place. In something
simple, like Quantity * UnitPrice, it's not necessarily a problem. But most of the time, you
should avoid repeating any calculations and code. An easy way to remember this is with the
acronym DRY, which stands for “Don’t Repeat Yourself”.
Here’s an article on the topic: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
90
Select
CustomerID
,CompanyName
,TotalOrderAmount
,Case
when TotalOrderAmount >= 0 and TotalOrderAmount < 1000
then 'Low'
when TotalOrderAmount >= 1000 and TotalOrderAmount < 5000
then 'Medium'
when TotalOrderAmount >= 5000 and TotalOrderAmount <10000
then 'High'
when TotalOrderAmount >= 10000
then 'Very High'
End as CustomerGroup
from Orders2016
Order by CustomerID;
Discussion
As you've been seeing in the above problems, knowing the data types you're working with and
understanding the differences between them is important to get the right results. Using
“between” would have been fine for integer values, but not for decimal.
91
)
,CustomerGrouping as (
Select
CustomerID
,CompanyName
,TotalOrderAmount
,Case
when TotalOrderAmount >= 0 and TotalOrderAmount < 1000
then 'Low'
when TotalOrderAmount >= 1000 and TotalOrderAmount < 5000
then 'Medium'
when TotalOrderAmount >= 5000 and TotalOrderAmount <10000
then 'High'
when TotalOrderAmount >= 10000
then 'Very High'
End
as CustomerGroup
from Orders2016
)
Select
CustomerGroup
,Count(*) as TotalInGroup
,Count(*)/(select count(*) from CustomerGrouping)
as PercentageInGroup
from CustomerGrouping
group by CustomerGroup
order by TotalInGroup desc;
Discussion
92
,Customers.CompanyName
,SUM(Quantity * UnitPrice) as TotalOrderAmount
From Customers
Join Orders
on Orders.CustomerID = Customers.CustomerID
Join OrderDetails
on Orders.OrderID = OrderDetails.OrderID
Where
OrderDate >= '2016-01-01'
and OrderDate < '2017-01-01'
Group by
Customers.CustomerID
,Customers.CompanyName
)
Select
CustomerID
,CompanyName
,TotalOrderAmount
,CustomerGroupName
from Orders2016
Join CustomerGroupThresholds
on Orders2016.TotalOrderAmount between
CustomerGroupThresholds.RangeBottom
and CustomerGroupThresholds.RangeTop
Order by CustomerID;
Discussion
Note that this gives the same results as the original problem. However, instead of using hard-
coded values in the Case statement to define the boundaries of the CustomerGroups, you have
them in a table.
The benefit of this is that you can just reference the table, instead of duplicating a complex
Case statement, in every query where you want to group customers the same way.
Also, take a look at the values in CustomerGroupThresholds.
Note that there's no overlap between the rows when you look at RangeBottom and RangeTop,
so you can use “between”. You need to be careful with this, and pay attention to how many
digits there are to the right of the decimal, to make sure there are no potential values that could
be missed.
93
52. Countries with suppliers or customers
Select Country From Customers
Union
Select Country From Suppliers
Order by Country;
Discussion
There are 2 ways of using the Union statement. One is a simple Union as in the answer here.
Using a simple Union statement eliminates all the duplicates in the resultset.
You can also use Union All. Try it and take a look at the resultset:
Notice that within the individual SQL statements, I’ve put a Distinct. However, there are still
duplicates in the final output, because we have Union All, which does not eliminate duplicates.
94
Left Join SupplierCountries
on AllCountries.Country = SupplierCountries.Country
Order by AllCountries.Country;
Discussion
If you just joined from the AllCountries CTE directly to the Suppliers table and the Customers
table (without doing an intermediate CTE that does a Distinct), what would happen?
Here’s an alternate way of writing the query, which returns the same results. It uses derived
tables instead of CTEs.
Select
SupplierCountries.Country as SupplierCountry
,CustomerCountries.Country as CustomerCountry
From
(Select Country from Suppliers
Union
Select Country from Customers)
AllCountries
Left Join (Select Distinct Country from Suppliers)
CustomerCountries
on AllCountries.Country = CustomerCountries.Country
Left Join (Select Distinct Country from Suppliers)
SupplierCountries
on AllCountries.Country = SupplierCountries.Country
Order by AllCountries.Country;
95
,IfNull(SupplierCountries.Total,0) as TotalSuppliers
,IfNull(CustomerCountries.Total,0) as TotalCustomers
From AllCountries
Left Join CustomerCountries
on AllCountries.Country = CustomerCountries.Country
Left Join SupplierCountries
on AllCountries.Country = SupplierCountries.Country
Order by AllCountries.Country;
Discussion
Note that we had to switch from Distinct to Group By in the CTE, because we needed to get
the total with Count(*). You can’t use Distinct in this situation.
96
Discussion
In previous versions of MySQL, before Window functions were available, there were other
options to get the same results. However, they were much more difficult to write.
Having the Window functions (Row_Number() plus many others) makes it much easier to get
some very useful information.
Discussion
Including multiple instances of a table is one way of finding the answer we need.
When aliasing tables and columns, be careful to name them something meaningful, so you can
read and understand your SQL.
97
57. Customers with multiple orders in 5 day period, version 2
With NextOrderDate as (
Select
CustomerID
,Date(OrderDate) as InitialOrderDate
,Date(Lead(OrderDate,1)
OVER (Partition by CustomerID order by CustomerID, OrderDate)
) as NextOrderDate
From Orders
)
Select
CustomerID
,InitialOrderDate
,NextOrderDate
,DateDiff (NextOrderDate, InitialOrderDate) as DaysBetweenOrders
From NextOrderDate
Where
DateDiff (NextOrderDate, InitialOrderDate ) <= 5;
Discussion
There’s two main ways of solving this problem, the first using multiple instances of the table
(which we did in the first version of the problem), and the other using Window functions.
Which is better? If we’re okay with getting a narrower resultset, I’d prefer this version, using
the Lead window function, instead of the previous solution.
But if we need multiple columns from the following order, then it’s best to use the first
version. Otherwise, you’d need multiple calculated columns with the same Partition and Order
by.
Notice that the row count between the 2 answers are slightly different, 71 and 69. One of the
customers that causes this discrepancy is CustomerID ERNSH. Look at the results of the
answer SQL from problem # 56. Why would one OrderID show up twice?
98
Congratulations!
You’re finished! Now that you’ve completed the practice problems, you’ve improved your
SQL skills tremendously, and increased your ability in a skill that’s in enormous demand.
If you have a moment, I would really appreciate a review of this book on Amazon. Your
honest opinion can help people decide between the many SQL learning options available.
Any comments and suggestions are most welcome! Please email me at:
feedback@SQLPracticeProblems.com.
Thank you!
Sylvia Moestl Vasilik
99