Skip to content
SQLite

Create Table

Define tables with constraints and autoincrement keys.

#create#table#schema

Code

sqlite
-- Create tables with primary and foreign keys
CREATE TABLE users (
  id       INTEGER PRIMARY KEY AUTOINCREMENT,
  username TEXT    NOT NULL UNIQUE,
  email    TEXT    NOT NULL,
  created  TEXT    DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE posts (
  id         INTEGER PRIMARY KEY,
  user_id    INTEGER NOT NULL,
  title      TEXT    NOT NULL,
  body       TEXT,
  published  INTEGER DEFAULT 0,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- Enable foreign keys (off by default in CLI)
PRAGMA foreign_keys = ON;

-- Inspect schema
.schema users
.schema
.tables