Sub topic 2
Data Types and the Meaning of NULL
This chapter assumes you know what tables, rows, and columns are, can read short SQL statements, and have seen a key column in a spreadsheet or database. It builds on the tables from the previous chapter.
Data types
A data type is the kind of value a column holds, such as whole numbers, text, dates, or decimal amounts. The type controls what the database accepts, how it sorts values, and how much storage each value uses. An INTEGER column rejects 'abc', and a DATE column sorts dates by calendar order rather than as text.
NULL marks a missing value
NULL marks a value that is missing or unknown. It differs from zero and from an empty string. Any comparison with NULL, including NULL = NULL, returns unknown, so you must test for it with IS NULL.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
phone VARCHAR(20)
);
INSERT INTO customers (customer_id, name, phone)
VALUES (1, 'Ada Lovelace', NULL);
SELECT name
FROM customers
WHERE phone IS NULL;Primary keys identify each row
A primary key is a column, or a set of columns, whose values identify each row uniquely. The database rejects NULL and repeated values in a primary key, so two customers cannot both have customer_id 1. Names make poor keys because two people can share one.
Foreign keys link tables
A foreign key is a column that stores a primary key value from another table. It records which row a row relates to. For example, each order stores the customer_id of the customer who placed it.
One-to-many and many-to-many relationships
In a one-to-many relationship, one customer has many orders, so the orders table holds a customer_id foreign key. A many-to-many relationship, such as orders and products, needs a junction table that holds two foreign keys.
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL
);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
product_id INTEGER NOT NULL REFERENCES products (product_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id)
);Constraints protect data integrity
Constraints are rules the database checks on every insert and update. NOT NULL requires a value, UNIQUE blocks duplicates, CHECK tests a condition, and REFERENCES rejects a foreign key that points to a missing row.
Exercise
Exercise
Why does WHERE phone = NULL return no rows even when some phone values are missing?
Show answer
NULL is not equal to anything, including NULL, so the comparison evaluates to unknown and no row matches. Use WHERE phone IS NULL instead.