SQL QuestSQL Interview Questions › Subqueries & CTEs

Filter on an Average You Just Computed

EasyFreeQuerying BasicsSubqueries & CTEsAggregation & Grouping

Sales want the countries where the average order is worth more than 200. The average has to be computed first and only then filtered.

Show exactly these 2 columns, in this order: country, avg_order. avg_order is the average of total across that country's orders, rounded to 2 decimals and aliased exactly avg_order. Keep only countries whose avg_order is strictly greater than 200. Order by avg_order descending, then country ascending.

The new idea: a whole query can sit in the FROM clause. FROM (SELECT country, ROUND(AVG(total), 2) AS avg_order FROM orders GROUP BY country) AS country_avg builds a small table of one row per country, and the outer query then treats it like any other table — so WHERE avg_order > 200 is legal, filtering a column that did not exist a moment earlier.

Two things people forget. The derived table needs a name (AS country_avg), or SQLite has nothing to call the thing you just built. And yes, HAVING ROUND(AVG(total), 2) > 200 would also work here — the derived table earns its keep once that computed column is used more than once or joined to something, and this is the smallest place to see the shape.

Solve it in the browser editor →

Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".

Schema

orders

order_idcustomer_idproductcategoryquantitypricetotalorder_datecountrystatus
11Laptop ProElectronics11299.991299.992024-01-15USAcompleted
22Wireless MouseElectronics249.9999.982024-01-16Canadacompleted
33Office ChairFurniture1349.99349.992024-01-17USAcompleted

Expected output: 3 rows — Germany 302.49, USA 256.42, Japan 213.32

Hint

The hint for this one spells out most of the query, so it stays in the editor. Reach for SELECT, Subquery, Derived Table, and open the hint there if you stall.

Concepts

SELECT Subquery Derived Table Aggregation GROUP BY

Practise the topic: SQL practice questions · CTE practice · GROUP BY exercises

In these company practice sets

Walmart · LinkedIn

A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.

Related questions

A Subquery That Returns One ValueEasy · FreeA Subquery That Returns a Set (IN)Easy · FreeGive a Query a Name (WITH)Easy · FreeMovies Rated Above the AverageEasy · FreeEvery Film by a Director Who Once Hit 8.5Easy · FreeBetter Than Its Own GenreEasy · Free

Where would this cost you points in an interview?

Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.

Take the readiness test