CREATE TABLE with constraints
ShopKart wants product reviews. Rules: ratings 1–5, the product and customer must exist, and one review per product per customer.
CREATE TABLE reviews (
review_id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- auto-numbered
product_id INT NOT NULL REFERENCES products (product_id),
customer_id INT NOT NULL REFERENCES customers (customer_id),
rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),
comment TEXT,
created_at TIMESTAMP NOT NULL DEFAULT now(),
UNIQUE (product_id, customer_id) -- one review per product per customer
);| Constraint | Guarantees |
|---|---|
| PRIMARY KEY | Unique + not NULL; identifies the row |
| FOREIGN KEY / REFERENCES | The value exists in the other table |
| UNIQUE | No duplicates (NULLs allowed) |
| NOT NULL | A value is required |
| CHECK | A condition is true (rating BETWEEN 1 AND 5) |
| DEFAULT | Value used when none is given |
| GENERATED … AS IDENTITY | Auto-incrementing number (SERIAL in older PostgreSQL) |
| Common types | Use for |
|---|---|
| INT / BIGINT | Whole numbers, ids (BIGINT for big tables) |
| NUMERIC(10, 2) | Money: exact decimals (never FLOAT for money) |
| TEXT / VARCHAR(n) | Text |
| DATE, TIMESTAMP | Dates; date and time (TIMESTAMPTZ with time zone) |
| BOOLEAN | true / false |
INSERT, and constraints doing their job
INSERT INTO reviews (product_id, customer_id, rating, comment) VALUES
(1, 1, 5, 'Great sound'),
(3, 2, 4, 'Battery could be better'),
(2, 6, 3, NULL);INSERT INTO reviews (product_id, customer_id, rating) VALUES (1, 2, 9);INSERT INTO reviews (product_id, customer_id, rating) VALUES (99, 2, 4);INSERT INTO reviews (product_id, customer_id, rating) VALUES (1, 1, 2);Three bad rows, three clear errors, and nothing bad saved. This is exactly what protects tables from buggy pipelines.
UPDATE and DELETE (with RETURNING)
UPDATE reviews
SET rating = 5, comment = 'Battery is fine after update'
WHERE product_id = 3 AND customer_id = 2
RETURNING review_id, rating, comment;| review_id | rating | comment |
|---|---|---|
| 2 | 5 | Battery is fine after update |
DELETE FROM reviews
WHERE comment IS NULL
RETURNING review_id, product_id;| review_id | product_id |
|---|---|
| 3 | 2 |
MERGE: the upsert
A supplier sends a price file: one existing product with a new price and one brand-new product.
CREATE TABLE price_updates (product_id INT, name TEXT, category TEXT, price NUMERIC(10, 2));
INSERT INTO price_updates VALUES
(2, 'Phone Case', 'Accessories', 249), -- existing product: new price
(7, 'USB-C Cable', 'Accessories', 199); -- new productMERGE INTO products AS t
USING price_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET price = s.price
WHEN NOT MATCHED THEN
INSERT (product_id, name, category, price) VALUES (s.product_id, s.name, s.category, s.price)
RETURNING merge_action(), t.product_id, t.name, t.price;| merge_action | product_id | name | price |
|---|---|---|---|
| UPDATE | 2 | Phone Case | 249.00 |
| INSERT | 7 | USB-C Cable | 199.00 |
One statement: matched → update, not matched → insert. MERGE is standard SQL and works in PostgreSQL 15+, SQL Server, Oracle, Snowflake and Databricks (it's the heart of the Delta Lake lesson in our Databricks course). merge_action() is a PostgreSQL 17+ extra that reports what happened to each row.
-- PostgreSQL's older upsert syntax (MySQL has a similar ON DUPLICATE KEY UPDATE)
INSERT INTO products (product_id, name, category, price)
VALUES (7, 'USB-C Cable', 'Accessories', 179)
ON CONFLICT (product_id) DO UPDATE SET price = EXCLUDED.price
RETURNING product_id, name, price;| product_id | name | price |
|---|---|---|
| 7 | USB-C Cable | 179.00 |
Transactions: all or nothing
BEGIN;
UPDATE products SET price = 1; -- disaster: every price is now 1
ROLLBACK; -- undo everything since BEGIN
SELECT name, price FROM products WHERE product_id IN (1, 3);| name | price |
|---|---|
| Headphones | 1999.00 |
| Smartwatch | 4999.00 |
Prices are back to normal: ROLLBACK undid the update. (Fun fact from testing: our first version set prices to 0, and the CHECK constraint price > 0 refused it before we even needed the rollback.) In a bank transfer, “take money from A” and “give money to B” go in one transaction, so a crash can never do only half.
| ACID | Meaning | Example |
|---|---|---|
| Atomicity | All statements or none | Transfer: debit and credit together |
| Consistency | Constraints always hold | No rating of 9 |
| Isolation | Others don't see half-done work | A report doesn't see the debit without the credit |
| Durability | COMMIT survives crashes | Written to the log on disk |
Isolation levels (from weakest): READ UNCOMMITTED, READ COMMITTED (PostgreSQL's default), REPEATABLE READ, SERIALIZABLE. Stronger levels prevent more anomalies (dirty reads, non-repeatable reads, phantom rows) at some cost in concurrency.
Views and materialized views
CREATE VIEW order_totals AS
SELECT o.order_id, o.customer_id, o.order_date, o.status,
SUM(oi.quantity * oi.unit_price) AS total
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id;SELECT order_id, status, total
FROM order_totals
WHERE total > 5000
ORDER BY total DESC;| order_id | status | total |
|---|---|---|
| 115 | DELIVERED | 6298.00 |
| 108 | DELIVERED | 5298.00 |
CREATE MATERIALIZED VIEW monthly_revenue AS
SELECT DATE_TRUNC('month', order_date)::date AS month, SUM(total) AS revenue
FROM order_totals
WHERE status = 'DELIVERED'
GROUP BY 1;
REFRESH MATERIALIZED VIEW monthly_revenue; -- re-run the query to update stored rows| View | Materialized view | |
|---|---|---|
| Stores data | No, runs the query each time | Yes, stores the result |
| Freshness | Always current | As of the last REFRESH |
| Speed | As fast as the query | Fast reads |
| Use for | Simplify and secure access | Expensive dashboard queries |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What are ACID properties?Fresher+
Q2View vs table vs materialized view?Fresher+
Q3How do you implement an upsert?1–3 yrs+
Q4What isolation levels exist and what do they prevent?1–3 yrs+
Q5Why might a pipeline load data with constraints disabled, and what's the risk?3+ yrs+
Key takeaways
- ✓Constraints are the database's guard against bad data.
- ✓MERGE is the standard upsert and the core of incremental loads.
- ✓Transactions make multi-step changes safe.
- ✓Next: why queries are slow, and how indexes fix them.
Frequently asked questions
What is an upsert?
Update the row if it exists, insert it if it doesn't, in one statement. Standard SQL does this with MERGE; PostgreSQL also has INSERT ... ON CONFLICT DO UPDATE, MySQL has ON DUPLICATE KEY UPDATE.
What is a transaction?
A group of statements that succeed or fail together. BEGIN starts it, COMMIT saves everything, ROLLBACK undoes everything since BEGIN.
What are ACID properties?
Atomicity (all or nothing), Consistency (rules like constraints always hold), Isolation (concurrent transactions don't see each other's half-done work), Durability (committed data survives crashes).
View vs materialized view?
A view is a saved query that runs every time you select from it, so it's always fresh. A materialized view stores the result and must be refreshed, so it's fast but can be stale.
Why use constraints if the app already validates data?
Data arrives from many places: pipelines, scripts, other apps, manual fixes. Constraints in the database are the last line of defence that nothing can bypass.
🧠 Quick check: changing data safely
1. INSERT a rating of 9 when CHECK (rating BETWEEN 1 AND 5) exists...
2. You run UPDATE without WHERE. What happens?
3. BEGIN; UPDATE …; ROLLBACK; leaves the data...
4. MERGE is used for...
Checking your access…