I have a column (completeddate) that I need to do the following
select *
from orders
where completeddate > '01-01-2013'
The problem is the date in the field looks like this (below)
25-FEB-08 12.00.00.000000000 AM
The format of the column is this
TIMESTAMP(6)
How do I set up my query to return rows where the completeddate is greater than 01-01-2013
Try this
select *
from orders
where completeddate > CONVERT(DATETIME, '01-01-2013', 105)
105 for dd-MM-yyy
You haven't specified the DBMS you are using, but nearly all of them store dates as a number. The format that you are seeing is almost certainly the client's interpretation of the date and has nothing to do with how the date is actually stored.
Most DBMSes are able to translate standard string representations of dates into a numeric date value. The likely problem is that you aren't using a standard date format. You should either use '2013-01-01' or '01/01/2013'. In my experience, YYYY-MM-DD (ISO 8601 and RFC 3339) is the least ambiguious and most supported format. If you strongly prefer MM/DD/YYYY (a primarily North American representation) then you usually need to use backslashes.
You need to convert the string '01-01-2013' to a database date object before the comparison. Don't know what is the type of your database, but all databases shall provide a function for converting date objects to and from strings, you can have something like:
where completeddate > TO_DATE('01-01-2013', 'DD-MM-YYYY')
Hope this helps.
did you try this?
SELECT CAST(your_timestamp_field AS DATETIME) FROM orders WHERE completeddate > '2013-01-01'
Related
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.
I have the following data:
StartDate FinishDate Details
09/10/2013 11/10/2013 xxx
14/10/2013 13/10/2014 Taking a year off
Whilst editing this data I which to check the date ranges do not overlap.
I am running an SQL query from access via ado to do this; I am putting the dates entered into database format (ie 'mm/dd/yyyy'); This is the query I've got:
SELECT Count(*)
FROM MarkerAbsence
WHERE PerID = 718 AND
('10/09/2013' BETWEEN StartDate AND FinishDate OR
'10/11/2013' BETWEEN StartDate AND FinishDate)
If the data is valid, it should return zero records; however it doesnt it returns 1 (being the second listed record above) and therefore seems to be interpreting '10/11/2013' as dd/mm/yyyy instead of mm/dd/yyyy.
Yet if I do this in SMO:
DECLARE #datevar datetime2 = '31/12/2008';
SELECT #datevar;
I get:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
While
DECLARE #datevar datetime2 = '12/31/2008';
SELECT #datevar;
returns
2008-12-31 00:00:00.0000000
So why am I having this problem and how do I fix it?
If you're running a query using MS Access, you need to delimit dates with # symbols, i.e.: #12/31/2008#. If this won't work for whatever reason, it is best to use string dates in the 'yyyy-mm-dd' format, as it will be recognized and is unambiguous.
You're probably getting this problem as MS is a US company, and the US uses mm/dd/yyyy format, so MS has defaulted much of their older software to treat dates as being in this format if at all possible, whereas you're probably in a country that uses - and have your PC's locality set to use - dd/mm/yyy format. Since not all of MS' software follows this rule, you have this problem.
The solution is to use a string date format that is unambiguous, such as: yyyy-mm-dd, mmm/dd/yyyy, or dd/mmm/yyyy (where mmm returns a three-letter month such as Dec).
You are using dd/mm/yyyy formats for your date strings. By default, without an explicit conversion, SQL is expecting date strings in the mm/dd/yyyy or yyyy-mm-dd format. So either change your strings to match one of these formats or do this:
SELECT Count(*)
FROM MarkerAbsence
WHERE PerID = 718 AND
(CONVERT(DATETIME, '10/09/2013', 103) BETWEEN StartDate AND FinishDate OR
CONVERT(DATETIME, '10/11/2013', 103) BETWEEN StartDate AND FinishDate)
The task:
I need to count every record in a table that was added after 07/01/2011.
Info:
There is a column in the table "Date_added" which is formatted as varchar and contains dates in format mm/dd/yyyy.
What I've tried:
I tried the following query:
SELECT count(date_added) FROM Abatements_Doc WHERE date_added >= '07/01/2011'
Unfortunately it counted any date where the month was greater than 07 regardless of the year or day. I'm at a loss as to how I should format my query to get it to read the dates properly instead of by ascii sort. In my research I discovered the CAST and CONVERT options, but am not sure how to use them, or which one I should use if any. I'm extremely new to SQL, and want to make sure I don't mess up the data in the table. I just need to get the count as specified above without altering the data in the table in any way. Any help in this regard will be very much appreciated. Thanks in advance.
I didn't test. But try convert statement.
SELECT count(date_added)
FROM Abatements_Doc
WHERE convert(datetime,date_added,1) >= convert(datetime,'07/01/2011',1)
(1) don't use mm/dd/yyyy as your date format. Use a safe and unambiguous format; the only one I trust for DATETIME/SMALLDATETIME is YYYYMMDD.
(2) change the data type in your table to DATETIME/SMALLDATETIME/DATE depending on accuracy required. Then `WHERE date_added >= '20110701' will work just fine (and will use an index on that column, if one exists).
(3) if you can't change the data type, then the following will work just fine as well (though no index will be used):
WHERE CONVERT(DATETIME, date_added, 101) >= '20110701'
Varchar can't be compared, try changing your column to date type.
Convert both date_added column values and your target date to DATETIME and compare; as in:
SELECT COUNT(1)
FROM Abatements_Doc
WHERE (CONVERT(datetime, date_added, 101)) >= CONVERT('07/01/2011', date_added, 101))
Is there a way to convert a date to a string in Sqlite? For example I am trying to get the min date in Sqlite:
SELECT MIN(StartDate) AS MinDate FROM TableName
I know in SQL Server I would use the SQL below to accomplish what I am trying to do:
SELECT CONVERT(VARCHAR(10), MIN(StartDate), 101) AS MinDate FROM TableName
Thanks!
SQLite doesn't have a date type. What CURRENT_TIMESTAMP actually returns is a string in the format YYYY-MM-DD HH:MM:SS. The date/time formatting/calculation functions accept strings in this format, or alternatively, numbers, which are interpreted as Julian dates unless you use the 'unixepoch' modifier.
So, "converting a date to a string" depends on how you're storing your dates:
If you're storing them as Julian dates, use DATE(YourDateColumn).
If you're storing them as Unix times, use DATE(YourDateColumn, 'unixepoch').
If you're storing them as ISO 8601 strings, then, well you don't have to do anything. Unless you want a string in a different format, in which case you should use the STRFTIME function.
If you're storing them as some other string format, you really should consider using one of the supported formats so you can use the date/time functions.
In all three date formats, chronological order is the same as lexicographical order, so the MIN function works as expected.
try this!!
SELECT * FROM Table WHERE strftime('%Y-%m-%d',CreatedAt) BETWEEN '2014-10-07' AND '2014-10-17'
Try this:
SELECT MIN(DATE('your-date-here')) as MinDate FROM TableName
And make sure your-date-here follows a well understood format by SQLite (See the Time String. section in the documentation)
This should be easy
I have a date column on table A
SELECT * FROM TABLEA
WHERE DTE = '01/02/2010'
The problem is that this is deployed onto US servers and I have no control over the date as its an arg.
How can I tell SqlServer to treat this date as being in that format??
I gave tried this:
SELECT *
FROM TABLEA
WHERE DTE = CONVERT(VARCHAR(10), '01/01/2010' , 101) AS [DD/MM/YYYY]
Your last try was almost correct, but it should have been
SELECT * FROM TABLEA WHERE AS_OF_DATE = CONVERT(DATETIME, '01/01/2010', 101)
Use a safe format. For dates (without a time component), the safe format is YYYYMMDD, e.g. today is '20100209'.
For datetimes, the safe format is YYYY-MM-DD'T'HH:mm:SS, where 'T' is the literal T, so right now is '2010-02-09T11:10:30'.
(When I'm saying safe, I mean that SQL Server always, unambiguously, knows how to convert these strings into datetime values)
Check out this reference article: The ultimate guide to the datetime datatypes
EDIT: Specifically what Tibor says about SET DATEFORMAT & SET LANGUAGE, since you mention that you have no control over the input format.
Another option is a double conversion (check performance when used as criteria):
select strTempNo, dtmTempDateStart,
convert(varchar(10), Convert(datetime, dtmTempDateStart, 103), 126) As UTCDate
I use 103 here as the data is already in UTC format but this works as well (UTC ISO8601 is 126).
If your dates are known to be always in American format you have to use 101.
Alternatively use 112 (ISO "safe" format) and cut the first 8 characters out of the string.
Data sample: (Sorry, don't have an American date table available)
521002 2008-09-1500:00:00.000 2008-09-15
580195 2008-04-1500:00:00.000 2008-04-15
530058 2008-09-2200:00:00.000 2008-09-22
580194 2008-04-0200:00:00.000 2008-04-02
500897 2008-07-0100:00:00.000 2008-07-01
500966 2008-09-2300:00:00.000 2008-09-23