First and foremost, I am learning SQL for the first time. I only know a bit a Python from following the
Data Analyst in Python path from Dataquest. That is the full extent of my “programming background.” As such, I want to learn as many best practices and as quickly as I can so that I do not teach myself bad habits that will be difficult to unlearn later on.
In my first SQL mission (Introduction to SQL) I came across this SQL Style Guide. I quickly scanned it and was only able to make sense of about 20% of it; I was so new to SQL syntax, I wasn’t sure what a lot of it referred to. So I carried on with the SQL missions but couldn’t help but notice that the lessons/missions that followed would rarely follow the (little) advice I had just read about in the SQL style guide. I ignored these inconsistencies and just continued on the learning path. Hakuna matata.
However, I am now into the Building and Organizing Complex Queries mission which again mentions the above style guide. I read it again. No surprise, I was able to learn a lot more from it after completing several missions since last reading it. This lead me to Goolge-around a bit where I found this article. This advice goes (almost entirely) against what I just read in the other style guide! So what gives?!
Then it hit me: it’s just a guide, Mike, not a rule book! Then I found this article on medium which (effectively) is a blend of the two previously mentioned style guides. However, I did learn a lot just by noticing the differences and scrutinizing the examples.
So, if you’re like me and want to know the “right way” to be formatting your SQL queries, understand that these guides are just guides and aren’t written in stone. Sure, there are definitely some common threads amongst them but ultimately their purpose is the same: to increase readability, facilitate maintaining code, and increase portability between SQL flavours. For this reason, there will be similarities and there will be differences. There is no SQL style rule book per se…not that I know of anyway!
My suggestion would be to do as I have done: take them with a grain of salt and read as many different ones as you feel comfortable reading then adopt the practices that make the most sense to you. You may try one way of writing a query and discover that it’s not as clear/readable as you once thought and so adopt a new way of styling it. I think that’s okay.
I suspect that in the real world, our data team would have an agreed upon style which we would then treat as law…however, for now, I am not going to worry so much about “lining up my river” or whether I should be explicitly using
AS for aliasing or if I should be using CTEs instead of subqueries (whatever those are!). All that said, I think it’s good to think about and start to develop good styling habits as we learn new syntax but always keep in mind that it’s a guide and not a law.
Happy learning everyone!