Search code examples
sqlsql-serverconvention

SQL coding convention: Long select statements with UNION


This is a very basic question, but I haven't found anything online.

Assume I have a large SQL file with hundreds of long select statements like this:

SELECT 'col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', NULL UNION
SELECT 'col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', NULL 

Should the UNION here be at the end, or in the front, like this:

SELECT 'col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', NULL 
UNION SELECT 'col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', NULL

Solution

  • It's very much a personal style question. Some write:

    SELECT
    id,
    name,
    dob
    FROM PERSON;
    

    Some - like me - write:

    SELECT
      id
    , name
    , dob
    FROM PERSON;
    

    A reasoning of mine for doing so (that is debateable), is that you can comment out all columns except the first with just two dashes without having to fiddle around with commas. But probably it's just because I like it so.

    For the very same reason, my friend mauro writes:

    select 42,'Arthur Dent',date '1957-04-22' union all
    select 43,'Ford Prefect',date '1900-08-01' union all
    select 44,'Tricia McMillan',date '1959-03-07'
    ;
    

    .. And I write:

              SELECT 42,'Arthur Dent',DATE '1957-04-22'
    UNION ALL SELECT 43,'Ford Prefect',DATE '1900-08-01'
    UNION ALL SELECT 44,'Tricia McMillan',DATE '1959-03-07'
    ;
    

    There is no wrong or right here. I'd just suggest you are consistent - with yourself, and with all people working on the same project as you.

    Cheers - Marco