Subquery Examples

Inline Subquery

  • creates a table that you could then query again in the FROM statement

Expert Tip

Note that you should not include an alias when you write a subquery in a conditional statement. This is because the subquery is treated as an individual value (or set of values in the IN case) rather than as a table. Nested and Scalar subqueries often do not require aliases the way WITH and Inline subqueries do.

FROM orders
WHERE DATE_TRUNC('month',occurred_at) =
 (SELECT DATE_TRUNC('month',MIN(occurred_at)) AS min_month
  FROM orders)
ORDER BY occurred_at

This query works because the result of the subquery is only one cell. Most conditional logic will work with subqueries containing one-cell results. But IN is the only type of conditional logic that will work when the inner query contains multiple results.


STEP 1 – Use DATE_TRUNC to pull month level information above the first order ever placed in the orders table.

SELECT DATE_TRUNC('month', MIN(occurred_at)) as first_order
FROM orders;

STEP 2 – Use the result of the previous query to find only the orders that took place in the same month and year as the first order, and then pull the average for each type of paper qty in this month.

  • Find all the orders placed on the date from first_order
  • Get the average qty of all those orders placed per paper type
  • Final output – column per each paper type with average qty
SELECT AVG(standard_qty) AVG_Standard, AVG(gloss_qty) AVG_Gloss, AVG(poster_qty) AVG_Poster
FROM orders
	WHERE DATE_TRUNC('month', occurred_at) = (SELECT 	DATE_TRUNC('month', MIN(occurred_at)) as first_order
	FROM orders)

The total amount spent on all orders on the first month that any order was placed in the orders table (in terms of usd).

SELECT SUM(total_amt_usd)
FROM orders
	WHERE DATE_TRUNC('month', occurred_at) = (SELECT 	DATE_TRUNC('month', MIN(occurred_at)) as first_order
	FROM orders)

I got everything correct! 😊 

This entry was posted in Study Notes and tagged . Bookmark the permalink.

Leave a Reply