Simplify queries, WITH keyword
Part of the Fundamentals section of Coddy's SQL journey — lesson 49 of 72.
Queries can get too messy by adding many inner queries. For example here is a query that has many sub-queries:
SELECT * FROM table1
WHERE col2 IN (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
)
)To make it easier we can use the WITH query_name AS (...) keyword. It allows us to save a query with a name and use it wherever we want:
WITH query1 AS (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
), query2 AS (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN query1
)
SELECT * FROM table1
WHERE col2 IN query2 AND col4 IN query1Here we reused query1 in query2 and in the main query.
Challenge
EasyAvailable tables and columns:
<strong>devices_specs</strong>:<strong>device_id</strong>,<strong>width</strong>,<strong>height</strong>,<strong>num_features</strong>,<strong>opinion</strong><strong>devices_score</strong>:<strong>device_id</strong>,<strong>score</strong>
write a query that:
- First identifies "large devices" (devices with
widthgreater than 200) - Then calculates the average score for these large devices. Call this column as
average_score
Use the WITH clause to solve this problem.
Cheat sheet
Use WITH query_name AS (...) to create named subqueries that can be reused:
WITH query1 AS (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
), query2 AS (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN query1
)
SELECT * FROM table1
WHERE col2 IN query2 AND col4 IN query1This approach makes complex queries with multiple subqueries more readable and allows reusing the same subquery multiple times.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns9Multiple tables
Basic Join Part 1Basic Join Part 2Recap - JoinSelf joinRecap - Self JoinUnionSimplify queries, WITH keywordRecap - With QueriesRecap - Real Estate Contractor