Filter by Dates in SQL - sql

I have a column in my table for dates (DateTime) and I am trying to create a WHERE clause that says, WHERE dates BETWEEN 12-11-2012 and 12-13-2012
A sample value of dates column = 2012-05-24 00:38:40.260
I want to say WHERE dates BETWEEN MM-DD-YYYY and MM-DD-YYYY.
I tried doing
WHERE dates BETWEEN ((convert(nvarchar(10), dates,110) = '2012-12-12') AND (convert(nvarchar(10), dates,110) = '2012-12-12'))
but doesn't seem to work. "Incorrect syntax near ="
Please help
EDIT:
Thanks for various options and description guys. Got it working with #RichardTheKiwi's options.

If your dates column does not contain time information, you could get away with:
WHERE dates BETWEEN '20121211' and '20121213'
However, given your dates column is actually datetime, you want this
WHERE dates >= '20121211'
AND dates < '20121214' -- i.e. 00:00 of the next day
Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:
WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'
Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.

WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))

Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.

Related

SQL, casting a string to date so I can use GETDATE()

I am using SQL Server Management Studio 18 against SQL Server 2016. I have some material that are in batches and those batches have expiration dates that are held as strings, but are basically in the format of 'yearmonthday', e.g. '20210312' for March 3rd, 2021. My goal is to only see material that is expiring after the current date. Whenever I try to CAST the expiration date column AS DATE within the WHERE clause, I get this error:
Conversion failed when converting date and/or time from character string
(or something similar when trying different methods).
So, right now my code looks like this:
SELECT MaterialColumn, BatchColumn, CAST(ExpirationColumn AS DATE)
FROM StockTable
WHERE CAST(ExpirationColumn AS DATE) > CAST(GETDATE() AS DATE)
If I don't do the WHERE clause, I know I can CAST the ExpirationColumn as DATE without issue, but when it's in the WHERE clause, I run into that error. Is there any way I can filter to see only the dates that I want?
You can use try_cast() instead:
SELECT MaterialColumn, BatchColumn, CAST(ExpirationColumn AS DATE)
FROM StockTable
WHERE TRY_CAST(ExpirationColumn AS DATE) > CAST(GETDATE() AS DATE);
You can also find the bad values:
SELECT ExpirationColumn
FROM StockTable
WHERE TRY_CAST(ExpirationColumn AS DATE) IS NULL AND ExpirationColumn IS NOT NULL;
It sounds like you might need to fix some data values.
Honestly, if your dates are all stored in the format yyyyMMdd then there's no need to convert. Instead use a varchar parameter, as (at least) a varchar in the format yyyyMMdd had the same sort order as a date.
As a result you just convert GETDATE to the right format:
WHERE Expiration > CONVERT(varchar(8), GETDATE(), 112)
Of course, this doesn't change my statements in the comment; fix your design, don't stores dates as a string but as a date (and time) data type.

count records in specific date format with SQL

i'm trying to define a rule that count rows where date format is dd/mm/yyyy and greater than a specific date in sql but i couldn't find the right function to use.
The second part is working : SELECT COUNT (*) FROM CUSTOMER WHERE DAT_0 >= '01/01/1995' but how could i specify the format too
In Standard SQL, the WHERE clause would look like:
WHERE DAT_0 >= DATE '1995-01-01'
Many databases would simply accept this without the DATE as well:
WHERE DAT_0 >= '1995-01-01'
In your comment DATE_0 is a date column
Therefore we can change it to any format as below using to_char then to_date
to_date(to_char(DATE_0,'yyyymmdd'),'yyyy-mm-dd')
When comparing you can try this, converting the date to_number, i find it very easy
to_number(to_char(DATE_0,'yyyymmdd')) > 19950101
if datatype of "DAT_0" is date or datetime or timestamp , they are recorded as a specific format specified by default datetime setting in your database engine , therefore you can't have multiple format inside the column , so there is no concern there

SQL Server clean up inconsistent dates

I have dates currently stored as varchar(1000) that are in inconsistent formats. I.e. yyyy-mm-dd and dd-mm-yyyy etc.
What query can I run to clean these up so they are in a consistent format, so I can convert the column datatype from varchar(1000) to date?
Thanks
This could get ugly if you have many different date formats, possibly including invalid data. One option would be to assign a new date column using a CASE expression to choose the correct format mask:
UPDATE yourTable
SET date_col = CASE WHEN date LIKE '[0-9]{2}-[0-9]{2}-[0-9]{4}'
THEN CONVERT(datetime, date, 105)
WHEN date LIKE '[0-9]{4}-[0-9]{2}-[0-9]{2}'
THEN CONVERT(datetime, date) END;
You may add conditions to the above CASE expression for other date formats.

T-SQL Dates using Convert() function?

I am bit confusing here?
declare #date1 datetime = '2016-01-21 14:10:47.183'
I want to convert '2016-01-21 14:10:47.183' To '21-01-2016'
when I tried: select convert(date,#date1,105)
I am getting: 2016-01-21
But with: select convert(varchar(10),#date1,105)
I am getting: 21-01-2016
Why I am not having same results with above code?
Why should I convert to varchar?
Thanks in advance
This is just presentation matter and should be done in application layer. If you cannot do it in application you could use FORMAT (SQL Server 2012+):
declare #date1 datetime = '2016-01-21 14:10:47.183'
SELECT FORMAT(#date1, 'dd-mm-yyyy');
LiveDemo
Why I am not having same results with above code?
select convert(date,#date1,105)
-- DATETIME -> DATE
-- vs
select convert(varchar(10),#date1,105)
-- DATETIME -> VARCHAR(10) using specific style
If you only to skip time part use SELECT CAST(#date1 AS DATE) and do not bother how it is presented. It is still DATE.
To sum up: in SQL query use DATE as date, in application display it with desired format.
The reason why is because once you put a value in a datetime column (or date or any of the other variations on date-time datatypes) in SQL Server. SQL Server ceases to think of that date as having any particular format. It translates it into numbers, and stores it that way internally.
So when you select a date from a date time column, SQL Server displays it in the default format that you have selected based on your environment/local settings.
If you want to display it in any other format, you have to first convert it to a string, because as far as SQL Server is concerned, dates don't have formats. They are just numbers. The 21st day of March is the 21st day of March, whether you write it as 3/21 or 21/3.
So when you try to convert a date to a date with a different format, SQL Server just ignores you because dates don't have formats. However, if you want to convert that date to a string, SQL Server will be happy to help you display that string in any format you like.
Hope this helps, but sounds like some further research into how SQL Server stores dates would help your understanding.

Between Date is not working in SQL SERVER

I have a very simple SQL which select data from a range of date. So, for example if I have,
SELECT ...... WHERE PV.[Time] BETWEEN '02/26/2014' AND '02/26/2014'
This SQL Select statement is not selecting the data in 02/26/2014. Please help
Your current statement BETWEEN '02/26/2014' AND '02/26/2014' has the same value on the left and right and so is equivalent to = '02/26/2014'.
This will only bring back rows at midnight on 26 Feb. Use
WHERE PV.[Time] >= '20140226' AND PV.[Time] < '20140227'
It's always preferable to use a non-dubious string format for dates (1/2/2000 can be interpreted as 01-feb-2000 or 02-jan-2000, depending on your local settings). I prefer the ISO format yyyymmdd or ODBC canonical yyyy-mm-dd and always use CONVERT to be explicit when handling dates. But this is not your problem :)
The problem with your query is that you are actually filtering dates BETWEEN '02/26/2014 00:00:00' AND '02/26/2014 00:00:00', thus you'll only get values at exactly the datetime. To get datetime values through whole day 02/26/2014 use the following:
SELECT ...
WHERE PV.[Time] >= '2014-02-26' AND PV.[Time] < dateadd(day, 1, '2014-02-26');