Row Removal, Saved Queries and Pairing Every Row in SQL
SQL & DataModel answerLast updated
Explain how DELETE and TRUNCATE differ, when a view beats a stored table, and how a CROSS JOIN builds full combination grids, using a small employee and department schema.
You are working with two small tables in a relational database.
employees
| id | name | dept_id |
|---|---|---|
| 1 | Alice | 10 |
| 2 | Bob | 20 |
| 3 | Carol | 10 |
| 4 | Dave | 30 |
departments
| dept_id | dept_name |
|---|---|
| 10 | Sales |
| 20 | Marketing |
| 30 | Engineering |
Answer the three conceptual questions below as you would in a technical discussion with a data team. Use the tables above for examples where it helps.
- Removing data. How do
DELETEandTRUNCATEdiffer? Consider logging, speed, filtering, triggers, foreign keys, identity counters, rollback and locking. When would you choose each one? - Saved query vs stored data. How does a view differ from a physical table? Give the advantages and drawbacks of each, and say where a materialized view fits.
- Pairing every row. What does a
CROSS JOINdo? Describe a realistic analytics scenario that needs it, and explain what to watch out for regarding result size.
Where behavior differs between database engines (SQL Server, PostgreSQL, MySQL, Oracle, Redshift), point that out rather than giving one universal answer.
Hints
Hint 1
For the first question, think about what the engine records and locks: row-by-row logging versus releasing whole storage pages, and what that means for WHERE clauses, triggers, foreign keys and auto-increment counters.
Hint 2
For the second question, ask when the work happens. A view runs its query every time it is read; a table pays the cost once at load time. Then consider freshness, indexing, storage, security and updatability.
Hint 3
For the third question, compute the output size as rows in A times rows in B using the sample tables, then think about a case where you need every combination to exist even when no source data exists for it, such as a date by product grid with zero-sales days.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
A good answer covers mechanics, consequences, judgment and engine differences. Many of the behaviors below vary by database, and saying so explicitly is part of a strong answer.
1. DELETE vs TRUNCATE
| Aspect | DELETE | TRUNCATE |
|---|---|---|
| Category | DML | DDL in most engines |
| Filtering | Supports WHERE | Whole table only |
| Mechanism | Removes rows one by one, logging each | Releases data pages, minimal logging |
| Speed | O(rows deleted) | Close to constant time |
| Triggers | Row-level delete triggers fire | They do not fire |
| Foreign keys | Checked per row, can cascade | Usually refused if the table is referenced (Postgres needs CASCADE) |
| Identity counter | Unchanged | Reset in SQL Server and MySQL; Postgres only with RESTART IDENTITY |
| Rollback | Yes inside a transaction | Yes in SQL Server and Postgres; implicit commit in Oracle, MySQL and Redshift |
| Locks | Row or page locks | Table-level lock |
| Privilege | DELETE | Stronger (TRUNCATE or ALTER) |
Choosing:
- Use
DELETEfor a subset, for exampleDELETE FROM employees WHERE dept_id = 30;, or when triggers, auditing or dependable rollback on every engine matter. - Use
TRUNCATEto empty a whole table fast, typically a staging table in a nightly load: truncate, then reload. - In Redshift,
DELETEonly marks rows as removed and space returns afterVACUUM, whileTRUNCATEfrees it immediately. Because it commits implicitly, never rely on rolling it back there. DROPis different again: it removes the table definition, whereasTRUNCATEkeeps schema, indexes and grants.
2. View vs table
A table stores rows physically. A view is a saved SELECT with no data of its own; each read re-executes the query against the base tables.
CREATE VIEW v_employee_dept AS
SELECT e.id, e.name, d.dept_name
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id;
View advantages
- Always reflects current data, with no refresh job.
- Centralizes join logic and business definitions in one place.
- Works as a security layer by exposing chosen columns or rows without granting base-table access.
- Costs almost no storage.
View drawbacks
- The cost is paid on every read, and stacked views compound it.
- Typically cannot be indexed.
- Updates through a view generally work only for simple single-table views.
- It can break if base columns are renamed or dropped.
Table advantages
- Fast reads, indexes, partitioning.
- Can hold historical snapshots that must not change when sources change.
Table drawbacks
- Storage cost.
- Goes stale without ETL refresh.
- Logic gets duplicated across pipelines.
Middle ground: a materialized view stores the result and is refreshed on demand or on a schedule (Redshift can auto-refresh). It suits expensive aggregates behind dashboards where a little staleness is acceptable.
Rule of thumb: views for abstraction, security and light logic; tables or materialized views for heavy, frequently read aggregates.
3. CROSS JOIN
A CROSS JOIN returns the Cartesian product, pairing each row of one input with every row of the other, with no join condition. The output has |A| x |B| rows. With the sample data that is 4 x 3 = 12 rows.
SELECT e.name, d.dept_name
FROM employees e
CROSS JOIN departments d;
Realistic use: a complete reporting grid. If you aggregate only the sales table, days with no sales for a product simply vanish, which skews averages and charts. Build every date and product combination first, then left join the facts.
SELECT c.cal_date, p.product_id,
COALESCE(SUM(s.amount), 0) AS sales
FROM calendar c
CROSS JOIN products p
LEFT JOIN sales s
ON s.sale_date = c.cal_date
AND s.product_id = p.product_id
WHERE c.cal_date BETWEEN '2024-01-01' AND '2024-01-31'
GROUP BY c.cal_date, p.product_id;
Other uses: all size and color SKU combinations, store by week planning grids, and attaching a single-row totals or parameter table to every row to compute a percent of total.
Size caution
- 10,000 products x 365 days is about 3.65M rows, which is fine.
- 1M x 1M is 10^12 rows, which is unusable.
- Filter both inputs first and estimate the row count before running.
- A forgotten join condition (
FROM a, bwith noWHERE) is an accidental cross join and a classic cause of inflated metrics. - If either side is empty, the result is empty, which can silently wipe out a scaffold.
Complexity summary
DELETE: O(n) time and log space for n removed rows.TRUNCATE: roughly O(1), since only page deallocation is recorded.- View: the full cost of the underlying query on each access, no storage.
CROSS JOIN: O(|A| x |B|) time and output.
Common mistakes
- Saying
TRUNCATEcan never be rolled back. It can in SQL Server and Postgres. - Saying
TRUNCATEalways resets identity. Postgres does not by default. - Truncating a table that other tables reference by foreign key.
- Assuming a regular view caches results. Only materialized views do.
- Running a cross join on unfiltered large tables.
Optional demo (Python and SQLite)
SQLite has no TRUNCATE, but an unfiltered DELETE triggers an internal truncate optimization. You can create the two tables, build the view, and run the cross join to confirm 12 rows, then delete all employees and confirm the view returns nothing while still existing.