SQL•DDL & Schema
SQL DDL: CREATE TABLE, Constraints (PRIMARY KEY, NOT NULL)
Data Definition Language (DDL) creates and defines schema integrity rules in relational tables.
Syntax
CREATE TABLE name (id INT PRIMARY KEY, email TEXT UNIQUE NOT NULL);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| PRIMARY KEY | Constraint | Uniquely identifies each row; cannot contain NULL. |
| UNIQUE | Constraint | Ensures all values in a column are distinct. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
-- Schema definition with constraints
CREATE TABLE accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
balance REAL DEFAULT 0.0 CHECK(balance >= 0.0)
);
INSERT INTO accounts (username, balance) VALUES
('alice_dev', 500.00),
('bob_coder', 250.00);
SELECT * FROM accounts;Expected Output:
id username balance -- --------- ------- 1 alice_dev 500.0 2 bob_coder 250.0
How It Works: Step-by-Step
- Lines 2-6: Defines accounts table with PRIMARY KEY, NOT NULL, UNIQUE, and CHECK constraints.
- Lines 8-10: Inserts valid records complying with schema constraints.
Key Concepts
- Constraints enforce data integrity at the database engine level.
- CHECK constraints validate business rules (e.g. balance >= 0.0).
Common Mistake: Inserting duplicate values into a UNIQUE column
Violating a UNIQUE or PRIMARY KEY constraint aborts the query with a constraint violation error.
❌ Incorrect
INSERT INTO accounts (username) VALUES ('alice_dev'); // Error: UNIQUE constraint failed!✅ Correct
// Ensure username is unique before insertion
Related SQL Tutorials & Compiler
SQL Multirow Aggregate Metrics Calculation: COUNT, SUM, AVG, and GROUP BY
Calculate multirow aggregate metrics using COUNT, SUM, AVG, MIN, MAX, and partitioned GROUP BY filters with HAVING.
SQL Transactions: BEGIN, COMMIT, and ROLLBACK
Ensure ACID reliability using database transactions with BEGIN, COMMIT, and ROLLBACK.
SQL Window Functions: ROW_NUMBER, RANK, and OVER (PARTITION BY)
Compute running totals and row rankings across subsets using the OVER() clause.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.