From e43288f87aedfa2571cee8f7d43c9d4a43c83362 Mon Sep 17 00:00:00 2001 From: Zach Margolis Date: Wed, 22 May 2024 10:39:52 -0700 Subject: [PATCH 1/2] Add a SQL style guide --- _articles/queries.md | 1 + 1 file changed, 1 insertion(+) diff --git a/_articles/queries.md b/_articles/queries.md index f0bca5fd..0e474f7b 100644 --- a/_articles/queries.md +++ b/_articles/queries.md @@ -3,6 +3,7 @@ title: "Reporting Queries" description: "Queries to run in the Rails console for common reporting questions" layout: article category: "Reporting" +subcategory: "Queries" --- ## Query timeout From c5809322ac94b44b08c8f85dd983bc7cf64ea4e9 Mon Sep 17 00:00:00 2001 From: Zach Margolis Date: Wed, 22 May 2024 11:08:55 -0700 Subject: [PATCH 2/2] Add missing article --- _articles/sql-style-guide.md | 67 ++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 _articles/sql-style-guide.md diff --git a/_articles/sql-style-guide.md b/_articles/sql-style-guide.md new file mode 100644 index 00000000..c8888363 --- /dev/null +++ b/_articles/sql-style-guide.md @@ -0,0 +1,67 @@ +--- +title: "SQL Style Guide" +description: "Conventions for formatting SQL queries" +layout: article +category: "Reporting" +subcategory: "Queries" +--- + +This is a guide for writing "raw" SQL queries, used in ETLs and reports. It does +not apply to queries that are auto-generated via ORMs like ActiveRecord. + +Currently we do not have any automated linting/enforcement of this guide. + +## Keywords + +Capitalize keywords + +```sql +-- DO +SELECT 1 +FROM mytable; + +-- DO NOT +select 1 +from mytable; +``` + +## Commas + +Prefer leading commas (they usually make for less diff noise when adding or removing items in a list) + +```sql +-- DO +SELECT + col1 +, col2 +, col3 +FROM mytable; + +-- DO NOT +SELECT + col1, + col2, + col3 +FROM mytablel +``` + +## `SELECT *` + +Avoid `SELECT *` and select specific fields when possible. Using explicit columns +makes analysis of queries easier. + +(This rule applies most to checked-in code. For running test queries interactively, +`SELECT *` is totally fine). + +```sql +-- DO +SELECT + col1 +, col2 +, col3 +FROM mytable; + +-- DO NOT +SELECT * +FROM mytable; +```