Sub topic 1
Creating a Table with CREATE TABLE
Prerequisites
This chapter assumes you can write basic SQL (SELECT, INSERT, UPDATE, DELETE), understand tables, rows, and columns, and know common data types such as integers, text, and dates.
Creating a table
CREATE TABLE defines a new table: its name, its columns, and the rules for each column. Each column line has a name, a data type, and optional constraints.
CREATE TABLE customers (
customer_id INTEGER,
email VARCHAR(255),
full_name VARCHAR(100),
created_at TIMESTAMP
);Choosing data types for columns
The data type controls which values a column accepts and how the database stores them. Choose the narrowest type that fits the data.
INTEGERstores whole numbers, such as IDs and counts.VARCHAR(n)stores text up to n characters, such as names and emails.NUMERIC(p, s)stores exact decimals with p total digits and s after the decimal point. Use it for money instead of floating point types.TIMESTAMPstores a date and time.
What constraints do and why to use them
A constraint is a rule that the database enforces on every row. If the rule fails, the database rejects the statement. Checks in application code can be skipped or buggy, but a constraint in the table applies to every program that writes to it.
Common constraints include NOT NULL, DEFAULT, PRIMARY KEY, UNIQUE, FOREIGN KEY, and CHECK. This chapter covers NOT NULL and DEFAULT.
Requiring values with NOT NULL
NULL means that a value is missing. A NOT NULL constraint rejects any row where that column has no value.
CREATE TABLE customers (
customer_id INTEGER NOT NULL,
email VARCHAR(255) NOT NULL,
full_name VARCHAR(100)
);
-- Fails: email is missing, so the database rejects the row
INSERT INTO customers (customer_id, full_name)
VALUES (1, 'Ada Lovelace');The database returns an error that names the column, such as a "not-null constraint" violation. The exact wording depends on the database system.
Providing defaults with DEFAULT
DEFAULT supplies a value when an INSERT leaves a column out.
CREATE TABLE customers (
customer_id INTEGER NOT NULL,
email VARCHAR(255) NOT NULL,
full_name VARCHAR(100) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO customers (customer_id, email, full_name)
VALUES (2, '[email protected]', 'Grace Hopper');
-- status is 'new' and created_at is the current timeExercise
Given the customers table with email NOT NULL and status DEFAULT 'new', does this statement succeed? INSERT INTO customers (customerid, fullname) VALUES (3, 'Alan Turing');
Show answer
No. The email column is NOT NULL and the INSERT does not supply it. The DEFAULT for status fills in 'new', but that does not satisfy the email rule.