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

Build and change schema objects.

Create table

Define a new table with columns and constraints.

sqlANYcreate-tableddl
sql
CREATE TABLE users (
  user_id INTEGER PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  created_at TIMESTAMP NOT NULL
);
Notes

Use explicit types and constraints to enforce data quality.

Add a column

Modify an existing table by adding a new column.

sqlANYalter-tableddl
sql
ALTER TABLE users
ADD COLUMN last_login_at TIMESTAMP;
Notes

ALTER TABLE changes schema without recreating the table.

Add a constraint

Attach a foreign key or check constraint after table creation.

sqlANYalter-tableconstraintforeign-key
sql
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers(customer_id);
Notes

Constraints help maintain relational integrity.

Drop table

Remove a table definition and its data.

sqlANYdrop-tableddl
sql
DROP TABLE old_logs;
Notes

Be careful: dropping a table deletes its data. Some engines support IF EXISTS.

Truncate table

Remove all rows quickly without dropping the table.

sqlANYtruncateddlmaintenance
sql
TRUNCATE TABLE staging_events;
Notes

TRUNCATE is often faster than DELETE for clearing a table.

Constraints and Indexes

Enforce integrity and speed up lookups.

Define primary key

Mark a column as the main row identifier.

sqlANYprimary-keyconstraint
sql
CREATE TABLE departments (
  department_id INTEGER PRIMARY KEY,
  name VARCHAR(100) NOT NULL
);
Notes

Primary keys uniquely identify each row.

Define unique constraint

Ensure a column or column set stays unique.

sqlANYuniqueconstraint
sql
ALTER TABLE users
ADD CONSTRAINT uq_users_email UNIQUE (email);
Notes

Unique constraints prevent duplicate values.

Add check constraint

Restrict column values with a boolean rule.

sqlANYcheck-constraintconstraint
sql
ALTER TABLE products
ADD CONSTRAINT chk_price_positive CHECK (price >= 0);
Notes

CHECK constraints enforce domain rules inside the database.

Create index

Add an index to improve lookup performance.

sqlANYindexperformanceddl
sql
CREATE INDEX idx_orders_customer_id
ON orders (customer_id);
Notes

Indexes speed up reads but add write overhead and storage cost.

Create composite index

Index multiple columns together.

sqlANYindexcomposite-indexperformance
sql
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at);
Notes

Column order matters in composite indexes.

INSERT, UPDATE, and DELETE

Modify table data.

Insert one row

Add a single row to a table.

sqlANYinsertdml
sql
INSERT INTO users (user_id, email, created_at)
VALUES (1, 'a@example.com', CURRENT_TIMESTAMP);
Notes

Specify column names explicitly for clarity and safety.

Insert multiple rows

Add several rows in one statement.

sqlANYinsertbulk-insert
sql
INSERT INTO roles (role_id, role_name)
VALUES
  (1, 'admin'),
  (2, 'editor'),
  (3, 'viewer');
Notes

Multi-row INSERT is concise and often more efficient than repeated single-row inserts.

Insert from select

Populate a table using query results.

sqlANYinsertselect
sql
INSERT INTO active_customers (customer_id, email)
SELECT customer_id, email
FROM customers
WHERE status = "active";
Notes

Great for staging and snapshot tables.

Update matching rows

Modify existing data using a WHERE clause.

sqlANYupdatedml
sql
UPDATE users
SET status = 'inactive'
WHERE last_login_at < DATE '2024-01-01';
Notes

Always confirm the WHERE clause before running UPDATE in production.

Delete matching rows

Remove rows that match a condition.

sqlANYdeletedml
sql
DELETE FROM sessions
WHERE expires_at < CURRENT_TIMESTAMP;
Notes

DELETE removes rows one by one from the table.

Merge or upsert data

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

sqlANYmergeupsertdml
sql
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);
Notes

MERGE support and exact syntax vary by dialect. Some engines use ON CONFLICT or ON DUPLICATE KEY UPDATE instead.

Transactions

Control units of work and isolation boundaries.

Begin, commit, and rollback

Wrap multiple changes in one transaction.

sqlANYtransactionsbegincommitrollback
sql
BEGIN;

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

COMMIT;
Notes

If something fails, use ROLLBACK instead of COMMIT.

Use savepoints

Create partial rollback points inside a transaction.

sqlANYtransactionssavepoint
sql
BEGIN;
SAVEPOINT before_optional_step;
UPDATE orders SET status = "archived" WHERE order_id = 10;
ROLLBACK TO SAVEPOINT before_optional_step;
COMMIT;
Notes

Savepoints let you recover from part of a transaction without aborting the whole unit of work.

Set transaction isolation level

Control how concurrent transactions interact.

sqlANYtransactionsisolation
sql
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
Notes

Isolation level support can vary across engines, but this is a core transactional concept.

Recommended next

No recommendations yet.