Q
Problem solve Get help with specific problems with your technologies, process and projects.

# Closest date before or after a given date

In your answer Selecting the latest order for a customer (March 15 2002), you said:

What's different this time is that you want the closest date to a specified date, not the latest date. This might mean closest either before or after which would require a DATEDIFF function and an ABS value -- but I'll assume you want the closest before the specified date. This is simpler, and allows the use of MAX() with an additional WHERE condition:

```select *
from Customers
, Orders
where Customers.ID = Orders.Cust_ID
and Orders.OrderDate =
( select max(OrderDate)
from Orders
where Cust_ID = Customers.ID
and OrderDate < somedate

)```

I actually do need to write a query to get the date that is closest to another date (closest either before or after). Can you provide more information on how the DATEDIFF and ABS functions will help, or even provide an example?

DATEDIFF and ABS are specific to Microsoft SQL Server and Access; other database systems will have similar functions. The basic strategy for this problem is to use a subquery which calculates the minimum absolute difference between the date value in the column and given date. The outer query then selects the row where the absolute difference is equal to the minimum.

```select TheDate
from TheTable
where abs(datediff('d',TheDate,somedate))
= ( select min(
abs(datediff('d',TheDate,somedate))
)
from TheTable )```

Note that this will return all dates that are closest to the given date; there could be more than one date that is the same number of days away.

This was last published in October 2002

## Content

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

#### Have a question for an expert?

Please add a title for your question

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

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

### 2 comments

Send me notifications when other members comment.
I am implementing the hotel booking functionality & for the date availability on calender I am facing the problem. I need the continuous date from table on which the date & availability column exist.
Cancel
In most cases I can select the date I need using a maxdate function. However, how can I get sql to choose between the max date and a lesser date? I am trying to pull a designated organization number by date, but those can vary by any future dated transactions.

Thanks,
Cancel

## SearchDataManagement

• ### Kubernetes gains momentum in big data implementation process

Big data vendors and users are looking to Kubernetes-managed containers to help accelerate system and application deployments and...

• ### IT, others focus efforts as GDPR implementation date looms

The EU's General Data Protection Regulation is meant to bring better data privacy to bear in the age of big data. How GDPR ...

• ### Streaming tool from StreamSets eyes data in motion for GDPR

StreamSets software for inspecting big data brings governance to data in motion. Such capabilities may find more use as the ...

## SearchBusinessAnalytics

• ### Rethinking analytics processes spurs enterprise innovation

By taking a fresh look at the makeup of their analytics organizations, enterprises can innovate their business models and take ...

• ### Diversified data sets for analytics deliver top results

Analytics teams should focus on data diversity to ensure that their projects deliver the most meaningful insights -- but they ...

• ### How to boost the value of BI in today's analytics landscape

Traditional BI reporting still gives businesses valuable information. But its value can be increased by incorporating it into a ...

## SearchSAP

• ### New leadership and redesign may spark SAP Community revival

SAP Community Network was once the best forum for SAP developers to share ideas, but user activity declined significantly. Can ...

• ### SAP Ariba Live focuses on procurement for purpose

SAP Ariba Live 2018 focused on the idea that businesses can use procurement technology to do good in the world; for example, by ...

• ### SAP debuts consumption-based pricing model for SAP Cloud

SAP Cloud Platform is now available as a consumption-based model, an alternative to the subscription model. SAP also updated the ...

## SearchSQLServer

• ### ObjectRocket launches Azure MongoDB service

Count ObjectRocket is among those pursuing Azure MongoDB deployments. This open source NoSQL database continues to find traction ...

• ### Microsoft SQL Operations Studio eases SQL Server admin tasks

SQL Operations Studio simplifies routine administration of SQL Server and Azure SQL databases, making database development and ...

• ### Meltdown and Spectre fixes eyed for SQL Server performance issues

Microsoft has responded to the Spectre and Meltdown chip vulnerabilities with patches and other fixes. But IT teams need to sort ...

## TheServerSide.com

• ### Rust and Python top list of most popular development languages

A new Stack Overflow survey of over 100,000 developers indicated Java and JavaScript are not as popular as they had been before. ...

• ### Stay ahead of Java security issues like SQL and LDAP injections

Java security best practices include validating input to prevent injection attacks and managing malicious JAR vulnerabilities.

• ### Why the Waterfall or Agile debate will be around forever

Which is the right methodology to use for your project: Waterfall or Agile? The industry may be at peak Agile, as the ...

## SearchDataCenter

• ### IBM cloud services to secure mainframes out to the edge

Big Blue will introduce IBM cloud services that use blockchain, containers and its z14 mainframes to deliver improved security ...

• ### Four disadvantages of hyper-converged infrastructure systems

Problems with scalability and unexpected licensing costs can create problems for organizations that deploy hyper-converged ...

• ### IBM Power9 servers seek market inroads to AI, cloud

IBM follows up its first Power9 server with a raft of systems designed to appeal to a wider array of markets -- most notably, AI ...

## SearchContentManagement

• ### Scrivito unveils serverless CMS product

By building the CMS with ReactJS, Scrivito gained attraction with development community, according to an analyst.

• ### Content personalization tools sharpen focus on customers

Content personalization isn't new; Amazon weaponized it, and Jeff Bezos is the world's richest man. New tools are putting it ...

• ### Leading brands see the need for personalized content

Content personalization continues to expand within companies as maturing technologies make it a viable marketing option for ...

## SearchHRSoftware

• ### Oracle HCM Cloud gets 'big' upgrade

Oracle is bringing consumerlike approaches to its HCM cloud applications. That includes using virtual assistants and intelligent ...

• ### Why the talent management revolution pivots on AI for HR

In this Q&A, HR analyst Jeanne Meister explains how AI will transform the way companies deal with talent and how HR departments ...

• ### Blockchain in HR remains in beta, outlook uncertain

Blockchain in HR verification is getting interest from universities, vendors and startups. There are powerful forces driving its ...

Close