Common Table Expressions
Learn how to separate a subquery from its enclosing query for more comprehensive and readable SQL code.
We'll cover the following...
In our running example, we consider car models and the assembly of their parts. In SQL, we modeled this example through a table called CarModel that we populated with sample cars:
Since these cars are assembled from different parts, we also record these in a separate table called CarPart. This also allows us to oversee our assembly progress. As the database engineer, we propose the following data model for the car parts:
The database table CarPart consists of three columns, namely model, name, and built_at. The first column, model, references the car model that this part belongs to as a foreign key (i.e., FOREIGN KEY (model) REFERENCES CarModel (id)). name records the name of the car part and constitutes the primary key of CarPart together with model (i.e., PRIMARY KEY (model, name(256))). For our example, we ...