Databases · Middle · Question 28 of 75

What is a CTE (WITH ...) good for?

WITH recent AS (
  SELECT * FROM orders WHERE created_at > now() - interval '7 days'
)
SELECT user_id, COUNT(*) FROM recent GROUP BY user_id;

Explanation

Since PostgreSQL 12, simple CTEs are inlined into the main query and optimized together. MATERIALIZED forces computing the CTE once.

Further reading

Problem with a question

Databases · Middle · question 28

Test yourself

Take the Databases · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz