| description | SQL guidelines for .sql files and migration files | ||
|---|---|---|---|
| globs |
|
- Use
snake_casefor all table names, column names, index names, and constraint names. - Table names are plural nouns (
users,orders,line_items). - Foreign key columns follow the pattern
<referenced_table_singular>_id(e.g.,user_id). - Index names follow the pattern
idx_<table>_<columns>(e.g.,idx_orders_user_id).
- Use
BIGINT(orBIGSERIALin Postgres) for primary keys. Do not useINTfor IDs on tables that may grow large. - Add indexes for every foreign key column.
- Add indexes for columns that appear frequently in
WHERE,ORDER BY, orJOINconditions. - Add a
created_attimestamp (with timezone) to every table.
- Every migration must include both an
upand adownsection. Migrations must be reversible. - Wrap multi-statement migrations in a transaction so a partial failure does not leave the schema in an inconsistent state.
- When adding a column to a large table, add it as
NULLfirst. Backfill data in a separate step. Then add theNOT NULLconstraint. - Never drop a column or table in the same migration that removes the application code referencing it. Drop in a follow-up migration after deploying the code change.
- Never rename a column or table directly in one step on a live database. Add the new name, migrate data, then remove the old name.
- Write SQL keywords in uppercase (
SELECT,FROM,WHERE,JOIN). - Qualify ambiguous column names with the table name or alias when joining multiple tables.
- Avoid
SELECT *in application queries. List columns explicitly. - Prefer
EXISTSoverCOUNT(*)when checking for the presence of rows.