Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Date Between Two Columns

Tags:

sql

I need a query in SQL.
If I have two columns STARTDATE and END_DATE.
I want to select a all rows where a date falls between these two dates.

e.g.: startdate = 1/1/2011 AND enddate = 2/2/2011.

like image 331
ConquistadorAravinth Avatar asked Aug 25 '11 12:08

ConquistadorAravinth


People also ask

How do I select data between two dates in SQL?

SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2005-02-28 21:00:00' AND '2008-12-25 00:00:00';

How do I find the difference between two date columns?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference.


2 Answers

SELECT * FROM table1 
WHERE '2011-01-01' BETWEEN table1.startdate AND table1.enddate

Replace the explicit date either with now() or a parameter or whatever.

If the enddate is not defined as NOT NULL you can do:

SELECT * FROM table1 
WHERE '2011-01-01' BETWEEN table1.startdate AND COALESCE(table1.enddate, NOW())

See: http://www.1keydata.com/sql/sql-coalesce.html

like image 58
Johan Avatar answered Oct 11 '22 18:10

Johan


Does this help you ?

select * 
from table 
where START_DATE < NOW() AND END_DATE > NOW()

Depending on the database, use CURRENT_TIMESTAMP() or TODAY()

like image 44
Jean-Charles Avatar answered Oct 11 '22 19:10

Jean-Charles