Converting String 'Yyyy-Mm-Dd' to Date

I want to select from table where date column is equal to specific date which I sending as a string in format 'yyyy-mm-dd'. I need to convert that string and than to compare if I have that date in my table.

For now I am doing this:

  select *
  FROM table
  where CONVERT(char(10), date_column,126) = convert(char(10), '2016-10-28', 126)

date_column is a date type in table and I need to get it from table in this format 'yyyy-mm-dd' and because that I use 126 format. I am just not sure with the other part where I converting string which is already in that format and do I need to convert it because I don't know is it good to use this:

 CONVERT(varchar(10), date_column,126) = '2016-10-28'
3

3 Answers

You don't need to convert the column as well. In fact, you better not convert the column, because using functions on columns prevents sql server from using any indexes that might help the query plan on that column. Also, you are converting a string to char(10) - better just convert it to date:

where date_column = convert(date, '2016-10-28', 126)

Also, if you are using a datetime data type and not date, you need to check that the datetime value is between the date you pass to the next date.

4

You can convert string to date as follows using the CONVERT() function by giving a specific format of the input parameter

declare @date date
set @date = CONVERT(date, '2016-10-28', 126)
select @date

You can find the possible format parameter values for SQL Convert date function here

You do not need to do that. yyyy-MM-dd is the default format.

Please note that you need to take into account the time as well, if there's a timestamp in date_column. In that case you should write something like this

... WHERE date_column >= '2016-10-28 00:00:00' AND date_column < '2016-10-29 00:00:00'

... WHERE date_column BETWEEN '2016-10-28 00:00:00' and '2016-10-29 00:00:00'

As I just learned that (other than I thought) BETWEEN actually includes the end timestamp and thus is not equivalent to the above >= ... < approach.

This should use indexes properly as well.

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest