Modularize Code via Common Table Expressions
There are other things to consider like naming conventions and commenting, which we’ll cover later in this article.Ģ. Most importantly, you want to make sure that your programming style is consistent throughout your code. For example, instead of… WHERE height<=200 AND age<=65Ĭonsider using white spaces to make it more legible: WHERE height <= 200 AND age <= 65 Spaces refers to the white space that you use in your code. You don’t necessarily have to follow this exact way, but you should apply indentation and align your statements where ever you can. Notice how all of the column names in the SELECT clause are aligned, the conditions in the WHERE clause are aligned, and the conditions in the CASE statement are aligned. The main reason why the second block of code is more legible is because of its indentation and vertical alignment. It’s quite obvious that the second one is much easier to read and that’s completely attributed to its programming style! There are several components of programming style, but we’re going to focus on indentation and spaces. Or SELECT name, height, weight, age, gender, CASE WHEN age < 18 THEN "child" ELSE "adult" END AS childOrAdult, salary FROM People LEFT JOIN Income USING (name) WHERE height <= 200 AND age <= 65 Let me give you a quick example - which of the following two blocks of code are more legible? SELECT name,height,weight,age,gender,CASE WHEN age<18 THEN "child" ELSE "adult" END AS childOrAdult,salary FROM People LEFT JOIN Income USING (name) WHERE height<=200 and age<=65 The style in which you code is essential for interpretability and minimizing errors. If you think that your programming style is trivial for SQL, think again.