AlgoViz

SQL databases

easy 25 min

A SQL (relational) database keeps data in tables with declared columns, joins those tables by key when you ask a question, and enforces rules such as unique emails and valid references.

A tiny relational engine

Read it, run it, change a line and run it again.

Loading editor…

Constraints, a hash join, grouping and rollback in plain Python. A real engine adds storage, indexes, a planner and isolation.

The same in SQL
-- PostgreSQLCREATE TABLE users (    id SERIAL PRIMARY KEY,    email VARCHAR(255) UNIQUE NOT NULL,    name VARCHAR(100) NOT NULL,    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);CREATE TABLE orders (    id SERIAL PRIMARY KEY,    user_id INT NOT NULL REFERENCES users(id),    total NUMERIC(10, 2) NOT NULL CHECK (total >= 0),    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);INSERT INTO users (email, name)VALUES ('alice@example.com', 'Alice')RETURNING id;SELECT * FROM users WHERE name = 'Bob';UPDATE users SET email = 'bob@new.example' WHERE id = 2;DELETE FROM users WHERE id = 3;SELECT u.name, o.total, o.created_atFROM users uJOIN orders o ON u.id = o.user_idWHERE o.total > 100ORDER BY o.created_at DESCLIMIT 10;SELECT user_id, COUNT(*) AS order_count, SUM(total) AS total_spentFROM ordersGROUP BY user_idHAVING COUNT(*) > 5;BEGIN;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;COMMIT;