r/SQL • u/Ali-Zainulabdin • Oct 23 '24
Discussion SQL Tricks Thread
Hi everyone, let's start a thread to share useful SQL tips and tricks that have saved you time or made querying more efficient. Whether it's optimizing queries, using window functions, or organizing data, all insights are welcome! Beginners and pros alike can learn a lot from this. Looking forward to your contributions!
230
Upvotes
3
u/0sergio-hash Oct 24 '24 edited Oct 24 '24
These are from more the analytics perspective than engineering but I've found them helpful in my short experience so far
A more meta tip is for debugging. If a block of code or nested thingy won't run, I try to copy paste most of it elsewhere and run the innermost part, then add a part, run again, etc etc to pinpoint the big
This is also helpful for testing assumptions when developing logic
2. I was reminded of this trick yesterday:
And it's cousin
3. I can't stress enough how much formatting, aliasing tables to helpful names, aliasing columns to helpful names and adding in spaces between blocks of the query help me
Aliasing and putting the alias before all the col names and organizing cols by table you pulled them from / organizing similar calcs is so visually helpful when I revisit code later
4. Break complicated processes into steps. I'd always rather more verbose code and 5 intelligible temp tables (which you can create and query independently of each other for debugging later by the way) than one big block of nested ugly code lol
5. REGEX !!!
I know Postgres has it, and some others. When you have it, use it. Special characters or things that shouldn't be there will wind up in your data set eventually and knowing how to clean them up will save you a ton of heartache and weird overflowing column issues and text mismatches etc