Best Practices for Writing SQL Queries
Make your team happy once in a while
Dear reader, stay at least 30 seconds. Don’t destroy writers’ read ratio :)

It’s always easy to mess with SQL without proper guidelines.
Everyone has their habits to write SQL queries, just like any coding language you can end up confusing other team members so they cannot understand.
So, slowly and steadily people realize the the importance of following a set of good practices.
Below are some practices you can follow to make yourself better.
1. Write SQL keywords in capital letters. Writing SQL queries in capital, makes your code look more professional, clean, and readable.
2. Use table aliases with columns when you are joining multiple tables.
3. Never use select *, always mention the list of columns in the select clause. Using an asterisk sign in a query causes redundant consumption of the database engine’s resources because it will retrieve all table columns.
In particular, using SELECT * provokes consuming more network and disk resources.
4. Add useful comments wherever you write complex logic. But avoid too many comments.
5. Use joins instead of subqueries when possible for better performance.
6. Create CTEs instead of multiple sub-queries, it will make your query easy to read
7. Considering cardinality within GROUP BY can make it faster (try to consider a unique column first in the group by list)
8. Use EXISTS in place of IN wherever possible
9. Join tables using JOIN keywords instead of writing join condition in where clause for better readability.
10. Never use order by in sub queries, It will unnecessarily increase runtime.
11. If you know there are no duplicates in 2 tables, use UNION ALL instead of UNION for better performance.
12. Use WHERE instead of HAVING to define filters on non-aggregate fields
13. Avoid wildcards at the beginning of predicates (something like ‘%abc’ will cause a full table scan to get the results)
Anything else you want to add...💬You can Subscribe to me here for more such content. P.P.S.S. Put a ❤️ in the comments if this content resonates with you.
Cheers!






