r/mysql • u/GamersPlane • Jun 04 '25
question When is denormalizing acceptable?
As I'm going through refactoring an old project, I'm noticing I'm making some subqueries many times across various queries. For example:
SELECT parentID forumID, COUNT(forumID) childCount
FROM forums
GROUP BY parentID
I've noticed I've made this subquery 6 times already, and because it's a subquery, I obviously can't index on it. So it got me thinking, should I add a new column childCount? Obviously, this would be denormalizing, but in the purpose of reducing query load. I know normalization is a difficult balance, and I'm trying to get an idea of when I should vs just do a subquery for the info.
2
Upvotes
3
u/VintageGriffin Jun 04 '25
If you can afford to edit every bit of code that touches that particular kind of content to keep the counters in sync, caching them that way is a perfectly valid reason to denormalize for speed/performance reasons.
Just be sure to actually count the number of items every time you update the counters rather than increment or decrement them by a fixed value, to save yourself from counters eventually getting out of sync.
1
u/johannes1234 Jun 05 '25 edited Jun 05 '25
The relevant question is: Is that what's making it slow?
Profile Our application, check which parts of the application are slow, which queries those are and then analyze the query performance (check execution plan / explain etc. for a start) if that thing seems to be the problem then optimize it.
If it's a hundred times in code it doesn't matter, if it is never executed in normal operation.
A simple start for analysis might also be:
SELECT * FROM statements_with_runtimes_in_95th_percentilethat gives you the queries taking the most time. You may even check your production system for that. (Assuming you are using MySQL, not a fork like MariaDB, which still doesn't have as detailed info, I think)1
u/Informal_Pace9237 Jun 05 '25
Not sure what made you decide indexes will not help a Table SubQuery.
1
u/Gargunok Jun 09 '25
If speed is really an issue a materialized view might be a good candidate and then you have the code encapsulated to update in line with the base data.
I would though be wondering why it is slow first
1
u/AmiAmigo Jun 05 '25
https://chatgpt.com/share/68414d91-fe00-800e-8fe3-5495ecaaf370
It’s completely fine. I normally do it for my own sanity
0
u/naturalizedcitizen Jun 04 '25
When you cannot change existing schema, then creating views can help. You can update the view as frequently as per business requirements