SQL Style Guide
A SQL style guide is a short set of rules for how a team writes SQL, so every query looks familiar and is quick to review. The database doesn't care about style: a query squeezed onto one line returns the same rows as one laid out over twenty. People care. A query is read far more often than it's written, by reviewers, by teammates fixing a bug at night, and by you six months later. In this lesson, we will take a messy but working query and rewrite it step by step: one clause per line, consistent keyword case, clear names and aliases, explicit joins, useful comments and CTEs for long logic. At the end there's a checklist to run before you share a query. These rules match common published guides; whatever your team picks, the most important rule is to be consistent.
In One Minute
- One clause per line (
SELECT,FROM,JOIN,WHERE,GROUP BY,ORDER BY), and one column per line in long lists. - Keywords in one case (this course uses UPPERCASE); names in lowercase
snake_case. - Name things plainly: plural table names,
<table>_idkeys, units in column names (fee_usd). - Short, meaningful aliases (
sforstudents); nevera,b,c. - Explicit
JOIN ... ON, never commas with conditions inWHERE. - Comments explain why, not what; CTEs split long logic into named steps.
- Be consistent, and let a formatter do the spacing.
Before and After
Here is a working query that's hard to read. It lists each student's total paid for Java courses:
select s.first_name,sum(p.amount_usd) as t from students s,payments p,courses c where s.student_id=p.student_id and c.course_id=p.course_id and c.technology='Java' group by s.first_name order by 2 desc; first_name | t
------------+---------
Srihitha | 1500.00
(1 row)And the same query, following the style in this lesson:
-- Total paid per student for Java courses, highest first
SELECT
s.first_name,
sum(p.amount_usd) AS total_paid_usd
FROM payments AS p
JOIN students AS s ON s.student_id = p.student_id
JOIN courses AS c ON c.course_id = p.course_id
WHERE c.technology = 'Java'
GROUP BY s.first_name
ORDER BY total_paid_usd DESC, s.first_name; first_name | total_paid_usd
------------+----------------
Srihitha | 1500.00
(1 row)Explanation: The results are the same rows; only the column name changed from t to total_paid_usd. But the second version can be checked at a glance: each clause starts a line, the joins say exactly how tables connect, the filter stands alone, and total_paid_usd tells the reader what the number is and its unit. ORDER BY total_paid_usd DESC, s.first_name replaces ORDER BY 2, which silently breaks if someone adds a column, and the tie-breaker makes the order certain.
Layout
Put each main clause at the start of its own line, and indent what belongs to it.
| Rule | Example |
|---|---|
| One clause per line | SELECT ... / FROM ... / WHERE ... |
| Long column lists: one per line, indented | s.first_name, / s.last_name, |
Each JOIN on its own line, with its ON | JOIN courses AS c ON c.course_id = p.course_id |
Several conditions: one per line, starting with AND / OR | WHERE c.technology = 'Java' / AND p.paid_on >= '2025-12-01' |
| Spaces around operators and after commas | a = b, not a=b; (a, b), not (a,b) |
End statements with ; | Required between statements anyway |
Leading or trailing commas? Both are common. Trailing commas (s.first_name,) read like normal text; leading commas (, s.first_name) make it easy to comment out the last line. Pick one per team.
Case and Naming
Write keywords in one case and names in another, so they're easy to tell apart. This course writes keywords in UPPERCASE and names in lowercase; many teams use all-lowercase with syntax highlighting doing the job. Either works if it's consistent.
| Thing | Convention | Good | Avoid |
|---|---|---|---|
| Tables | Plural nouns, snake_case | payments, study_sessions | Payment, tblPayment, PaymentsTable |
| Columns | Singular, snake_case, units included | amount_usd, paid_on, is_active | Amt, paidDate, flag1 |
| Primary key | <singular table>_id | payment_id | id (ambiguous in joins), ID |
| Foreign key | Same name as the key it points to | payments.student_id | payments.stu |
| Dates and times | _on for dates, _at for timestamps | paid_on, created_at | date, time (reserved words) |
| Booleans | A yes/no question | is_active, has_paid | active_flag, status_bit |
| Indexes and constraints | Table, columns, kind | payments_student_id_idx | idx1 |
Avoid names that need quotes. "Student Name" or "Order" must be quoted forever, in every query, by everyone. Lowercase names without spaces or reserved words never need quotes, in any database.
Aliases
An alias should be short and point clearly to its table. Use the first letter or a short abbreviation (s for students, p for payments, e for enrollments), and write AS so it's obvious that an alias is being defined.
| Do | Don't |
|---|---|
FROM payments AS p JOIN students AS s | FROM payments a JOIN students b |
Prefix every column with its alias when there's a join: s.first_name | Leave columns bare, so readers guess which table they come from |
Name output columns for what they mean: sum(p.amount_usd) AS total_paid_usd | AS t, AS x, or no name at all (sum) |
Use a longer alias when the same table appears twice: mentee, mentor (Self Join) | s1, s2 |
Joins and Filters
Always write joins with JOIN ... ON. The old comma style, FROM a, b WHERE a.x = b.x, mixes join conditions with filters, and forgetting one condition silently produces a cross join with every combination of rows (CROSS JOIN):
-- The comma join with its join condition forgotten
SELECT count(*) AS rows_returned
FROM students s, payments p
WHERE p.amount_usd > 400; rows_returned
---------------
6
(1 row)Explanation: Only two payments are over $400, but the query returns 6 rows: each of those payments paired with every one of the three students, because nothing connects the two tables. With JOIN payments AS p ON p.student_id = s.student_id, the missing condition would have been a syntax error, not a wrong answer.
Other rules for conditions: compare columns to values of the same type (paid_on >= DATE '2025-12-01'), write ranges as >= start AND < end rather than BETWEEN on timestamps (Date Functions), and put parentheses around mixed AND / OR even when not strictly needed (AND, OR and NOT).
Comments and CTEs
A comment should explain why the query does something, not repeat what the SQL already says.
| Helpful | Not helpful |
|---|---|
-- Refunds are stored as negative payments, so exclude them from revenue | -- select the amount |
-- Course 6 has no fee yet; LEFT JOIN keeps it in the list | -- join courses |
| A header: what the query answers, who uses it | Commented-out old code left behind |
When a query has several steps, give each step a name with a CTE (Common Table Expressions). A reader can then follow the logic from top to bottom:
-- Students who have paid more than the average student, with their totals
WITH totals AS (
SELECT student_id, sum(amount_usd) AS total_paid_usd
FROM payments
GROUP BY student_id
),
average AS (
SELECT avg(total_paid_usd) AS avg_paid_usd
FROM totals
)
SELECT
s.first_name,
t.total_paid_usd
FROM totals AS t
JOIN students AS s ON s.student_id = t.student_id
CROSS JOIN average AS a
WHERE t.total_paid_usd > a.avg_paid_usd
ORDER BY t.total_paid_usd DESC; first_name | total_paid_usd
------------+----------------
Srihitha | 1700.00
(1 row)Explanation: totals and average read like the sentences you'd use to describe the question: "work out each student's total, work out the average, then keep the students above it." Only Srihitha, with $1,700.00, is above the $1,075.00 average of the two students who have paid.
Let a Tool Do the Spacing
Formatters and linters apply a style automatically, so reviews can focus on logic instead of spaces. SQLFluff is a widely used open-source linter and formatter for many dialects; pgFormatter formats PostgreSQL; most editors and database tools (DBeaver, DataGrip, VS Code extensions) also format SQL. Run the formatter before committing, and let a CI check fail on unformatted SQL so nobody has to point it out by hand.
A Checklist Before You Share a Query
| Check | Why |
|---|---|
| Each clause on its own line; long lists one item per line | Easy to scan and to diff |
| Keywords and names in consistent case | Easy to tell apart |
Every join is JOIN ... ON, with the right join type | No accidental cross joins; LEFT JOIN kept on purpose |
| Columns prefixed with aliases when there's a join | No guessing which table a column is from |
| Output columns named for meaning and unit | total_paid_usd, not t or sum |
No SELECT * in application code | Columns added later don't change results or break code |
ORDER BY names columns, with a tie-breaker | Stable, readable ordering |
| Values passed as parameters in app code | No SQL injection (SQL Injection) |
NULL handled on purpose | COALESCE, IS NULL, count(col) vs count(*) |
| A comment for anything surprising | The next reader knows why |
Common Mistakes
SELECT * in application code. A new column changes every result and can break code that reads columns by position. List the columns.
ORDER BY 2 or GROUP BY 1, 2. Positions break silently when columns move. Use names. (Some teams allow GROUP BY 1 in quick analysis queries; keep it out of code that lives long.)
Cryptic aliases. a, b, c force readers to scroll back. Use table initials or roles.
Names that need quotes. "Order" and "First Name" must be quoted forever. Use lowercase snake_case.
Comments that restate the SQL. They add noise and go stale. Explain the reason instead.
Arguing about style in every review. Pick a guide, automate it, and move on.
Interview Corner
What makes a SQL query readable?
One clause per line, consistent keyword case, clear table aliases, explicit JOIN ... ON, meaningful output column names, CTEs for multi-step logic, and comments that explain why. Most of it can be automated with a formatter.
Why avoid SELECT * in production code?
It returns columns you don't need, can change when the table changes, can break code that relies on column order, and hides which columns the query actually depends on.
Why prefer JOIN ... ON over comma joins?
It separates join conditions from filters, makes the join type explicit, and turns a forgotten join condition into an error instead of a silent cross join.
How would you name a column storing a course fee in dollars?
Something like fee_usd: lowercase snake_case, singular, with the unit in the name.
Practice
Challenge: Restyle this query so it follows the guide, and make sure it returns the same rows: select c.title,count(*) n from courses c,enrollments e where c.course_id=e.course_id and e.status='active' group by c.title order by 2 desc,1;
Show solution
-- Number of active students in each course, most popular first
SELECT
c.title,
count(*) AS active_students
FROM enrollments AS e
JOIN courses AS c ON c.course_id = e.course_id
WHERE e.status = 'active'
GROUP BY c.title
ORDER BY active_students DESC, c.title; title | active_students
-------------------+-----------------
SQL Basics | 2
Java Basics | 1
Java Collections | 1
JavaScript Basics | 1
(4 rows)The comma join became JOIN ... ON, n became active_students, and ORDER BY 2 DESC, 1 became names. Courses with no active students don't appear, exactly as in the original; to list them with 0, you'd start FROM courses with a LEFT JOIN and move the status test into the ON clause (LEFT JOIN).
Key Takeaways
| Instead of | Write |
|---|---|
select ... from a, b where a.x = b.x | SELECT ... FROM a JOIN b ON b.x = a.x |
sum(amount_usd) t | sum(amount_usd) AS total_paid_usd |
ORDER BY 2 DESC | ORDER BY total_paid_usd DESC, first_name |
SELECT * | The columns you need |
"Student Name" | student_name |
Was this tutorial helpful?