# SQL Tables, Constraints and Indexes

Define and change schema.

```sql
CREATE TABLE users (
  id          BIGINT PRIMARY KEY,
  email       VARCHAR(255) NOT NULL UNIQUE,
  name        TEXT NOT NULL,
  age         INTEGER CHECK (age >= 0),
  active      BOOLEAN DEFAULT TRUE,
  created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE orders (
  id        BIGINT PRIMARY KEY,
  user_id   BIGINT NOT NULL REFERENCES users(id),
  total     NUMERIC(10,2) NOT NULL
);

ALTER TABLE users ADD COLUMN phone VARCHAR(30);
ALTER TABLE users DROP COLUMN phone;
CREATE INDEX idx_orders_user ON orders(user_id);
DROP TABLE orders;
TRUNCATE TABLE logs;     -- remove all rows, keep structure

BEGIN;  UPDATE accounts SET balance = balance - 50 WHERE id = 1;  COMMIT;  -- or ROLLBACK;
```
