DEV Community

Cover image for Unlock the Power of CTEs: Simplify and Optimize Your SQL Queries

Posted on


Unlock the Power of CTEs: Simplify and Optimize Your SQL Queries

CTE stands for Common Table Expression, it's a feature in SQL that allows you to define a temporary result set that you can refer to within the context of a single SELECT, INSERT, UPDATE, or DELETE statement.

CTEs are similar to subqueries but are defined using the WITH clause and can be self-referencing and can be used multiple times in the same query.

The basic syntax for a CTE is as follows:

WITH table_expression_name (column1, column2, ...) AS (
  SELECT ...
FROM table_expression_name
Enter fullscreen mode Exit fullscreen mode

Where table_expression_name is the reference name.

Key differences between Temporary Tables and CTEs

Feature CTEs Temporary Tables
Syntax WITH clause CREATE TEMPORARY TABLE statement
Scope Only visible to the query in which they are defined Visible to the current session
Lifetime Only available for the duration of the query Remain in the database until they are explicitly dropped or the session ends
Persistence Not persistent, results not stored in the database Stored in the database and its result can be used by multiple queries or even different sessions
Recursive CTEs Supported Not Supported
Speed (depending on the size of data) CTEs


WITH top_selling_products (product, sales) AS (
  SELECT product, SUM(quantity) as sales
  FROM orders
  GROUP BY product
SELECT product, sales
FROM top_selling_products;
Enter fullscreen mode Exit fullscreen mode

In this example, the CTE top_selling_products is defined to return the top 3 products based on total sales. The final statement retrieves the product and sales.


Overall, CTEs can help simplify complex queries and improve readability and maintainability of your code. They also help to avoid repetitive code, and can improve the performance of your queries by reducing the need for subqueries.

Top comments (0)

Super Useful CSS Resources

A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.