WITH (CTE)

Advanced

Common Table Expression — a named temporary result set that you can reference within a query.

Syntax

WITH name AS (SELECT ...) SELECT ... FROM name

Example

WITH top_customers AS (
  SELECT customer_id, SUM(amount) as total
  FROM orders
  GROUP BY customer_id
  ORDER BY total DESC
  LIMIT 10
)
SELECT c.name, tc.total
FROM top_customers tc
JOIN customers c ON tc.customer_id = c.id;

About SQL WITH (CTE)

The WITH (CTE) keyword belongs to the Advanced category of SQL statements. Common Table Expression — a named temporary result set that you can reference within a query. Understanding this command is essential for any developer working with relational databases like PostgreSQL, MySQL, SQLite, or SQL Server.

SQL (Structured Query Language) is the standard language for managing and querying relational databases. The WITH (CTE) statement is supported across all major database systems, though specific syntax may vary slightly between PostgreSQL, MySQL, MariaDB, Oracle, SQL Server, and SQLite. Always consult your database's documentation for vendor-specific features and limitations.

Best practices for using WITH (CTE): always test queries on a development database before running them in production, use parameterized queries to prevent SQL injection, and leverage EXPLAIN to understand query performance. For complex queries, consider using CTEs (Common Table Expressions) to improve readability and maintainability.

Related SQL Keywords