Live data from Hacker News

SQL style guide by Simon Holywell

sqlstyle.guide

1–10 of 76 posts

Re: SQL style guide by Simon Holywell

#3
I've stopped using aliases in the SQL I write and it's dramatically increased the clarify.

From this style guide, the aliases section would look like this in my style guide:

    SELECT first_name
    FROM staff
    JOIN students
      ON students.mentor_id = staff.staff_num;

Re: SQL style guide by Simon Holywell

#4
Not bad advice. The one about “where possible avoid simply using id as the primary identifier for the table” stood out to me. In the past with multiple ORMs (ya, ya, we all hate them) the default was to map to a column named id. Also when doing joins its cleaner to use the table_name.id or alias.id then table_name.table_name_id or alias.table_name_id or whatever else besides id is used. The best is when multiple people have worked on the project over the years and the columns are a combo of camel, snake, camel_snake, all UPPER / lower. Must look at the table definitions or ERD every time you want to write some non-trivial query. So having a consistent style guide is better than having any one specific style guide. This would be a good starting point and adjust with your team as needed.

Re: SQL style guide by Simon Holywell

#6
post #3

I've stopped using aliases in the SQL I write and it's dramatically increased the clarify. From this style guide, the aliases section would look like this in my style guide: SELECT first_name FROM staff JOIN students ON students.mentor_id = staff.staff_num;

If the table names are all short one word like that, they are already basically aliases. What do you do when you end up on some legacy project (you did not make the schema) where_the_table_names_look_like_this? Seems some sort of alias might be more appropriate. Also, when you are writing longer / sub queries or using Common Table Expressions it’s impossible to not use an alias.

Re: SQL style guide by Simon Holywell

#9

Not bad advice. The one about “where possible avoid simply using id as the primary identifier for the table” stood out to me. In the past with multiple ORMs (ya, ya, we all hate them) the default was to map to a column named id. Also when doing joins its cleaner to use the table_name.id or alias.id then table_name.table_name_id or alias.table_name_id or whatever else besides id is used. The best is when multiple peop…

I have found that naming ids as _id helps downstream code when trying to figure out which thing's id you are dealing with. It also helps with avoiding renaming fields when a structure contains multiple ids.

I do agree it makes joins more verbose.

Post reply on HN