Data Manipulation Language (DML) statements query and modify data in tables.
SELECT
INSERT
UPDATE
DELETE
UPSERT
Query data from tables.
SELECT * FROM users WHERE email LIKE '%@example.com';SELECT u.username, COUNT(o.id) AS order_countFROM users uLEFT JOIN orders o ON u.id = o.user_idGROUP BY u.usernameHAVING COUNT(o.id) > 5ORDER BY order_count DESCLIMIT 10;
Insert new rows into a table.
INSERT INTO users (username, email)VALUES ('alice', '[email protected]');INSERT INTO orders (user_id, total, status)VALUES (1, 99.99, 'pending'), (2, 149.99, 'shipped');
Modify existing rows in a table.
UPDATE usersSET last_login = now()WHERE id = '7f9c24e8-3b12-4fef-91e0-56a2d5a246ec';UPDATE ordersSET status = 'cancelled'WHERE created_at < now() - INTERVAL '90 days' AND status = 'pending';
Remove rows from a table.
DELETE FROM sessions WHERE expires_at < now();DELETE FROM users WHERE id = '123e4567-e89b-12d3-a456-426614174000';
Insert rows or update them if they already exist.
UPSERT INTO user_preferences (user_id, theme, language)VALUES ('user123', 'dark', 'en');
WITH regional_sales AS ( SELECT region, SUM(amount) AS total_sales FROM orders GROUP BY region)SELECT region, total_salesFROM regional_salesWHERE total_sales > 1000000;
Data Control Language (DCL) statements manage access permissions and security.
CREATE USER alice WITH PASSWORD 'secure123';CREATE ROLE developers;GRANT developers TO alice;ALTER USER alice WITH PASSWORD 'newsecure456';DROP USER IF EXISTS olduser;
BEGIN;INSERT INTO accounts (id, balance) VALUES (1, 1000);INSERT INTO accounts (id, balance) VALUES (2, 500);COMMIT;
Abort a transaction and discard changes.
BEGIN;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;-- Something went wrongROLLBACK;
Create nested transactions with savepoints.
BEGIN;SAVEPOINT sp1;UPDATE users SET status = 'active' WHERE id = 1;SAVEPOINT sp2;DELETE FROM logs WHERE created_at < now() - INTERVAL '1 year';-- Rollback only the DELETEROLLBACK TO SAVEPOINT sp2;-- Release the first savepointRELEASE SAVEPOINT sp1;COMMIT;