SQL date Statement - sql

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.

Related

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

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;

How to query for today's date and 7 days before data?

I'm using sql server 2008. How to query out a data which is the date is today and 7 days before today ?
Try this way:
select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE()
Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):
select * from tab
where DateCol between adddate(now(),-7) and now()

SQL to Return Dates for Selected Week Only

I'm writing a SQL query on a timesheet report. I need the report to return only the details for the week of the selected date.
E.g., if I pick 02/01/2012 (dd/MM/yyyy), then it should only return results between 02/01/2012 and 08/01/2012.
Thanks
SELECT
*
FROM
yourTable
WHERE
dateField >= #yourDate
AND dateField < #yourDate + 7
Some variations of SQL may have specific ways of adding 7 days to a datevalue. Such as...
- DateAdd(Day, 7, #date)
- DATE_ADD(#date, INTERVAL 7 DAYS)
- etc, etc
This option is both index friendly, and is resilient to database fields that have time parts as well as date parts.
You easiest is the equivalent of WEEK_OF_YEAR function in your SQL engine
But you can also use DATE_ADD
WHERE table.date BETWEEN target_date AND DATE_ADD(target_date,INTERVAL 7 DAY)
That depends on the database system you're using. MySQL has a function calles WEEK(), SQL Server can do something like this with the DATEPART() function:
MySQL:
SELECT
*
FROM table
WHERE WEEK(date_col) = WEEK('02/01/2012');
SQL SERVER:
SELECT
*
FROM table
WHERE DATEPART(WEEK, datecol) = DATEPART(WEEK,'02/01/2012');
SELECT * FROM table_name
WHERE date BETWEEN '1/02/2012' AND '1/08/2012';
you can replace the example date with your date and yourdate + 6.
Look here for example: http://www.roseindia.net/sql/sql-between-datetime.shtml

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;

sqlite select with condition on date

I have an sqlite table with Date of Birth. I would like to execute a query to select those records where the age is more than 30.
I have tried the following but it doesn't work:
select * from mytable where dob > '1/Jan/1980'
select * from mytable where dob > '1980-01-01'
Some thing like this could be used:
select dateofbirth from customer Where DateofBirth BETWEEN date('1004-01-01') AND date('1980-12-31');
select dateofbirth from customer where date(dateofbirth)>date('1980-12-01');
select * from customer where date(dateofbirth) < date('now','-30 years');
If you are using Sqlite V3.7.12 or greater
Dont use date(dateofbirth) just use dateofbirth. So your query would look like this:
select * from customer where dateofbirth < date('now','-30 years');
Using the magic docs at the sqlite website:
select * from mytable where dob < date('now','-30 years');
Try writing using the date format 'YYYY-MM-DD'
select * from mytable where dob > '1980-01-01'
A more programic way would be something like this:
select * from mytable where datediff(dob, now()) > 30
You'll Need to find specific syntax for sqlite.
select * from mytable where date(dob) > date('1980-01-10')
QLite3 has some cool new date functions. Per the docs site you can use date(), time(), datetime(), julianday(), unixepoch(), or strftime() depending on how your column data is formatted.
If you use strftime(), like my suggestion below, then you have to make sure that your column data is formatted the same way as your strftime string.
You would probably want something like:
SELECT * FROM mytable WHERE dob < strftime("%m/%d/%Y", 'now', '-30 year');
Note that you might have to change the format string here to match your own.
And here's some code that I use personally to give you a better idea of how powerful it is. It lets me get all the orders from the previous 3 months, not including this month.
SELECT * FROM orders WHERE SHIPPEDDATE > strftime('%m/%d/%Y', 'now', 'start of month', '-3 month');
The modifiers are very powerful with sqlite. The first string inside strftime() is the format, the 2nd string is when you want the date to start. 'Start of month' puts the day to 1, and '-3 month' goes back 3 months. So if I ran that today (08/03/2022), the date it uses would be 05/01/2022.