r/SQL • u/Puzzleheaded_Cow3298 • Jun 20 '26
MySQL How can I write cleaner, more maintainable SQL?
Basically, as the title says, I sometimes use CTEs, joins, window functions, and subqueries all in a single query.
I'm able to get the job done, but I don't think my queries are very efficient, and they're definitely not something that would impress an interviewer.
Is there any place where I can learn to write more readable and maintainable SQL code?
26
Upvotes
18
u/nl_dhh Jun 20 '26
Experience, mostly. It helps if you have a good understanding of the engine. Also having colleagues to learn from helps, but since you mentioned interviews, I guess that's out of the question now.
I noticed you tagged this post as MySQL. I dont have any resources for that, but if you're (also) interested in MS SQL, consider Brent Ozar's videos. I'm guessing there's a big overlap between MS SQL and MySQL, so you might find his basic courses useful, regardless of what engine you're working on.
10
u/Sexy_Koala_Juice DuckDB Jun 20 '26
What’s wrong with using all of those in a single query?
34
u/mrrichiet Jun 20 '26
I'll get downvoted for this but use CoPilot etc.
I've used SQL for decades but still struggle to get the query structure correct first time. CoPilot articulates the solution in such a clear way that it educates you and helps you see things more clearly, which helps when it comes to constructing future queries.
7
u/nidprez Jun 20 '26
readability > efficiency in 90% of the cases. If queries take longer than 5-10 minutes and you absolutely cant do anything else while waiting on them it may be useful to think about efficiency. Still if you take 1-2 days to shorten and 8 minute query to 3 minutes and you run that query only once per month, did you save money for the company?
Also efficiency is usually just smart indexing, partitioning, temp tables, and then more hacky stuff in your query or column orders etc depending on the DB.
Maintainable code for me is: comments and printing statements between part of your code, consistent formatting, readable table names and aliases, consistent tabbing, not using select * from, unless when your creating tables or printing output, use CTEs as much as possible unless you have a performance hit, I also like to number my CTEs...
13
u/Jazzlike_Drawing_139 Jun 20 '26 edited Jun 20 '26
Those things all have their place. Personally I prefer CTEs over subqueries where possible, so you can essentially declare the compiled sets of data you’ll be using in one place at the start.
Window functions are the best tool for lots of aggregation types.
When you talk about efficiency, I’m not sure if you mean:
If your main goal is code being readable and maintainable id focus on things like
3
u/Substantial_Egg_3603 Jun 20 '26
I troubleshoot, and peer review Coworkers SQL all the time. Most of the time its for SQL pass through for another tool. The below assumes you are very new to SQL.
Know your expected outcome before you begin writing your SQL. If you have an example record, use that record while you are creating your code. Cocky developers never do this, and it usually shows when reviewing or verifying output.
I mention these items due to the amount of contractors my company has hired of the years.
MOST IMPORTANT: find someone where you work who is a good developer and become their best friend.
Im tired of typing and its a Saturday morning, so that's all I got.
PS: ignore the haters, code is a lot like art, beauty is in the eye of the beholder.
2
u/alinroc SQL Server DBA Jun 20 '26 edited Jun 20 '26
And the problem with doing this is what, exactly? You write the query needed to get the results.
Why do you say that? Because of what the code looks like? Or because they bring a 64-core (wait, individual MySQL queries aren't multi-threaded, are they?), 1 TB server to a screeching halt for 15 minutes every hour? What metrics do you have that indicate your queries aren't efficient?
Want to impress me, your interviewer? Show me well-formatted, clean, consistent code that can be read and followed. Show me that you understand why you wrote the query the way you did. Even if it's not "optimal", if it got the correct results and you can walk me through why you wrote it that way, I'll keep listening.
2
u/PasghettiSquash Jun 20 '26
I think the answer to your question isn't really about your queries - I think it's "how would you setup your data warehouse." Imagine if you had 10 coworkers and you're all contributing to the same repo - if you are the decision maker, what rules are you putting in? No single letter aliases? No select * or select distinct? Trailing vs leading, etc. What about the table naming conventions?
Then you can use a linter and CI checks to ensure that's what happens - obviously this is probably too much work for any personal setup, but these are the sorts of things I'd never live without now. You can't really maximize optimization AND readability AND maintainability AND speed - but you can make thoughtful decisions once and never spend time thinking about that decision again.
2
u/TodosLosPomegranates Jun 21 '26
Comment your code. Practice DRY. Have a reason for everything. Clean up orphans.
3
u/bishnabob Jun 20 '26
I agree with the other posts - consistency is paramount. Develop a style - I favour lowercase keywords as it's less shouty, I always [ ] if I use 'as', I [ ] when column names are keywords (dbo.Calendar.Date I'm looking at you), and I tab things consistently.
My style isn't the same as other people's, but it's legible and easy to follow. Nothing worse than cobbled together code that mashes styles and takes me longer to read it.
1
u/TreeOaf Jun 20 '26
Consistency is a great way to maintain readable code.
Develop habits for format, alias, keywords, et cetera
If you’re writing queries against a set of tables over and over this will benefit you and your colleagues as things become quickly recognisable i.e. always writing
Finally, learn your functions.
1
u/wildjackalope Jun 20 '26
EXPLAIN and EXPLAIN ANALYZE will give you the optimizer. From there, you kind of have to go down the rabbit hole based on your particular data. There’s basic “rules of the road” but they’re going to apply differently in different use cases. As you go you’ll likely see the trends that point to best practices that you may not have been aware of.
1
u/NTrun08 Jun 20 '26
It’s hilarious watching your coworkers argue over the microsecond differences between the performance of the various methods, especially when depending on the actual query the performance might vary on which method is best. The real answer is “clean SQL” is 95% vibes of the person in charge.
1
u/ifatree Jun 20 '26
SQL isn't a flexible language where you have many different ways to do the same exact thing in the same way. very small changes to ordering of operators can make a huge difference to the query's performance, and performance is nearly always favored over readability. the part of SQL that needs to be clean and efficient is the query plan, not the layer you're operating on directly with code. and the query plans depend in part on the data, which means the same code can lead to multiple valid query plans that the engine has to decide which to use at which time based on the data it thinks will be returned with the specific parameters you're using each query. you often have to defensively use patterns that will force the optimal ordering based on you knowing the data better than SQL does. nobody cares what that looks like when it works.
1
u/Ok-Can-2775 Jun 20 '26
Does any one here use the order of operations when constructing a query? I believe is standard across SQL’s. For me it helped to understand when I was writing a query how I would approach solving the problem and being more efficient at it.
1
u/Kemper2290 Jun 20 '26
To compare my code to others I think looking at the other submissions after you complete a leet code helps alot. If you look at several of them you can kinda get an idea of what the standards is or areas to improve. Always take them with a grain of salt though
1
u/SingingTrainLover Jun 20 '26
Here's a great book on exactly that subject:
https://www.amazon.com/Refactoring-Legacy-T-SQL-Improved-Performance/dp/1484255801/ref=sr_1_1
Having everything in a single query forces the query optimizer to work with larger sets of data. If you can select smaller sets into temp tables with simple indexes, then join those temp tables together, the whole process is much faster overall.
1
u/Wayne_Kane Jun 20 '26
Use sqlfluff to lint and format the code
1
u/Sir-Squashie Jun 20 '26
In addition to the great advice you've seen here, I'd say to define your own traits and apply them to your code. Decide what your naming conventions are, preferred tabbing/layout etc is, figure out what you think looks "good" and just start doing it. Give it a while and you'll be able to tell where you've made a "mistake" and even tell your code from a line up
1
u/dittybopper_05H Jun 22 '26
Simplify, simplify, simplify.
Meaning, if there is a way to do something without the abstraction of using a view or writing a new function, do that instead.
A subquery that properly formatted is easier to understand than having to go back and find out what a function does, unless it's a very common function.
Views are to be avoided when you are looking at large numbers of records. They're fine if your query is just pulling one person's record (or whatever), but if you are looking at large numbers of records, they are a major performance hit.
Last year, I re-wrote an overnight process that used a view that used data from another view. It was originally written by someone who was apparently addicted to abstraction, but had no appreciation for performance, or the fact that someone would have to have to maintain it in the future.
That process took roughly 6 hours to run from start to finish.
I had to add a few fields, but I decided that the way it was written was an inefficient mess, so I re-wrote it from scratch using small individual SQL statements to populate a local table. When the table was fully populated the script would write out a data file to be transmitted to third party vendor software.
I cut the total run time down to under 2 minutes.
That's in addition to adding the fields requested and improving the accuracy of the data.
Even better, the script itself is in easy to understand "chunks". Each SQL statement does one or two things at most. Each statement has a comment line above it describing what it does. If someone decides that a change needs to be made, it's quick and easy to find the relevant part of the code and change it.
0
u/mikeblas Jun 20 '26
What do "cleaner", "readable", and "maintainable" specifically mean?
0
u/dumi_007 Jun 20 '26
There's a lot here
A lot of it seems like tension resolution
0
u/hermoum75 Jun 21 '26
Don't sweat combining CTEs, joins, and window functions—that's just a standard Tuesday in complex multi-database environments! To keep things clean, maintainable, and interview-ready:
-1
u/Infamous_Welder_4349 Jun 20 '26
Depending on how complex the request is try using WITH statements to break it out.
4
u/[deleted] Jun 20 '26
[removed] — view removed comment