SQL:SQL DDL: CREATE TABLE, Constraints (PRIMARY KEY, NOT NULL)
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:

ParameterTypeDescription
PRIMARY KEYConstraintUniquely identifies each row; cannot contain NULL.
UNIQUEConstraintEnsures all values in a column are distinct.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler