Sub topic 2
Identifying Rows with PRIMARY KEY
This chapter assumes you know basic SQL statements (SELECT, INSERT, UPDATE, DELETE), tables, rows, and common data types such as integers and text. Examples use PostgreSQL syntax. Notes near the end cover MySQL and SQL Server.
Defining a primary key
A primary key is the column, or set of columns, that uniquely identifies each row. Its values must be unique and cannot be NULL.
A composite primary key uses several columns together. Each combination of values must appear only once:
CREATE TABLE enrollments (
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
PRIMARY KEY (student_id, course_id)
);Generating key values automatically
An identity column is a column the database fills with a new number on each insert. In PostgreSQL, GENERATED ALWAYS AS IDENTITY creates one.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL
);
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ada Lovelace');Preventing duplicates with UNIQUE
A UNIQUE constraint rejects a second row with the same value. Unlike a primary key, a UNIQUE column can allow NULL in most systems, and a table can have several UNIQUE columns. The customers table above already uses UNIQUE on email. Inserting the same address again fails:
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Another Ada');
-- ERROR: duplicate key value violates unique constraintLinking tables with FOREIGN KEY
A foreign key requires a value to exist in another table's key column. This is called referential integrity. The following table refers to customers:
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
total_amount NUMERIC(10, 2) NOT NULL
);Choosing ON DELETE and ON UPDATE behavior
A referential action decides what happens to child rows when the parent row changes. ON DELETE RESTRICT (or the default, NO ACTION) rejects the delete. ON DELETE CASCADE deletes the child rows too. ON UPDATE CASCADE copies a changed key value to child rows.
INSERT INTO orders (customer_id, total_amount) VALUES (1, 25.00);
DELETE FROM customers WHERE customer_id = 1;
-- ERROR: update or delete violates foreign key constraint> Note: Identity keys rarely change, so ON UPDATE CASCADE is seldom needed. Choose ON DELETE based on whether child rows should survive their parent.
MySQL uses AUTO_INCREMENT in place of the identity clause. SQL Server uses IDENTITY(1,1).
Exercise
A customers row has child orders rows that reference it with ON DELETE CASCADE. What happens to those orders when you delete the customer?
Show answer
The database deletes those orders automatically. With RESTRICT, the same delete would fail instead.