SQL: How to use 'LIKE' with a date 'between'? - sql

So, i´m trying to select rows between two dates.
In db, the dates also have time.
Therefor i need to use LIKE.
SQL
$query = "SELECT * FROM table WHERE date >= LIKE :selectedDateFrom AND <= LIKE :selectedDateTo";
$query_params = array(':selectedDateFrom' => $selectedDateFrom.="%", ':selectedDateTo' => $selectedDateTo.="%");
This one returns error!
How should it look like?

In db, the dates also have time.
Therefor i need to use LIKE.
No, you don't.
To select all date/times where the date component is between (from) and (to), inclusive, you can write it as
SELECT *
FROM table
WHERE date >= :selectedDateFrom
AND date < :selectedDateToPlusOne
(Note the < instead of <=, and set the second parameter to one day after the last day you want to include in your results.) This works even when the column includes times.

you can't use like with dates in SQL
SO use this:
$query = "SELECT * FROM table WHERE date >= :selectedDateFrom AND date <= :selectedDateTo";

You'd strip the time part from a datetime with DATE().
SELECT *
FROM mytable
WHERE date(mydate) >= :selectedDateFrom
AND date(mydate) <= :selectedDateTo;
Or with BETWEEN for better readability:
SELECT *
FROM mytable
WHERE date(mydate) BETWEEN :selectedDateFrom AND :selectedDateTo;

Related

SQL, LEFT operator on datetime

Is it possible to use the LEFT() operator in MSSQL on a datetime.
I'm asking because this is my db:
In a SQL query i want now to SELECT only this objects WHERE Rueckmeldetatum = a date in form like (2023-01-27) so my string comperable has no time just a date. But with this SQL Query I'm getting no results:
SELECT TOP (1000) [KNR]
,[Rueckmeldedatum]
FROM [Fertigung].[dbo].[Box1Auswertung]
WHERE LEFT(Rueckmeldedatum,10) ='2023-01-27'
But normally or what i want to get is the 20th entry from the picture.
You should cast the datetime to date, then compare to a date literal:
SELECT TOP (1000) [KNR], [Rueckmeldedatum]
FROM [Fertigung].[dbo].[Box1Auswertung]
WHERE CAST(Rueckmeldedatum AS date) = '20230127';
Or, better yet, use this sargable version:
SELECT TOP (1000) [KNR], [Rueckmeldedatum]
FROM [Fertigung].[dbo].[Box1Auswertung]
WHERE Rueckmeldedatum >= '20230127 00:00:00' AND
Rueckmeldedatum < '20230128';
You should use this instead of LEFT or casting, then, if the index is available, your query can use this:
SELECT TOP (1000) [KNR]
,[Rueckmeldedatum]
FROM [Fertigung].[dbo].[Box1Auswertung]
WHERE Rueckmeldedatum >= '2023-01-27' AND Rueckmeldedatum < DATEADD(DAY, 1, '2023-01-27')
Also, make your query from the application parameterized.

SQL Server DateTime and SQL

I am having trouble with the following simple query
SELECT * FROM users WHERE Created = '28/02/2013'
The issue is the column CREATED is a datetime datatype, so the query executes fine as long as the timestamp is 0:00:0, if the time stamp is set to say 12:00, then the query does not return a result set.
Any idea why?
Thanks
Because you are not specifying the time, so it assumes that you are doing:
SELECT * FROM users WHERE Created = '28/02/2013 00:00:00'
If you want the whole day, then you need a range of times:
SELECT *
FROM users
WHERE Created >= '20130228' AND Created < '20130301'
Also, please use non ambiguous format for dates ('YYYYMMDD') instead of other formats.
SELECT * FROM users WHERE CAST(Created AS DATE) = '28/02/2013'
will fix it, but be careful, it disables indexes
SELECT * FROM users WHERE Created BETWEEN '28/02/2013 00:00' AND '28/02/2013 23:59'
And this will use index
If you don't need to consider time: try to convert created field to date and then compare as;
SELECT * FROM users WHERE convert(date,Created) = '28/02/2013'
--this would be even better with iso date format (not culture specific)
SELECT * FROM users WHERE convert(date,Created) = '20130228' --yyyymmdd format
You have to convert the column into date and then compare
SELECT * FROM users WHERE CONVERT(VARCHAR(11), Created, 106) = '28 Feb 2013'

ignoring timestamp in WHERE clause when comparing to date

My table has records like these
23-MAY-11 11.40.39.000000 AM
The following query brings nothing
SELECT *
FROM my_table
WHERE tenant_pha = 'test'
AND create_date >= TO_DATE('05/10/2011','mm/dd/yyyy')
AND create_date <= TO_DATE('05/23/2011','mm/dd/yyyy')
However, the below query will bring data
SELECT *
FROM my_table
WHERE tenant_pha = 'test'
AND create_date >= TO_DATE('05/10/2011','mm/dd/yyyy')
AND create_date <= TO_DATE('05/24/2011','mm/dd/yyyy')
I think this is because create_date column is time stamp.
How can I change my query to bring the desired result ( I want to avoid doing functions on the left side columns because they will make the query long).
You are right about the timestamp. '05/23/2011' is the same as '05/23/2011 12:00 AM'.
To include the whole day I usually move my date up by a day. < '05/24/2011' will include all of 5/23.
or change to '05/23/2011 23:59:59'
You can use trunc() without problems, you only need to create a function based index.
If you create this index:
CREATE INDEX idx_trunc_date ON my_table (trunc(create_date));
then the following condition will make use of that index:
AND trunc(create_date) >= TO_DATE('05/10/2011','mm/dd/yyyy')

How to get one day ahead of a given date?

Suppose I have a date 2010-07-29. Now I would like to check the result of one day ahead. how to do that
For example,
SELECT *
from table
where date = date("2010-07-29")
How to do one day before without changing the string "2010-07-29"?
I searched and get some suggestion from web and I tried
SELECT *
from table
where date = (date("2010-07-29") - 1 Day)
but failed.
MySQL
SELECT *
FROM TABLE t
WHERE t.date BETWEEN DATE_SUB('2010-07-29', INTERVAL 1 DAY)
AND '2010-07-29'
Change DATE_SUB to DATE_ADD if you want to add a day (and reverse the BETWEEN parameters).
SQL Server
SELECT *
FROM TABLE t
WHERE t.date BETWEEN DATEADD(dd, -1, '2010-07-29')
AND '2010-07-29'
Oracle
SELECT *
FROM TABLE t
WHERE t.date BETWEEN TO_DATE('2010-07-29', 'YYYY-MM-DD') - 1
AND TO_DATE('2010-07-29', 'YYYY-MM-DD')
I used BETWEEN because the date column is likely DATETIME (on MySQL & SQL Server, vs DATE on Oracle), which includes the time portion so equals means the value has to equal exactly. These queries give you the span of a day.
If you're using Oracle, you can use the + and - operators to add a number of days to a date.
http://psoug.org/reference/date_func.html
Example:
SELECT SYSDATE + 1 FROM dual;
Will yield tomorrow's date.
If you're not using Oracle, please tell use what you ARE using so we can give better answers. This sort of thing depends on the database you are using. It will NOT be the same across different databases.
Depends of the DateTime Functions available on the RDBMS
For Mysql you can try:
mysql> SELECT DATE_ADD('1997-12-31',
-> INTERVAL 1 DAY);
mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);
-> '1997-12-02'
If youre using MSSQL, you're looking for DateAdd() I'm a little fuzzy on the syntax, but its something like:
Select * //not really, call out your columns
From [table]
Where date = DateAdd(dd, -1, "2010-07-29",)
Edit: This syntax should be correct: it has been updated in response to a comment.
I may have the specific parameters in the wrong order, but that should get you there.
In PL SQL : select sysdate+1 from dual;

SQL date Statement

I need some help figuring out and SQL Statement.
I know what I want I just cant express it.
Im using php, so it doesnt need to be exclusivly SQL, its to act as a filter.
Pseudo code
$query="SELECT * FROM MyTable WHERE 'TIS' is not older than 2 days or empty = ''$ORDER"; }
TIS in the name of the column in my table were I store dates in this format 03-12-09 (d,m,y).
The $ORDER is for ordering the values based on values from other fields not dates.
Im looking at
SELECT *
FROM orders
WHERE day_of_order >
(SELECT DATEADD(day,-30, (SELECT MAX(day_of_order) FROM orders)) AS "-30 Days");
But i dont quite think im on the rigth track with this.
Thanks
Try the following:
SELECT *
FROM MyTable
WHERE COALESCE(TIS, SYSDATE) > SYSDATE - INTERVAL '2' DAY
$ORDER
I don't know what database you're using - the above uses Oracle's method of dealing with time intervals. If you're using SQL Server the following should be close:
SELECT *
FROM MyTable
WHERE COALESCE(TIS, GETDATE()) > DATEADD(Day, -2, GETDATE())
$ORDER
In MySQL try this:
SELECT *
FROM MyTable
WHERE COALESCE(TIS, NOW()) > DATE_SUB(NOW(), INTERVAL 2 DAYS)
$ORDER
I hope this helps.
So, I was pretty lost in all this.
How did it got solved:
First I understood that the Statement I was using was not supported by MySql thanks to eligthment from Bob Jarvis.
_ Second In a comment by vincebowdren wich "strongly" adviced me to change the data type on that field to Date wich indeed I had not, it was a string.
It was pretty Dumb for me to try using SQL operations for Dates on a field that had String values.
So I just RTFM: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
and:
mysql> SELECT something FROM tbl_name
-> WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= date_col;
Then proceeded to change the field value to date.
and this is my perfectly working query:
$query="SELECT * FROM MyTable WHERE DATE_SUB(CURDATE(),INTERVAL 2 DAY) <= TIS OR TIS = 0000-00-00 $ORDER "; }
I would like to thank the posters for their aid.