Mysql function to find the number of working days between two dates
Solve it fast? Finding working days between two dates in MySQL is a breeze. Use a recursive CTE to whip up dates and then COUNT those that aren't chilling out as weekends.
Snap this piece of code:
Redraft '2023-01-01'
and '2023-01-10'
to fit your time frame, toss in holiday checks (if you dare).
Constructing a MySQL function
Elevating your game? Ditch the simple solution and opt for a custom function. Similar to Excel but without needing the mouse is NETWORKDAYS(), a function to count workdays accounting for those sweet, sweet holidays.
Upgrading your function
Pitch your tent with MySQL, create a custom function, BusinessDaysBetweenDates
:
Hail it like a SQL Caesar:
Crafting a calendar table
Going holiday mad? Build a calendar table and list down when you can put your out-of-office reply on:
Tweak the function to peep into the Calendar
table when marking days.
Considering holidays
Hosting a holiday spirit, or just want some days off? Choreograph a subquery dance in your function:
Optimizing the robustness and accuracy
Aiming for the MVP of SQL scripts? Wrestle with edge cases to ensure your function doesn't trip up where start and end dates want a weekend getaway.
Battle of boundaries
Grit your teeth, it's validation time. If your dates bookend on weekends, let's fix them to weekdays.
Act as if it's always Friday on the end date.
Squeezing performance
Overwhelmed by huge date ranges? Chop it down. Temporary tables to stockpile intermediate results or nut and bolts of date evaluation.
Script testing
Earn bragging rights by check and balancing your functions. Hard day’s work calls for a testing nightcap.
Battle test your functions against real-world time frames, because you, my friend, are building heroes of functions!
Was this article helpful?