Self Join, UNION ALL Reports, Views & Foreign Keys
Assignment review (team stats, profit rides, hierarchy report), then views, referential integrity and identity columns in SQL Server.
The Crux in 60 Seconds
Self join to see the "next row"
A single row cannot tell you about the following ride. Join the table to itself on id, end_location = start_location and end_time = start_time. Use a LEFT JOIN so every ride stays, then count matches.
UNION ALL stacks report blocks
One SELECT per hierarchy (category, subcategory, ship mode), each with a literal hierarchy_type. Every block needs the same number of columns; output column names come from the first query.
A view stores a query, not data
Querying a view re-runs its SELECT on the base tables every time. It sees new data, takes no storage, and fails if a base table is gone. Good for sharing big queries and regional slices.
Foreign key means parent first
A value in the child column must already exist in the parent's primary key (NULL is allowed unless the column is NOT NULL). Orphan inserts, and deletes or updates of a referenced parent row, throw errors.
Foundational Concepts & Comparisons
UNION
- Removes duplicate rows; the database still sorts and de-duplicates.
- Use it when you need a unique list: team_1 plus team_2 gives 6 unique teams.
UNION ALL
- Keeps every row, so the same query gives 10 rows (India repeats).
- Use it when every row must count (matches played) or when you know there are no duplicates, as in the hierarchy report.
Table
- Physical object that holds the data.
- Data stays until you change or delete it.
View (virtual table)
- Holds only a
SELECTdefinition: an "envelope" around a query. No data, no storage. - Still a permanent database object: it survives log-out and anyone with database access can see it.
INNER vs LEFT JOIN (in a self join)
- INNER returned only the matching ride pair (1 row).
- LEFT returned all 7 rows of the first copy; only the matching row had data from the second copy, the rest were NULL.
Transactional vs analytical systems
- Transactional (Amazon purchases, bank transactions): put constraints on so no junk or wrong data enters.
- Analytical / warehouse loading millions of rows: usually no constraints (each insert would be checked); validate data at the SQL level instead.