OSSQL.009: Common Table Expressions — WITH, Named Queries and Chained Results

Colored-pencil illustration of an engineering database workstation and server racks.

Open-Source SQL Programming • Intermediate • Estimated study time: 30 minutes.

A common table expression (CTE) names a query result for use within a single SQL statement. Naming intermediate results makes multi-stage queries easier to read, inspect and maintain. In the preceding subqueries lesson, nested SELECT statements supplied intermediate values. An ordinary CTE offers another way to express related query stages.

Prerequisites and learning objectives

Use the SQLite command-line shell or a local SQLite graphical client. Review aggregate functions and GROUP BY. By completion, learners can define a statement-scoped CTE, chain two CTEs, filter aggregated results, preserve missing-data semantics and distinguish CTEs from persistent database objects. Run all examples against disposable local data, never production telemetry.

Statement scope and syntax

The SQLite WITH clause reference explains ordinary and recursive CTEs. An ordinary CTE is declared with WITH name AS followed by a parenthesized query. The following SELECT can reference the declared name as a relation. The name is not a permanent table or view. Multiple CTE definitions share a single WITH keyword and are separated by commas. Recursive CTEs are a separate technique for iterative and hierarchical queries.

Alex The Analyst introduces common table expressions and named query results. The demonstration uses a different SQL dialect; the laboratory below uses SQLite. Watch at source.

Laboratory: simulated rack telemetry

Open a local SQLite session using sqlite3 :memory: and enter the following synthetic dataset:

CREATE TABLE readings(rack TEXT, temp REAL);
INSERT INTO readings VALUES
  ('A',24),('A',30),('B',36),('B',40),('C',NULL);

Each row represents a simulated temperature reading in degrees Celsius. Rack C has an unknown reading, not a measured zero. Calculate one average per rack using the following query:

WITH rack_avg AS (
  SELECT rack, AVG(temp) AS mean_temp
  FROM readings GROUP BY rack
)
SELECT rack, mean_temp FROM rack_avg
ORDER BY rack;

Rack A returns 27.0°C, rack B returns 38.0°C, and rack C returns NULL. The SQLite aggregate function reference confirms that AVG ignores NULL inputs and returns NULL when no non-NULL input exists. The final ORDER BY ensures predictable presentation; a CTE does not guarantee output order.

Chaining named query stages

Separate aggregation from filtering by adding a second CTE. The same principle applies when combining results from SQL joins with subsequent transformations. Execute the following statement:

WITH rack_avg AS (
  SELECT rack, AVG(temp) AS mean_temp
  FROM readings GROUP BY rack
), hot AS (
  SELECT rack, mean_temp FROM rack_avg
  WHERE mean_temp >= 30
)
SELECT rack, mean_temp FROM hot ORDER BY rack;

Only rack B qualifies, with 38.0°C. Rack C does not satisfy the comparison because NULL represents an unknown value. The 30°C threshold is illustrative, not a recommended facility alarm setting. The database optimizer may inline or materialize intermediate results; naming a CTE alone does not guarantee caching or improved performance.

The SQL WITH Clause tutorial demonstrates common table expressions and how to organize query logic. Watch at source.

Missing data and scope

Use IS NULL to distinguish missing information from valid readings. Identify racks without a usable average using the following statement:

WITH rack_avg AS (
  SELECT rack, AVG(temp) AS mean_temp
  FROM readings GROUP BY rack
)
SELECT rack FROM rack_avg WHERE mean_temp IS NULL;

Rack C is returned. After the terminating semicolon, rack_avg no longer exists unless a separate database object with that name was created. Unlike a stored view or temporary table, an ordinary CTE is available only within its enclosing statement.

Exercises and answer key

Exercise 1: Change the chained query threshold to 27°C. Exercise 2: Explain why rack C is omitted by a numeric comparison. Exercise 3: Identify the syntax separating two CTE definitions. Exercise 4: Explain why a CTE name cannot normally be queried in a subsequent statement.

Answers: 1. Racks A and B qualify. 2. A comparison with NULL yields unknown, which WHERE does not retain. 3. A comma separates the definitions following WITH. 4. The CTE is statement-scoped rather than a separately created table. Four query-result assertions and one statement-scope failure assertion passed in SQLite 3.46.1. The examples contain synthetic data.

Conclusion

CTEs organize complex relational operations into named stages without requiring permanent objects. Validate each stage, account for NULL explicitly and use ORDER BY for reproducible reports. Consult the official SQLite documentation before relying on engine-specific optimization behavior.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply