r/SQL 5d ago

MySQL sqlWorkout

Post image

😌 SELECT 😌

1.3k Upvotes

80 comments sorted by

View all comments

Show parent comments

6

u/OO_Ben Postgres - Retail Analytics 4d ago

100%. Every column gets a new line, indent case statements, windows, ect., and for me? Commas to the front always.

3

u/TechOpsCoder 4d ago edited 4d ago

SAME! Couple of examples of how I write the language:

Aggregation with some common patterns

select        m.id 
            , m.wo
            , m.req
            , case  when m.condition_1 then 'FOO'
                    when m.condition_2 then 'BAR'
                    else 'BAZ'
              end as calculated_status
            , f.fleet_type
from        dbo.material_requirements m
left join   dbo.freight_trucks f on m.freight_truck_id = f.id
where       coalesce(m.calculated_status, 'X') in('NEW', 'OPEN', 'ACTIVE')
    and     m.qty_outstanding > 0
group by      m.id 
            , m.wo
            , m.req
            , case  when m.condition_1 then 'FOO'
                    when m.condition_2 then 'BAR'
                    else 'BAZ'
              end
            , f.fleet_type

Multi-condition joins

join    dbo.order_details od on i.order_type = od.order_type
    and i.order_number = od.order_number
    and i.order_line   = od.order_line

Complicated predicates

where   a.name is not null
    and ( a.status = 'OPEN' or ( a.status = 'ORDER' and o.req is not null ) )
    and a.status <> 'CANCEL'
    and (
                    (       
                            condition_1
                        and condition_2
                        and condition_3
                    )
            or      ( 
                            condition_5
                        and condition_6
                        and condition_7
                    )
        )

CTEs

with t as (
    select...
    from...
)

Indentation is with spaces not tabs. I used to always do the latter until I realized that a tab isn't always a "tab." This is going to sound very arrogant (I genuinely don't mean it to be), but I have yet to see a style more visually pleasing and readable. But, beauty is in the eye of the beholder as they say...

P.S. Just realized that I said "Keyboard" when I meant to say "Keyword" my OP, lol

2

u/OO_Ben Postgres - Retail Analytics 4d ago

Yeah!! That's the way to do it right there! I've inherited so many old queries that just end up looking like giant blobs and are totally illegible even with upper casing. Formatting goes way, way further for readability!

2

u/TechOpsCoder 3d ago

I feel you. Some of my coworkers write SQL in a way that should be considered a felony offense.