Junior Track Roadmap

ActiveRecord: CTE basics

This course covers non-recursive Common Table Expressions in Postgres and how ActiveRecord builds them. It starts with the SQL a WITH clause produces, then moves to ActiveRecord::Relation#with and the injection warning in its doc comments for raw Arel.sql strings. It shows that defining a CTE has no effect until .from or .joins references it by name. Later lessons join a CTE built from grouped enrollment data, build one CTE from another, and use EXPLAIN to test the optimization fence claim on PostgreSQL 12 and later.

What you'll learn

  • ✓How WITH names a subquery for the length of one statement
  • ✓Building CTEs with ActiveRecord::Relation#with and the SQL injection risk of Arel.sql
  • ✓Connecting a CTE to the query with .from or .joins
  • ✓Joining against a CTE built from grouped data
  • ✓Chaining CTEs and the order rule Postgres enforces
  • ✓Reading EXPLAIN plans for inlined and MATERIALIZED CTEs
Free preview · Lesson 1 2 min read

WITH: giving a subquery a name you can reuse

SQL: grouping & aggregates used GROUP BY with HAVING to keep only the groups above a threshold, such as courses with more than one enrollment. Written as a subquery, that result is computed once and thrown away as soon as the outer query finishes. Postgres can compute the same subquery and give it…

Read the full lesson free →

Curriculum

7 lessons
Type to start searching...