SQLSQL
IntermediateLesson 8 of 15

CREATE TABLE, Data Types & Constraints – SQL

Defining tables and enforcing data quality through the schema.

With CREATE TABLE you define structure and rules. Constraints are the most important defense against corrupt data – it is better for the database to refuse bad values than to trust every application layer individually. The available ones are: PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT, CHECK, and FOREIGN KEY.

CREATE TABLE bewertungen (
  id          INTEGER PRIMARY KEY,
  kunde_id    INTEGER NOT NULL,
  produkt_id  INTEGER NOT NULL,
  sterne      INTEGER NOT NULL CHECK (sterne BETWEEN 1 AND 5),
  kommentar   TEXT,
  erstellt    TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE (kunde_id, produkt_id),                          -- only one review per product per customer
  FOREIGN KEY (kunde_id)   REFERENCES kunden(id)   ON DELETE CASCADE,
  FOREIGN KEY (produkt_id) REFERENCES produkte(id) ON DELETE RESTRICT
);

Data types vary by dialect. Rough mapping: integers INTEGER/BIGINT; exact decimals NUMERIC(10,2) (for money!); text TEXT or VARCHAR(n); date/time DATE, TIMESTAMP; booleans BOOLEAN (SQLite: 0/1). SQLite only has "type affinities" and checks types loosely; PostgreSQL and MySQL are strict.

-- Auto-increment per dialect
-- PostgreSQL:  id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY   (older: SERIAL)
-- MySQL:       id INT AUTO_INCREMENT PRIMARY KEY
-- SQLite:      id INTEGER PRIMARY KEY                                 (automatic)

ALTER TABLE produkte ADD COLUMN lagerbestand INTEGER NOT NULL DEFAULT 0;
ALTER TABLE produkte RENAME COLUMN kategorie TO warengruppe;    -- PostgreSQL, MySQL 8, SQLite 3.25+
DROP TABLE IF EXISTS bewertungen;
WarningNever store money in FLOAT/REAL: 0.1 + 0.2 gives 0.30000000000000004 in binary floating point. Use NUMERIC(12,2) or cents as an INTEGER.
TipON DELETE CASCADE also deletes dependent rows, RESTRICT/NO ACTION prevents the deletion, SET NULL writes NULL. Choose deliberately – cascade can delete an unexpectedly large amount of data.