Advanced SQL Interviews don't just test you on correctness β they often check out your SQL coding style too, especially during take-home SQL challenges.
Usually, they are checking to see if you follow SQL coding conventions that result in readable and maintainable SQL queries. That's why in this tutorial, we're going to teach you these 8 SQL query best practices:
Letβs start with the β¨basicβ¨: Use uppercase for the SQL keywords and functions. It makes your queries clearer.
Avoid writing it like this:
Instead, opt for this format:
When it comes to naming things like schemas, tables, and columns, go for lowercase or snake case (using underscores) - it's a widely adopted convention in programming languages!
For example, instead of:
Choose this format:
π‘ Our Suggestions:
Make your queries easy to read by using short and meaningful names for tables, columns, and expressions, and avoid the need for lengthy or ambiguous names.
Avoid this approach:
Instead, use this technique:
π‘ SQL Writing 101:
Want your queries to be easier on the eyes? Keep your formatting consistent. Use spaces or tabs throughout, and things will look neater.
For example, avoid this:
Instead, write like this:
π‘ A little tip: You can also use a code formatter tool to automatically apply a style to your code.
Don't use in your queries. Instead, explicitly list the columns you need. This improves query performance and makes the query more readable.
Don't write like this:
Instead, dothis:
π‘ SQL Writing 101: If you're new to a table and want to see every column, add a clause to reduce the number of rows being generated:
Make your queries more readable by using simple names and combining data from different tables with s.
Avoid doing it like this:
Instead, opt for this format:
Be clear about your JOIN types (, , , etc.) to improve query clarity.
Instead of being vague like this:
Specify the JOIN type:
Use a consistent date format to prevent ambiguity.
Avoid this:
Instead, use a consistent format (assuming 'YYYY-MM-DD' format):
Use comments to explain your queries, but avoid writing long ones between queries. Briefly explain each step for clarity. You can use to write single-line comments in SQL.
Here's an example of not-so-helpful comment:
Instead, write a useful comment:
π‘ A tip to remember: Use for longer comments and make sure they add valuable insights.
By following these tips, your queries will be easier to understand, maintain, and work with!
In the next tutorial, we'll change gears, and cover how to pivot and unpivot in SQL (similar to how PIOVT works in Excel). Have no clue what we're dtalking about? No problem!
Next Lesson
EXECUTION ORDER βοΈ