compare dates in SQL query - sql

I would like to compare today's date with the dates I'm pulling from a DB and select entries accordingly. Those two formats do not match (I assume so) and I get an error. By the way, I am not sure what exact format myDate is stored in. Below is what I would essentially like to achieve.
WHERE (myDate > CURDATE())

you can format both the dates as below .
select * from mytable where convert(char(8), myDate,112) > convert(char(8),myDate,112)
code 112 will case them to be converted in YYYYMMDD format

select * from mytable where
convert(date, myDate) > convert(date,myDate)
in sql server.
or, if that does not work, try formatting the date with substring and then converting/casting/parsing.
select convert(date, (substring(myfield,9,2) + '/' + substring(myfield,6,2) + '/' + substring(myfield,1,4))) from mytable

Related

How to compare one field to another using LIKE

I want to so something like the following:
SELECT * FROM TABLE1
WHERE DATE1 LIKE DATE2 + '%'
However, when I try this I get the following error:
"5407: Invalid operation for DateTime or Interval"
I am working in Terdata SQL Assistant
You can't use like to compare dates, like is to compare string (varchar), then you can cast this dates to varchar or better way is cast both dates to the same format, for example:
SELECT * FROM TABLE1
WHERE convert(varchar, DATE1, 103) = convert(varchar, DATE2, 103)
This way cast dates to format: DD/MM/YYYY
If you wanna cast to another formats I let you a link that explain more types: https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
You could potentially just format the dates the same way to compare them.
WHERE FORMAT(DATE1, 'dd/mm/yyyy') = FORMAT(DATE2, 'dd/mm/yyyy')
date2 is less than 1 day later
where datediff(d,date1,date2) < 1
Since your using like ... you could mean within a day before or after.
abs(datediff(d,date1,date2)) < 1

Date Conversion in SQL

I have a date in following format in my DB.
10/16 - mm/yy
I need to convert it to:
October/16
Is this possible?
If it's not possible then please tell me why.
This is not a date, it's missing the day, it's a bad way to store year/month. There should be a 4 digit year to avoid confusion and the year should be listed first to enable correct sorting, e.g. '2016/10' or a numeric value 201610.
You can cast it to a DATE first and then use a FORMAT to disply only month/year:
set dateformat myd;
select format(cast(mystupidcolumn + '/1' as date), 'MMMM/yy')
Or SUBSTR the month part and use a CASE.
try this format,
SELECT DATENAME(month, DATEADD(month, #mydate-1, CAST('2008-01-01' AS datetime)))
You can display date by using this code
select datename(month, YourColumnName) + '/' + right(YEAR(YourColumnName),2)
FROM yourTableName
Simply change yourColumnName with name of your table column and yourTableName with name of table.
Yes you can, and it depend in what database you use to call date functions
If you column Datetime format
SQL server DATENAME(Month, GETDATE())
MySQL database MONTHNAME(now())
otherwise
convert it will in your choice at database or you code logic
split the value and lookup at month enum or fake the date to be accepted and complete date format like 01/10/16
so do something like SELECT DATENAME(Month, datecolumn) + '/' + YEAR (datecolumn)
also you can use instead of Year function DATEPART(yy,datecolumn)
the way you do it with format will look like
CONVERT(VARCHAR(11),GETDATE(),106)
but excepted to get first 3 char of month JUN

Oracle use LIKE '%' on DATE

My table myTab has the column startDate, which has the datatype "DATE". The data in this column are stored like dd.mm.yyyy.
Now I'm trying to get data with this query:
SELECT * FROM myTab WHERE startDate like '%01.2015"
Somehow it doesn't work and I don't know why.
Hope someone can help.
To make a text search on the date you would have to convert the date to text.
It's more efficient if you calculate the first and last date for what you want to find and get everything between them. That way it's done as numeric comparisons instead of a text pattern match, and it can make use of an index if there is one:
SELECT * FROM myTab WHERE startDate >= DATE '2015-01-01' AND startDate < DATE '2015-02-01'
SELECT * FROM myTab WHERE TO_CHAR(startDate,'dd.mm.yyyy') LIKE '%01.2015'
If the field type is "DATE" then the value isn't stored as a string, it's a number managed by Oracle, so you have to convert it to a string:
SELECT * FROM myTab WHERE to_char(startDate, 'MM.YYYY') = '01.2015';
You can also use date ranges in SQL queries:
SELECT * FROM myTab
WHERE startDate
BETWEEN to_date('01.01.2015', 'DD.MM.YYYY')
AND to_date('31.01.2015', 'DD.MM.YYYY');
Regarding you actual question "Somehow it doesn't work and I don't know why."
Oracle make an implicit conversion from DATE to VARHCAR2, however it uses the default NLS_DATE_FORMAT which is probably different to what you use in your query.
The data in this column are stored like dd.mm.yyyy.
Oracle does not store date in the format you see. It stores it internally in proprietary format in 7 bytes with each byte storing different components of the datetime value.
WHERE startDate like '%01.2015"
You are comparing a DATE with a STRING, which is pointless.
From performance point of view, you should use a date range condition so that if there is any regular INDEX on the date column, it would be used.
SELECT * FROM table_name WHERE date_column BETWEEN DATE '2015-01-01' AND DATE '2015-02-01'
To understand why a Date range condition is better in terms of performance, have a look at my answer here.
I solved my problem that way. Thank you for suggestions for improvements. Example in C#.
string dd, mm, aa, trc, data;
dd = nData.Text.Substring(0, 2);
mm = nData.Text.Substring(3, 2);
aa = nData.Text.Substring(6, 4);
trc = "-";
data = aa + trc + mm + trc + dd;
"Select * From bdPedidos Where Data Like '%" + data + "%'";
To provide a more detailed answer and address this https://stackoverflow.com/a/42429550/1267661 answer's issue.
In Oracle a column of type "date" is not a number nor a string, it's a "datetime" value with year, month, day, hour, minute and seconds.
The default time is always midnight "00:00:00"
The query:
Select * From bdPedidos Where Data Like '%" + data + "%'"
won't work in all circumstances because a date column is not a string, using "like" forces Oracle to do a conversion from date value to string value.
The string value may be year-month-day-time or month-day-year-time or day-month-year-time, that all depends how a particular Oracle instance has set the parameter NLS_DATE_FORMAT to show dates as strings.
The right way to cover all the possible times in a day is:
Select *
From bdPedidos
Where Data between to_date('" + data + " 00:00:00','yyyy-mm-dd hh24:mi:ss')
and to_date('" + data + " 23:59:59','yyyy-mm-dd hh24:mi:ss')
SELECT * FROM myTab WHERE startDate like '%-%-2015';
This will search for all dates in 2015. If this doesn't work, try:
SELECT * FROM myTab WHERE startDate like '%-%-15';

Sybase date comparison - Correct format?

I'm pretty new to Sybase and am writing a query to return results after a specified date, and also before a specified date. MM/DD/YYYY format
At the moment im doing..
SELECT *
From aTable
WHERE afterDate >= 08/07/2013
AND beforeDate <= 08/08/2013
I'm getting records back, but as I'm a Sybase newbie, I want to be sure Sybase is interpreting these dates correctly..
Their online doc is pretty bad for basic explanations on things like this!
Anyone able to confirm if what I have works, or does it need some formatting round the dates?
You'll need to convert the dates into DATETIME and tell sybase what the format is to be sure.
According to this documentation the code for MM/DD/YYYY is 101, so something like this:
SELECT *
FROM aTable
WHERE afterDate >= CONVERT(DATETIME,'08/07/2013',101)
AND beforeDate <= CONVERT(DATETIME,'08/08/2013',101)
You can see the difference by running the following select statements:
SELECT CONVERT(DATETIME,'08/07/2013',101) --MM/DD/YYYY (2013-08-07 00:00:00.000)
SELECT CONVERT(DATETIME,'08/07/2013',103) --DD/MM/YYYY (2013-07-08 00:00:00.000)
For any date-time field in sybase, instead of going through the convert function, there is a more direct approach.
SELECT *
From aTable
WHERE afterDate >= '2013-08-07'
AND beforeDate <= '2013-08-08'
The date has to be in the form 'YYYY-MM-DD'
If you want to add a time, it can be included along with the date. The date and the time have to be separated by a T.
Any date time field can be directly used using the format 'YYYY-MM-DDTHH:MM:SS'
Using the functions is too lengthy. Noone needs a bazooka to shoot a squirrel! :)
CAST( '2000-10-31' AS DATE )
will convert from text to date format....
I am assuming that your two fields (afterDate and beforeDate) are in Date format.
Your example would be:
SELECT *
From aTable
WHERE afterDate >= CAST( '08/07/2013' AS DATE )
AND beforeDate <= CAST( '08/08/2013' AS DATE )
Also, usually (but not always) a date range is on the SAME field. As I said, that is not true all the time and you may have a good reason for that.
The best approach is to use the ANSI standard which does not require any conversion: yyyymmdd (you can also include hh:mm:ss) for instance:
DateField1 >= "20150101" and DateFile1 <= "20150102"
You should decide which Input-Strings the user is going to use as parameter and then convert them and concatenate them like you want, unless it is Datetime it is not important which initial format it had, you can use it in a between-condition.
E. g. the user is from Europe and uses "DD.MM.YY" and "hh:mm" as an input parameter, I would convert and concatenate like this:
WHERE dateCol between convert(DATETIME,
convert(char(11),
convert(DATETIME, '01.06.14', 4), 16) || ' ' || '00:00', 8)
AND convert(DATETIME,
convert(char(11),
convert(DATETIME, '01.07.14', 4), 16) || ' ' || '16:00', 8)

How to change the date format

Table:
Dates (nvarchar)
==
23/02/2009 (dd/mm/yyyy)
24/02/2009
25/08/2009
28/12/2011
....
I want to change the date form like this (yyyymmdd)
Tried query
select cast(dates as datetime) from table1
Showing error
ЮArithemetic expression overflow
select Convert(char(10), dates, 112) from table1
Showing the same value 23/02/2009
The above query is not working.
Expected Output
20090232
20090224
20090825
20111228
...
How to make a query?
Use this article.
select CONVERT(varchar(8),CONVERT(datetime, '23/02/2009',103),112)
Try this simple query:
SELECT DATEPART(yyyy,dates)+DATEPART(m,dates)+DATEPART(d,dates) FROM table1
You can get more information on this link:
sql-server-dates
select convert(varchar, getdate(), 102)[Dates] from tablename
Take a look on this link: http://www.technoreader.com/SQL-Server-Date-Time-Format.aspx
Since these are stored as string data then you might as well just use the string functions to give you what you want.
First to give you a valid date
select
cast(SUBSTRING(dates,4,2) + '/' + left(dates,2) + '/' + right(dates,4) as datetime) NowItsADateTime
from DateTable
And second, what you asked for.
select right(dates,4) + SUBSTRING(dates,4,2) + left(dates,2) as YYYYMMDD
from DateTable