2 minutes
SQL Formatting
Code formatting on any software engineering team is standard and expected, but SQL formatting is still not widely used. Adopting a style standard makes SQL much easier to read and interpret. Consider this, a typical query without any style rules:
select
a.customer_id,
a.customer_name,
a.invoice_id,
b.product_id,
b.price,
b.line_no,
c.zip as "zip_code",
c.telephone,
c.region
from invoice_header a
join invoice_line b on a.invoice_id = b.invoice_id
join customer_master c on a.customer_id = c.customer_id
where a.return is null
The above query may not set off alarm bells in most teams, but I’d argue this is very difficult to read and can be easily improved. First, never alias tables to single characters unless they contain obvious meaning. Single characters obscure the source and make the SQL more difficult to read. Use the shortest alias that still conveys the meaning of the table. Indentation should be consistent throughout. Indenting content between the select
, from
, join
, and where
keywords makes the structure of the query more immediately apparent. Consider aliasing all the columns for consistency. Column aliasing allows the separation of behavior from naming.
select
header.customer_id as "customer_id",
header.customer_name as "customer_name",
header.invoice_id as "invoice_id",
line.product_id as "product_id",
line.price as "price",
line.line_no as "line_no",
cust.zip as "zip_code",
cust.telephone as "telephone",
cust.region as "region"
from
invoice_header header
join
invoice_line line
on header.invoice_id = line.invoice_id
join customer_master cust
on header.customer_id = cust.customer_id
where
header.return is null
Also, consider using something like SQLFluff to automate the linting process.
236 Words
2024-07-29 21:49