← Back to SQL, page 6

sql-0112 · Easy fresher

Can one CTE refer to another CTE defined earlier in the same WITH clause? Can it refer to one defined later?

Yes to the first: each CTE in a WITH list can use the ones defined before it. Referring to a CTE defined later is rejected by PostgreSQL, while SQLite resolves the forward reference anyway. Write CTEs in dependency order so the query works everywhere and reads top to bottom.

Full answer

A WITH clause is a list of named steps, read top to bottom. Later steps can build on earlier ones:

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
WITH scored AS (
  SELECT student_id, marks, marks >= 70 AS passed FROM enrolments WHERE marks IS NOT NULL
),
pass_counts AS (
  SELECT student_id, SUM(passed) AS passes FROM scored GROUP BY student_id
)
SELECT s.name, p.passes
FROM pass_counts p JOIN students s ON s.id = p.student_id
ORDER BY s.name;
namepasses
Asha2
Ben1
Chen2
Eli0

pass_counts uses scored, which was defined just before it.

Referring forward is where engines differ. SQLite accepts it and finds b even though it is defined later:

sql
WITH a AS (SELECT * FROM b), b AS (SELECT 1 AS x)
SELECT * FROM a;
x
1

PostgreSQL does not. Without RECURSIVE, a CTE can only see the CTEs listed before it:

sql
WITH a AS (SELECT * FROM b), b AS (SELECT 1 AS x)
SELECT * FROM a;
-- error on purpose
text
Error: relation "b" does not exist

Writing CTEs in dependency order avoids the question entirely, and it keeps WITH clauses readable: each step depends only on what is above it, so a reviewer can check them one at a time.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

WITH scored AS (
  SELECT student_id, marks, marks >= 70 AS passed FROM enrolments WHERE marks IS NOT NULL
),
pass_counts AS (
  SELECT student_id, SUM(passed) AS passes FROM scored GROUP BY student_id
)
SELECT s.name, p.passes
FROM pass_counts p JOIN students s ON s.id = p.student_id
ORDER BY s.name;

WITH a AS (SELECT * FROM b), b AS (SELECT 1 AS x)
SELECT * FROM a;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • CTEs in one WITH list are defined in order
  • Each CTE can use the CTEs above it
  • PostgreSQL rejects forward references; SQLite accepts them
  • Self-reference needs WITH RECURSIVE in PostgreSQL

Common mistakes

  • Ordering CTEs by importance instead of by dependency
  • Expecting a CTE from one statement to be visible in the next statement

Follow-ups

  • Can you define a CTE inside a subquery?
  • Can two CTEs refer to each other?

Tips

  • Describe a WITH list as a pipeline of named steps