Member-only story
3 Simple Tricks to Better Structure Your SQL Queries
And a Hands-on Example to Apply Them Right Away
SQL stands for Structured Query Language. Unfortunately, this does not mean that you will come up naturally with a perfectly structured piece of code once you start programming in this computer language.
As a Data Analyst, I keep applying myself three simple rules to better structure my SQL queries. They allow me not only to avoid mistakes in the way that I query from databases, but also to save time — for myself as well as for the colleagues I share my queries with. Let me present you these tricks and illustrate them with a real-life example.
1. Visualize your query output
Efficiently structuring your SQL code starts by having in mind the result you want to achieve. Ask yourself this simple question: How do I want my output table to look like?
In particular, pay attention to the following:
- Granularity level: at what level of aggregation do you want your output table to be? In other words, what should each row correspond to?
- Output fields: which fields will you be using based on the table generated by your query? In other words, what should each column correspond to?