SQL DDL and DML

Create and change schema objects, then insert, update, delete, merge, and manage transactional data changes.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## CREATE, ALTER, and DROP
Create table
CREATE TABLE users (
  user_id INTEGER PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  created_at TIMESTAMP NOT NULL
);

# Define a new table with columns and constraints.

Add a column
ALTER TABLE users
ADD COLUMN last_login_at TIMESTAMP;

# Modify an existing table by adding a new column.

Add a constraint
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers(customer_id);

# Attach a foreign key or check constraint after table creation.

Drop table
DROP TABLE old_logs;

# Remove a table definition and its data.

Truncate table
TRUNCATE TABLE staging_events;

# Remove all rows quickly without dropping the table.

## Constraints and Indexes
Define primary key
CREATE TABLE departments (
  department_id INTEGER PRIMARY KEY,
  name VARCHAR(100) NOT NULL
);

# Mark a column as the main row identifier.

Define unique constraint
ALTER TABLE users
ADD CONSTRAINT uq_users_email UNIQUE (email);

# Ensure a column or column set stays unique.

Add check constraint
ALTER TABLE products
ADD CONSTRAINT chk_price_positive CHECK (price >= 0);

# Restrict column values with a boolean rule.

Create index
CREATE INDEX idx_orders_customer_id
ON orders (customer_id);

# Add an index to improve lookup performance.

Create composite index
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at);

# Index multiple columns together.

## INSERT, UPDATE, and DELETE
Insert one row
INSERT INTO users (user_id, email, created_at)
VALUES (1, 'a@example.com', CURRENT_TIMESTAMP);

# Add a single row to a table.

Insert multiple rows
INSERT INTO roles (role_id, role_name)
VALUES
  (1, 'admin'),
  (2, 'editor'),
  (3, 'viewer');

# Add several rows in one statement.

Insert from select
INSERT INTO active_customers (customer_id, email)
SELECT customer_id, email
FROM customers
WHERE status = "active";

# Populate a table using query results.

Update matching rows
UPDATE users
SET status = 'inactive'
WHERE last_login_at < DATE '2024-01-01';

# Modify existing data using a WHERE clause.

Delete matching rows
DELETE FROM sessions
WHERE expires_at < CURRENT_TIMESTAMP;

# Remove rows that match a condition.

Merge or upsert data
MERGE INTO inventory AS target
USING incoming_inventory AS src
ON target.sku = src.sku
WHEN MATCHED THEN UPDATE SET quantity = src.quantity
WHEN NOT MATCHED THEN INSERT (sku, quantity) VALUES (src.sku, src.quantity);

# Insert new rows and update existing ones in one logical operation.

## Transactions
Begin, commit, and rollback
BEGIN;

UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;

COMMIT;

# Wrap multiple changes in one transaction.

Use savepoints
BEGIN;
SAVEPOINT before_optional_step;
UPDATE orders SET status = "archived" WHERE order_id = 10;
ROLLBACK TO SAVEPOINT before_optional_step;
COMMIT;

# Create partial rollback points inside a transaction.

Set transaction isolation level
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

# Control how concurrent transactions interact.

Recommended next

No recommendations yet.