Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

12.2 SQL Style Guide

Like all programming languages, SQL is incredibly flexible. However, following some best practices will keep your code easier to follow, and your database easier to maintain.

Data Modeling and Database Design

Before we begin to talk about syntax, the schema design will have the biggest long-term impact on your query readability.

Table and Attribute Names

Preferred:

Avoids:

Attributes and Types

Learn the datatypes that your DBMS offers. PostgreSQL offers many built-in data types. Chosing the best datatype can help improve performance and avpod data inconsistency errors.

Dates, Times, and Timestamps

Dates and times are some of the trickiest things to get right. Partially because it’s incredibly difficult to reconcile bad data.

You may make a lot of assumptions about how dates and times work in your life today, but many of these assumptions are not guaranteed to be true. Not everywhere observes daylight savings time, for example. And while we often think timezones are hour long blocks, there are some 15 minute timezone boundaries!


Query Syntax

Good structure for your SQL queries will help make them easier to read.

SQL Keywords

Intendation

Miscelleanous

For example:

WITH some_table AS (
  SELECT column1, column2, COUNT(*) AS my_count
  FROM another_table
)
SELECT *
FROM some_table
JOIN big_table as bt on bt.id = some_table.big_table_id
WHERE bt.some_value > 5;