Kodewick
Start learning →
Constraints, indexes and views21 / 23

SQL Constraints, indexes and views

Lesson 21 of 23 · Part 5 · Changing data and tables · about 20 minutes

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.

ConstraintRuleWhen broken
PRIMARY KEYevery row has one, no duplicatesERROR 1062
FOREIGN KEYthe value must exist in another tableERROR 1452
NOT NULLa value is requiredERROR 1048 or 1364
UNIQUEno duplicates, but NULL is fineERROR 1062
CHECK (condition)the condition must holdERROR 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.

Choose one

When do constraints do their job?

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:

main.sql
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]');
Output
Query OK, 0 rows affected
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.

Choose oneA wrong guess is fine

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;

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:

main.sql
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]');
Output
Statement on line 1
Query OK, 0 rows affected
Statement on line 7
Query OK, 2 rows affected · Records: 2 Duplicates: 0 Warnings: 0
ERROR 1062 (23000): Duplicate entry '[email protected]' for key 'members.email'
members
  1. members · 3same as member 1: ERROR 1062
UNIQUE: the email column can't hold the same value twice, so row 3 is rejected

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 UNIQUE on several columns (email, phone number…).
  • A UNIQUE column can be NULL, even in many rows: as lesson 5 explained, NULL isn't equal to anything, so two NULLs don't count as duplicates.
main.sql
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;
Output
Statement on line 1
Query OK, 0 rows affected
Statement on line 6
Query OK, 2 rows affected · Records: 2 Duplicates: 0 Warnings: 0
Statement on line 8
idemail
1NULL
2NULL
2 rows

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.

Choose oneA wrong guess is fine

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:

main.sql
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);
Output
Statement on line 1
Query OK, 0 rows affected
Statement on line 6
Query OK, 1 row affected
Statement on line 7
idstars
15
1 row
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③.
  1. ①error number: a CHECK failed
  2. ②the constraint's name: CHECK no. 1 of the reviews table
  3. ③it was broken
Reading a CHECK error: 3819 means a check failed, and the quotes hold its name

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:

  • UPDATE has to pass the check too: changing the stars to 0 also gives ERROR 3819.
  • A condition that comes out NULL (say, the stars are missing) doesn't count as broken: CHECK only rejects rows where the condition is false. If the value mustn't be empty, add NOT NULL as well.

MySQL only enforces CHECK from version 8.0.16 on; older versions accept it but ignore it.

Fill inTap one to fill a blank; tap a blank to take it back

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;
Choose oneA wrong guess is fine

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);
Exercise 1

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.

It should print
3 rows
exercise1.sql
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;
Output
Press Run or Ctrl+Enter

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:

customers
idnamecity
1Ana SilvaLondon
2Ben OkaforParis
3Chloe MartinLondon
4David KimTokyo
5Emma NovakBerlin
6Farah KhanParis
  1. customers · 6no index: all 6 rows checked to find the 2 in London
CREATE INDEX idx_city ON customers (city)
idx_city
cityid
Berlin5
London1
London3
Paris2
Paris6
Tokyo4
rows in the table
idnamecity
1Ana SilvaLondon
3Chloe MartinLondon
No index: every row has to be checked; with an index sorted by city, it jumps straight to the London rows

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:

main.sql
1CREATE INDEX idx_city ON customers (city);2 3SELECT name, city FROM customers WHERE city = 'London';4 5DESCRIBE customers;
Output
Statement on line 1
Query OK, 0 rows affected · Records: 0 Duplicates: 0 Warnings: 0
Statement on line 3
namecity
Ana SilvaLondon
Chloe MartinLondon
Hana SatoLondon
3 rows
Statement on line 5
FieldTypeNullKeyDefaultExtra
idintNOPRINULL
namevarchar(40)NONULL
cityvarchar(30)YESMULNULL
joineddateYESNULL
emailvarchar(60)YESNULL
5 rows

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;.

Fill inTap one to fill a blank; tap a blank to take it back

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';
Choose one

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:

main.sql
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;
Output
Statement on line 1
Query OK, 0 rows affected
Statement on line 8
idnametotal
3Ana Silva76.00
7Ben Okafor61.90
8George Brown59.00
3 rows

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.
Choose oneA wrong guess is fine

What's the result?

1CREATE VIEW cheap AS2SELECT name, price FROM products WHERE price < 10;3 4SELECT COUNT(*) FROM cheap;
Exercise 2

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.

It should print
idorder_datename
72025-10-10Ben Okafor
92025-10-15Ana Silva
122025-10-25David Kim
3 rows
exercise2.sql
1SELECT * FROM pending_orders2ORDER BY id;
Output
Press Run or Ctrl+Enter

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:

main.sql
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;
Output
Statement on line 1
Query OK, 0 rows affected
Statement on line 4
namestock
Backpack15
Headphones10
Desk lamp0
3 rows
Statement on line 6
Query OK, 1 row affected · Rows matched: 1 Changed: 1 Warnings: 0
Statement on line 8
namestock
Backpack15
Desk lamp0
2 rows
low_stock
namestock
Backpack15
Headphones10
Desk lamp0
UPDATE products SET stock = 50 WHERE id = 5
products
idnamestock
3Backpack15
5Headphones50
6Desk lamp0
SELECT * FROM low_stock
queried again
namestock
Backpack15
Headphones50
Desk lamp0
  1. queried again · 250 < 20 is false
A view stores no data: after the restock, the headphones' stock is no longer below 20, so they drop out of the view on their own

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":

main.sql
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;
Output
Statement on line 1
Query OK, 0 rows affected
Statement on line 4
Query OK, 0 rows affected
Statement on line 6
idnamecategorypricestock
5HeadphonesElectronics59.0010
1 row
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.

Choose oneA wrong guess is fine

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;
Exercise 3

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.

It should print
cityn
London3
Berlin2
Sydney2
Tokyo2
Paris1
5 rows
exercise3.sql
1SELECT * FROM city_counts2ORDER BY n DESC, city;
Output
Press Run or Ctrl+Enter

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 (writing NULL gives 1048, leaving the column out with no default gives 1364).
  • UNIQUE: no duplicates (ERROR 1062), though many NULLs 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 in WHERE and JOIN.
  • 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 VIEW removes it.
Finished lesson 21?Lesson 21 of 23 · progress stays in this browser
Next · lesson 22 · 15 minTransactionsLearn SQL transactions: START TRANSACTION, COMMIT and ROLLBACK tie changes together so all of them happen or none do, as orders and transfers need.Next lesson →
The button marks this lesson done and opens the next.