Menu
Coddy logo textTech

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 query1

Here we reused query1 in query2 and in the main query.

challenge icon

Challenge

Easy

Available 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:

  1. First identifies "large devices" (devices with width greater than 200)
  2. 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 query1

This approach makes complex queries with multiple subqueries more readable and allows reusing the same subquery multiple times.

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals