Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows within a date range in T-SQL

Tags:

date

tsql

I have a set of rows, each with a date value, and I need to select rows that fall within a specific date range. How can I do this?

select * from table where convert(int,date_created) between //what should go here?

I want to select between '20-10-2010' and '22-10-2010'.

It keeps complaining about string to date conversion.

like image 240
LocustHorde Avatar asked Jun 09 '11 10:06

LocustHorde


People also ask

How do I select a date range in SQL?

The date and time are collectively stored in a column using the datatype DATETIME2. Syntax: SELECT * FROM TABLE_NAME WHERE DATE_TIME_COLUMN BETWEEN 'STARTING_DATE_TIME' AND 'ENDING_DATE_TIME';

How do you select a date range?

In the calendar, click the desired start date, then click the end date. The selected days are highlighted. OR. Enter start and end dates in the Date Range fields.

How do I select only certain rows in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.


1 Answers

You need to use yyyymmdd which is the safest format for SQL Server

select * from table
where date_created BETWEEN '20101020' and '20101022'

Not sure why you had CONVERT to int there...

Note: if date_created has a time component that this fails because it assume midnight.

Edit:

To filter for the day 20 Oct 2010 to 22 Oct 2010 inclusive, if the date_created column has times, without applying a function to date_created:

where date_created >= '20101020' and date_created < '20101023'
like image 57
gbn Avatar answered Oct 18 '22 10:10

gbn