Q

SQL for five days ago, excluding weekends

I need the date which is five days before the current date. For business logic it should exclude Saturday and Sunday.

I need the date which is five days before the current date. For business logic it should exclude Saturday and...

Sunday.

For many situations involving business dates, the best solution is a calendar table. For example, see Difference between two dates using office hours (22 May, 2001).

Presumably holidays do not matter in this instance. Hard to imagine why they would not, when weekends do. But as they do not, we can apply a formula. To develop this formula, let's first explore all possibilities.

If today is Monday, then, counting backwards, we skip over Sunday and Saturday, so Friday is one, Thursday two, and so on, taking us to last Monday as "five days ago." Here the quotes around "five days ago" will mean excluding weekends, and represents the date we are after, not literally five days ago. We will see the distinction in a minute.

If today is Tuesday, then, counting backwards, Monday is one day ago, we skip over Sunday and Saturday, Friday is two, Thursday three, and so on, taking us to last Tuesday as "five days ago."

This pattern—"five days ago" is the same day of the week, a week ago—repeats for Wednesday, Thursday, and Friday.

On Saturday, the pattern breaks. On Saturday, five days ago is Monday. And on Sunday, five days ago is also Monday, since we don't count the Saturday.

To sum up our findings and express them as data:

```if today is     "5 days ago" is     subtract
Monday            Monday               7
Tuesday           Tuesday              7
Wednesday         Wednesday            7
Thursday          Thursday             7
Friday            Friday               7
Saturday          Monday               5
Sunday            Monday               6```

The total days (including weekend days) to subtract from today, to get to the "five days ago" date, is shown in the right column.

Let's say that we number the days of the week with Sunday=1, Monday=2, and so on, to Saturday=7. Listing these weekday numbers against the number of days to subtract, we get:

```if today is    weekday    subtract
Monday           2           7
Tuesday          3           7
Wednesday        4           7
Thursday         5           7
Friday           6           7
Saturday         7           5
Sunday           1           6```

Here's the formula:

`subtract = 7 - 2*(weekday/7) + (weekday-2)/7`

Remember, this is the number of days to subtract from today, in order to get to the "five days ago" date. In this formula, division is integer division (i.e., round down). Please don't ask me how this formula was discovered. Let's just say it was trial and error.

How would we use this formula in SQL? Here's an example using MySQL syntax:

```select distinct
cust.fname
, cust.lname
, cust.phone
from orders as o
inner
join customers as cust
on cust.id = orders.cust_id
where o.date_ordered =
date_sub( current_date
, interval
7 - 2 * floor(dayofweek(current_date)/7)
+ floor((dayofweek(current_date)-2)/7)
day )
and o.date_shipped is null```

This query returns customer contact information for customers with orders placed exactly "five days ago" which have not been shipped yet.

This was last published in July 2007

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

SearchDataManagement

• Cross-platform integration, data preparation process grows in cloud

While cloud computing may be convenient and more cost-effective for users, it can also lead to new challenges and requirements in...

• Graph data model cements tight relationships between data elements

Graph databases can help define and discover relationships between entities -- and offer increased flexibility and better ...

• Microsoft SQL Server 2016 relational DBMS overview

Microsoft SQL Server 2016 for Windows comes in four editions, with updates that include a new stretch database feature, Polybase,...

• Difficulties in hiring data scientists can waylay analytics efforts

Advanced analytics software provides a lot of functionality, but finding skilled data scientists who can use the available tools ...

• Business should work with IT to get self-service BI governance right

Self-service analytics is all about getting IT roadblocks out of the way of the business, but traditional tech teams can still ...

• Creative projects leave people guessing about future impact of AI

A push is underway to write creative AI algorithms that can engage in music, film and design projects. So far, they have ...

SearchSAP

• Hillarys Blinds speeds SAP S/4HANA upgrade with Panaya tool

Hillarys Blinds, a veteran of several SAP ECC upgrades, completed a move to SAP S/4HANA in just six months using the Panaya ...

• Charlotte Hornets build data warehouse with SAP HANA-based Phizzle

The Charlotte Hornets implemented Phizzle FanTracker, an SAP HANA-based platform, to consolidate fan records from many data ...

• Does SAP ONE Support Launchpad make SAP support any easier to use?

The new Fiori user experience makes it easier to access applications and support services, but product-specific support still ...

SearchSQLServer

• SQL Server on Linux signals Microsoft's changing development landscape

Expert Joey D'Antoni explains what SQL Server on Linux and the addition of Enterprise Edition features to Standard Edition say ...

• How to get the most out of virtual SQL Server with Microsoft Hyper-V

SQL Server is a CPU-intensive technology, which can make it tricky to run in a virtualized environment. Keep your SQL Server ...

• Microsoft previews SQL Server on Linux, opens features across editions

Microsoft looks to broaden the horizons of SQL Server, as it moves some Enterprise features to Standard Edition and issues the ...

TheServerSide

• Docker instances become the new norm and adoption goes mainstream

Many organizations use Docker instances for many reasons, although security, data storage and monolithic fears remain barriers to...

• How to turn your DevOps failures into ALM successes

Doing the right thing doesn't always mean you're doing things right. But don't fret, because short-term DevOps failures can mean ...

• From chatbots to IBM's Watson: How software deals with conversational language

The next big thing in software development is conquering the conversational language development hurdle. Here's how the big ...

SearchDataCenter

• Build a data center shutdown procedure to prepare for the worst

A data center shutdown checklist helps IT teams focus on backup, testing and system verification before pulling the plug and ...

• Telcos purge colocation data centers, open door to neutral connections

Enterprise customers in Verizon and CenturyLink's colocation data centers should expect better cloud and network connection ...

• IT slowly embraces composable infrastructure

If there will be a way to make an enterprise data center as efficient and optimized as cloud computing, composable infrastructure...

SearchContentManagement

• Microsoft brings its flavor of AI with Microsoft Cognitive Services

Microsoft Cognitive Services has a new array of APIs to make it easier to scan text, video and audio data and to bring ...

• Users prefer Office 365 suite collaboration features over SharePoint

Users don't want to jump through hoops, and they want applications to work on mobile devices. Those needs may kill traditional ...

• What new SharePoint features to expect in the next 12 months

Now that Microsoft is developing its SharePoint features, there are new feature rollouts all the time. Here's a rundown of the ...

SearchFinancialApplications

• Foot Locker seeks a good fit with Infor pre-employment assessment tool

Foot Locker is among a growing number of companies using cloud-based pre-hire assessment to screen job applicants for character ...

• Project planning for a new corporate performance management system

A corporate performance management system touches most aspects of any business. You need a carefully thought-out plan to ensure a...

• No one-size-fits-all strategy for cloud ERP software migration

Experts say a cloud ERP transition plan will vary according to a variety of factors, from company size to an organization's ...

Close