• 1 Post
  • 1 Comment
Joined 2 months ago
cake
Cake day: August 16th, 2024

help-circle
  • I have advice that you didn’t ask for at all!

    SQL’s declarative ordering annoys me too. In most languages you order things based on when you want them to happen, SQL doesn’t work like that- you need to order query dyntax based on where that bit goes according to the rules of SQL. It’s meant to aid readability, some people like it a lot,but for me it’s just a bunch of extra rules to remember.

    Anyway, for nested expressions, I think CTEs make stuff a lot easier, and SQL query optimisers mean you probably shouldn’t have to worry about performance.

    I.e. instead of:

    SELECT
      one.col_a,
      two.col_b
    FROM one
    LEFT JOIN
        (SELECT * FROM somewhere WHERE something) as two
        ON one.x = two.x
    

    you can do this:

    WITH two as (
         SELECT * FROM somewhere
         WHERE something
    )
    
    SELECT
      one.col_a,
      two.col_b
    FROM one
    LEFT JOIN two
    ON one.x = two.x
    

    Especially when things are a little gnarly with lots of nested CTEs, this style makes stuff a tonne easier to reason with.