Formatting SQL Queries

How I try to format my queries for better legibility (doesn't always happen though..) 
Notes, tips always welcome.

Basic rules:
  • indent and new line whenever applicable (make sure they align)
    • indent on: after a select statement, 2nd+ conditional, after a bracket
  • lowercase for syntax and aliases you make, uppercase for original column/table names
  • leading commas in select statements
  • initiate where/joins with 1=1 if complex conditions
  • temp tables > subqueries unless the subquery is basic
  • comment often
----------------------------------------------------------------------------------
/*
Name: Example Query

Sections:
    Section 1: Description
    Section 2: Description
    Section 3: Description

Dependencies:
    Section 1:
        -Table A
        -Table B
    Section 2:
        -Table C
    Section 3:

Output:
    Output table, if applicable

Version    Date Created    Created by    Description
1          2021-04-18      michelle      initial creation

*/

-- ******************************************** 
-- Section 1: Description

-- ---------------------
-- Section 1 pt 1: Basic formatting
create temporary table First(
    select 
        tabOne.a
        , tabTwo.b
        , tabTwo.c

        , sum(b.d)
    from TABLEA as tabOne

    join TABLEB as tabTwo
    on tabOne.b = tabTwo.b

    where 1=1
        and tabOne.a = 'whatever'
)
;

-- Section 1 pt 2: Formatting a subquery
select 
    *
from(
    select distinct
        A
        ,B
    from TABLEA

    join(
        select distinct
            C
        from TABLEB
    )
    on 1=1
        and TABLEA.B = TABLEB.C
        and etc......
)
;


-- ******************************************** 
-- Section 2: Description

etc.....

-- ******************************************** 
-- Section 3: Description

Comments

Popular posts from this blog

Making Predictions with a Tensorflow/Keras Model on a Webpage

SQL Syntax Notes

Basic Python Functions