Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Subqueries are powerful tools for writing complex SQL queries. Unfortunately, they can also lead to difficult-to-understand SQL. Learn how to make your SQL more readable and modular by converting subqueries to common table expressions.
Example Code
Subquery Example
SELECT
all_orders.EmployeeID,
Employees.LastName,
all_orders.order_count AS total_order_count,
late_orders.order_count AS late_order_count
FROM (
SELECT EmployeeID, COUNT(*) AS order_count
FROM Orders
GROUP BY EmployeeID
) all_orders
JOIN (
SELECT EmployeeID, COUNT(*) AS order_count
FROM Orders
WHERE RequiredDate <= ShippedDate
GROUP BY EmployeeID
) late_orders
ON all_orders.EmployeeID = late_orders.employeeID
JOIN Employees
ON all_orders.EmployeeId = Employees.Id
Rewritten with Common Table Expresssions
WITH all_orders AS (
SELECT EmployeeID, COUNT(*) AS order_count
FROM Orders
GROUP BY EmployeeID
),
late_orders AS (
SELECT EmployeeID, COUNT(*) AS order_count
FROM Orders
WHERE RequiredDate <= ShippedDate
GROUP BY EmployeeID
)
SELECT
Employees.ID, LastName,
all_orders.order_count AS total_order_count,
late_orders.order_count AS late_order_count
FROM Employees
JOIN all_orders ON Employees.ID = all_orders.EmployeeID
JOIN late_orders ON Employees.ID = late_orders.EmployeeID
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up