SQL Constraints, indexes and views
Constraints are a table's rules, and a statement that breaks one is rejected (NOT NULL, UNIQUE, CHECK); an index works like the index at the back of a book, so WHERE and JOIN find rows faster; a view is a saved query you can query like a table.
The PRIMARY KEY, NOT NULL and FOREIGN KEY you wrote in lesson 20 are all rules for a table; SQL calls them constraints. Whenever data is inserted or changed, the database checks them, and if a rule is broken, the whole statement is rejected and the table stays as it was.
| Constraint | Rule | When broken |
|---|---|---|
PRIMARY KEY | every row has one, no duplicates | ERROR 1062 |
FOREIGN KEY | the value must exist in another table | ERROR 1452 |
NOT NULL | a value is required | ERROR 1048 or 1364 |
UNIQUE | no duplicates, but NULL is fine | ERROR 1062 |
CHECK (condition) | the condition must hold | ERROR 3819 |
Lesson 20 covered the first two. This lesson starts with the other three, then looks at two things that make tables nicer to work with: indexes make lookups faster, and views save queries you use all the time.
When do constraints do their job?
INSERT and UPDATE, and a statement that breaks one fails with an error and changes nothing. They play no part in queries.NOT NULL: a value is required
This step shows the two errors NOT NULL can give. You met one in lesson 20: writing NULL into a NOT NULL column gives ERROR 1048. The other is even more common: the insert leaves the column out entirely, and it has no default:
1CREATE TABLE members (2 id INT PRIMARY KEY,3 name VARCHAR(20) NOT NULL,4 email VARCHAR(50)5);6 7INSERT INTO members (id, email) VALUES (1, '[email protected]');
ERROR 1364 (HY000): Field 'name' doesn't have a default value
ERROR 1364: name got no value and has no default to fall back on. A column without NOT NULL (like email) can be left out, and it becomes NULL; a NOT NULL column has to be given every time, or get a DEFAULT.
What happens when you run this?
1CREATE TABLE members (2 id INT PRIMARY KEY,3 name VARCHAR(20) NOT NULL,4 email VARCHAR(50)5);6INSERT INTO members (id, name) VALUES (1, 'Ana');7SELECT * FROM members;
name is NOT NULL, and it's given. email has no such rule, so leaving it out just makes it NULL; no error.UNIQUE: no duplicates
This step is about UNIQUE. Two members shouldn't share an email address, but the email isn't the primary key (that's id). Add UNIQUE to the column and its values can't repeat:
1CREATE TABLE members (2 id INT PRIMARY KEY,3 name VARCHAR(20) NOT NULL,4 email VARCHAR(50) UNIQUE5);6 7INSERT INTO members (id, name, email)8VALUES (1, 'Ana', '[email protected]'),9 (2, 'Ben', '[email protected]');10 11INSERT INTO members (id, name, email)12VALUES (3, 'Chloe', '[email protected]');
ERROR 1062 (23000): Duplicate entry '[email protected]' for key 'members.email'
| id | name | |
|---|---|---|
| 1 | Ana | [email protected] |
| 2 | Ben | [email protected] |
| 3 | Chloe | [email protected] |
members · 3same as member 1: ERROR 1062
The error is ERROR 1062, the same as a duplicate primary key. It goes on to say the duplicate value is '[email protected]' and the rule it ran into is members.email.
UNIQUE differs from a primary key in two ways:
- A table has only one primary key, but you can put
UNIQUEon several columns (email, phone number…). - A
UNIQUEcolumn can beNULL, even in many rows: as lesson 5 explained,NULLisn't equal to anything, so twoNULLs don't count as duplicates.
1CREATE TABLE members (2 id INT PRIMARY KEY,3 email VARCHAR(50) UNIQUE4);5 6INSERT INTO members (id, email) VALUES (1, NULL), (2, NULL);7 8SELECT * FROM members;
| id | |
|---|---|
| 1 | NULL |
| 2 | NULL |
You can add it to an existing table too: ALTER TABLE customers ADD UNIQUE (email);. But if the table already contains duplicates, it won't work.
Let's give the shop's customers table a new rule: no two customers in the same city. What happens?
1ALTER TABLE customers ADD UNIQUE (city);CHECK: test the value
This step is about CHECK: you write a condition, and every row has to meet it. A review can only have 1 to 5 stars:
1CREATE TABLE reviews (2 id INT PRIMARY KEY,3 stars INT CHECK (stars BETWEEN 1 AND 5)4);5 6INSERT INTO reviews (id, stars) VALUES (1, 5);7SELECT * FROM reviews;8 9INSERT INTO reviews (id, stars) VALUES (2, 6);
| id | stars |
|---|---|
| 1 | 5 |
ERROR 3819 (HY000): Check constraint 'reviews_chk_1' is violated.
The 5-star review goes in; 6 stars fails the condition and is rejected:
ERROR 3819① (HY000): Check constraint 'reviews_chk_1'② is violated③.- ①error number: a CHECK failed
- ②the constraint's name: CHECK no. 1 of the reviews table
- ③it was broken
The database made up that name. For friendlier errors, name it yourself: with CONSTRAINT stars_ok CHECK (stars BETWEEN 1 AND 5) the error says 'stars_ok'.
Two more things:
UPDATEhas to pass the check too: changing the stars to 0 also givesERROR 3819.- A condition that comes out
NULL(say, the stars are missing) doesn't count as broken:CHECKonly rejects rows where the condition is false. If the value mustn't be empty, addNOT NULLas well.
MySQL only enforces CHECK from version 8.0.16 on; older versions accept it but ignore it.
Fill in the blank so the price has to be greater than 0.
1CREATE TABLE prices (2 id INT PRIMARY KEY,3 price DECIMAL(6, 2) (price > 0)4);5 6INSERT INTO prices (id, price) VALUES (1, 9.90), (2, 25.00);7 8SELECT * FROM prices;
CHECK (condition). WHERE picks rows in a query and can't go in a table definition; UNIQUE isn't followed by a condition.Three rows are inserted at once, and the middle one has 0 stars. How many rows does the table have afterwards?
1CREATE TABLE reviews (2 id INT PRIMARY KEY,3 stars INT CHECK (stars BETWEEN 1 AND 5)4);5INSERT INTO reviews (id, stars) VALUES (1, 5), (2, 0), (3, 4);
INSERT is all or nothing: if any row breaks a constraint, the whole statement fails with ERROR 3819, and the rows already checked are undone too. Not a single row goes in.Typos in the member list
✓The members table has two rules: no two members share an email, and the level must be 1 to 3. Whoever typed in the data made two mistakes: Ben is a level 3 member, and Chloe's email is [email protected]. Fix the data so all three rows go in. Don't change the table's rules.
| id | name | level | |
|---|---|---|---|
| 1 | Ana | [email protected] | 1 |
| 2 | Ben | [email protected] | 3 |
| 3 | Chloe | [email protected] | 2 |
1CREATE TABLE members (2 id INT PRIMARY KEY,3 name VARCHAR(20) NOT NULL,4 email VARCHAR(50) UNIQUE,5 level INT CHECK (level BETWEEN 1 AND 3)6);7 8INSERT INTO members (id, name, email, level)9VALUES (1, 'Ana', '[email protected]', 1),10 (2, 'Ben', '[email protected]', 4),11 (3, 'Chloe', '[email protected]', 2);12 13SELECT * FROM members;
Indexes: like the index of a book
This step is about indexes. To find where a thick book talks about "pointers", you could leaf through it from the first page to the last, or turn to the index at the back: the words are in order, each with its page numbers, and you're there in a moment.
Databases work the same way. Without an index, WHERE city = 'London' has to look at every single row. Give city an index and the database keeps a separate list sorted by city, noting which rows have each city, so it can jump straight to them:
| id | name | city |
|---|---|---|
| 1 | Ana Silva | London |
| 2 | Ben Okafor | Paris |
| 3 | Chloe Martin | London |
| 4 | David Kim | Tokyo |
| 5 | Emma Novak | Berlin |
| 6 | Farah Khan | Paris |
customers · 6no index: all 6 rows checked to find the 2 in London
CREATE INDEX idx_city ON customers (city)| city | id |
|---|---|
| Berlin | 5 |
| London | 1 |
| London | 3 |
| Paris | 2 |
| Paris | 6 |
| Tokyo | 4 |
| id | name | city |
|---|---|---|
| 1 | Ana Silva | London |
| 3 | Chloe Martin | London |
To create an index, write CREATE INDEX index_name ON table (column). You choose the name; idx_ plus the column name is the usual habit:
1CREATE INDEX idx_city ON customers (city);2 3SELECT name, city FROM customers WHERE city = 'London';4 5DESCRIBE customers;
| name | city |
|---|---|
| Ana Silva | London |
| Chloe Martin | London |
| Hana Sato | London |
| Field | Type | Null | Key | Default | Extra |
|---|---|---|---|---|---|
| id | int | NO | PRI | NULL | |
| name | varchar(40) | NO | NULL | ||
| city | varchar(30) | YES | MUL | NULL | |
| joined | date | YES | NULL | ||
| varchar(60) | YES | NULL |
The result is exactly the same as without the index: an index only makes finding rows faster, it never changes the result, and you don't change your queries. In DESCRIBE, the Key of city is now MUL, meaning the column has an index whose values may repeat (UNI is a UNIQUE index, PRI the primary key).
Our shop has only a few dozen rows, so with or without an index it's over in a blink; with millions of rows, the difference can be milliseconds versus several seconds. Indexes have a cost, though:
- They take space: that sorted list is stored separately.
- Writes get a little slower: every insert, update and delete has to update the list too.
So you don't index every column. The ones worth it are those you search by often: columns that show up in WHERE, JOIN … ON and ORDER BY. The primary key comes with an index, UNIQUE creates one automatically, and MySQL also indexes foreign key columns for you (in DESCRIBE orders, customer_id is MUL too). Remove an index you don't need with DROP INDEX idx_city ON customers;.
The shop often looks up pending orders. Fill in the two blanks to index the orders' status.
1CREATE idx_status orders (status);2 3SELECT id, order_date4FROM orders5WHERE status = 'pending';
CREATE INDEX index_name ON table (column). Once it exists, you write your queries as usual, and the result is the same.Which column is most worth indexing?
Views: saved queries
This step is about views. Some queries you need every day, and retyping a long chain of JOINs and GROUP BY each time is a chore. CREATE VIEW view_name AS query saves the query under a name:
1CREATE VIEW order_totals AS2SELECT o.id, c.name, SUM(i.quantity * i.unit_price) AS total3FROM orders AS o4JOIN customers AS c ON c.id = o.customer_id5JOIN order_items AS i ON i.order_id = o.id6GROUP BY o.id, c.name;7 8SELECT * FROM order_totals9WHERE total > 5010ORDER BY total DESC;
| id | name | total |
|---|---|---|
| 3 | Ana Silva | 76.00 |
| 7 | Ben Okafor | 61.90 |
| 8 | George Brown | 59.00 |
From now on you can query order_totals just like a table, with WHERE, ORDER BY or JOIN. But it isn't a real table: it stores no data, only the query, and every time you query it, the database runs that query again. That's why a view is also called a virtual table.
- A view can't have the same name as an existing table (that gives
ERROR 1050). - In real MySQL some views can even be used to change data; this course's engine only supports querying through a view, so change the data in its tables directly.
What's the result?
1CREATE VIEW cheap AS2SELECT name, price FROM products WHERE price < 10;3 4SELECT COUNT(*) FROM cheap;
FROM just like a table.Pending orders
✓Every day, the warehouse wants to see which orders haven't shipped yet. Create a view pending_orders with the id and order_date of every order whose status is pending, plus the name of the customer who placed it. You don't need to change the final query.
| id | order_date | name |
|---|---|---|
| 7 | 2025-10-10 | Ben Okafor |
| 9 | 2025-10-15 | Ana Silva |
| 12 | 2025-10-25 | David Kim |
1SELECT * FROM pending_orders2ORDER BY id;
When the data changes, so does the view
This step looks at how views and data relate. A view stores no data and reruns its query every time, so as soon as the data in a table changes, the view shows the new data. Create a "low stock" view, then restock the headphones:
1CREATE VIEW low_stock AS2SELECT name, stock FROM products WHERE stock < 20;3 4SELECT * FROM low_stock;5 6UPDATE products SET stock = 50 WHERE id = 5;7 8SELECT * FROM low_stock;
| name | stock |
|---|---|
| Backpack | 15 |
| Headphones | 10 |
| Desk lamp | 0 |
| name | stock |
|---|---|
| Backpack | 15 |
| Desk lamp | 0 |
| name | stock |
|---|---|
| Backpack | 15 |
| Headphones | 10 |
| Desk lamp | 0 |
UPDATE products SET stock = 50 WHERE id = 5| id | name | stock |
|---|---|---|
| 3 | Backpack | 15 |
| 5 | Headphones | 50 |
| 6 | Desk lamp | 0 |
SELECT * FROM low_stock| name | stock |
|---|---|
| Backpack | 15 |
| Headphones | 50 |
| Desk lamp | 0 |
queried again · 250 < 20 is false
To change a view's query, use CREATE OR REPLACE VIEW view_name AS new_query. When you no longer need it, DROP VIEW view_name removes just the saved query; the tables and their data stay put. Query it after that and the table "doesn't exist":
1CREATE VIEW low_stock AS2SELECT name, stock FROM products WHERE stock < 20;3 4DROP VIEW low_stock;5 6SELECT * FROM products WHERE id = 5;7 8SELECT * FROM low_stock;
| id | name | category | price | stock |
|---|---|---|---|---|
| 5 | Headphones | Electronics | 59.00 | 10 |
ERROR 1146 (42S02): Table 'town.low_stock' doesn't exist
The other way round: if a table the view uses is dropped, the view is still there, but querying it gives ERROR 1356, because the saved query can't run anymore.
The notebook's price goes up to 12. What does the view give now?
1CREATE VIEW cheap AS2SELECT name, price FROM products WHERE price < 10;3 4UPDATE products SET price = 12.00 WHERE id = 1;5 6SELECT COUNT(*) FROM cheap;
price < 10, so only 3 are left.Customers per city
✓Create a view city_counts with how many customers each city has: two columns, city and n. Then customer 2 moves to Sydney: change their city with UPDATE. You don't need to change the final query; see whether the view keeps up.
| city | n |
|---|---|
| London | 3 |
| Berlin | 2 |
| Sydney | 2 |
| Tokyo | 2 |
| Paris | 1 |
1SELECT * FROM city_counts2ORDER BY n DESC, city;
What you learned
- Constraints are a table's rules, checked on every insert and update; a statement that breaks one is rejected as a whole.
NOT NULL: a value is required (writingNULLgives1048, leaving the column out with no default gives1364).UNIQUE: no duplicates (ERROR 1062), though manyNULLs are fine;CHECK (condition): the condition must hold (ERROR 3819).- An index (
CREATE INDEX name ON table (column)) works like a book's index: faster lookups, same results, but it takes space and slows writes a little; index columns you often use inWHEREandJOIN. - A view (
CREATE VIEW name AS query) is a saved query: you query it like a table, it stores no data, and it changes whenever the tables do;DROP VIEWremoves it.