There is no doubt that writing code is more art than science and every coder cannot write beautiful code which is both readable and maintainable, even with the experience. Yes, it’s blunt and hard but it’s mostly true.

In general, coding improves with experience but only when you learn the art of coding like favoring composition over inheritance or coding for interface than implementation, but, unfortunately only a few developers able to master these techniques.

The same applies to SQL queries. The way you structure your query, the way you write it goes a long way to communicate your intent to the fellow developer, DBA, and even yourself after a few months.

Whenever I see SQL queries on emails from different developers, I can see the stark difference in their writing style. Some developers and DBAs write it so neatly and indent their query such that you can easily spot key details like which columns you are extracting, and from which table, and what are joining or filtering conditions.

Since in real-life projects, SQL queries are hardly one-liner, learning the right way to write complex SQL queries makes a lot of difference; especially when you share that query to someone for review or execution. It also helps when you read it yourself later as I said, after a few months.

The problem is there are many books and courses to teach you SQL like what is a table, different SQL commands but there are very few (like The Complete SQL Bootcamp by Josh Portilla) which focus on writing proper SQL queries.

In this article, I am going to show you a couple of styles which I have tried in the past, their pros and cons and what I think is the best way to write SQL queries.

Unless you have a good reason not to use my style e.g. you have a better style or you want to stick with the style used in your project (consistency overrules everything) there is no reason not to use it.

By the way, I expect that you are familiar with SQL and definitely know how to write queries. I expect that you have used different SQL clauses like SELECT, INSERT, UPDATE, DELETE and understand their meaning in a SQL query. If you are not, it’s better you gain some experience with SQL by joining some of my recommended courses like:

Learn SQL by CodeCademy
Introduction to SQL by Jon Flanders
The Complete SQL Bootcamp by Josh Portilla, a Data Scientist, on Udemy or
SQL for Newbs: Data Analysis for Beginners by David Kim and Peter Sefton’s course on Udemy.
They all are great courses and teach you SQL basics, but, if you need some free alternatives you can also check out this list of free SQL courses for programmers and developers.

#database #sql #mysql #oracle #tips #sql server #sql (structured query language) #intro to sql #sql bootcamp

3 Tips to Write SQL Queries That Are Easier to Read and Modify
2.20 GEEK