How to compare current date to given date in MySQL - sql

How to compare current date to given date in MySQL I am using like that code but it's not working.
<%
rs=st.executeQuery("select approcode,approemail,appromon,approvemon,approtue,approvetue,approwed,approvewed,approthr,approvethr,approfri,approvefri,approsat,approvesat,commen,months,SUM(nol) from `pushkalit`.`approval`WHERE (CONVERT( `approcode` USING utf8 ) LIKE '%"+user+"%') AND appromon=DATE(now()) OR approtue=DATE(now()) OR approwed=DATE(now()) ");
// i have given in mysql, appromon varchar(30).....so on dateformat have dd/MM/yyyy
%>

You can compare it like
DATE(NOW()) = DATE(duedate)
Will compare only the date part.

you should try this to simple code asL:
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())

See DATE_FORMAT()
SELECT
approcode, approemail, appromon, approvemon, approtue,approvetue, approwed, approvewed, approthr, approvethr, approfri, approvefri, approsat, approvesat, commen, months, SUM(nol)
FROM `pushkalit`.`approval`
WHERE (CONVERT(`approcode` USING utf8) LIKE '%"+user+"%')
AND ( appromon = DATE_FORMAT(NOW(), "%d/%m/%Y")
OR approtue = DATE_FORMAT(NOW(), "%d/%m/%Y")
OR approwed = DATE_FORMAT(NOW(), "%d/%m/%Y") )
Note that i inserted parens around your OR conditions, because i think this is actually what you intended to query.

Related

run this query from oacle in postgresql?

I can not convert this query from oracle to posgresql. Any help would be appreciated.
Select tdcollid, tddate, tdentry, tdlng, tdlat, tdvpid
From Tracking where Tdcollid = 'jperez'
And Trunc(Tddate) = Trunc(To_Date('14-DEC-16','yyyy-MM-DD'))
order by Tddate
You can do:
Select tdcollid, tddate, tdentry, tdlng, tdlat, tdvpid
From Tracking
where Tdcollid = 'jperez' And
ttdate >= '2016-12-14'::date and
ttdate < '2016-12-14'::date + interval '1 day'
order by Tddate;
Note that the date comparisons are arranged so they can use an index (if appropriate). You can use the same logic as ttdate::date = '2016-12-14'::date if this is not a concern.
Try something like this:
SELECT tdcollid, tddate, tdentry, tdlng, tdlat, tdvpid
FROM tracking
WHERE tdcollid = 'jperez'
AND tddate::date = '2016-12-14'::date
ORDER BY tddate
If tddate is a timestamp, casting it to date with ::date will do the same as Oracle's TRUNC(timestamp). Also date constants should be preferably in ISO-8601 format.

Handling Oracle Date type with Doctrine DBAL

I have an already existing an working Oracle SQL that compares two dates:
SELECT * FROM table1 WHERE startDate <= TO_DATE(:startDate, 'YYYY-MM-DD');
$startDate = DateTime::createFromFormat('Ymd', 20160108);
As I said, this works fine.
I am trying to generate this query (or one that has the same results) with Doctrine's Query Builder, but I can't get it to work. This is what I did so far:
$startDate = DateTime::createFromFormat('!Ymd', 20160108);
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder->select('*');
$queryBuilder->from('table1');
$queryBuilder->where('startDate <= ' . $queryBuilder->createNamedParameter($startDate, \Doctrine\DBAL\Types\Type::DATETIME));
The above produces this output:
SELECT * FROM table1 WHERE startDate <= :dcValue1;
(:dcValue = '2016-01-08 00:00:00')
And Oracle complains with ORA-01861.
On an SQLite platform, this works fine. Any idea on how to this properly so that it works on both platforms?
when casting a character string to date it must match the NLS date format, or be explicitely formatted. If your code must run on a DB where you cannot be sure what the default session format for dates will be, be explicit. As a general rule, I'd say always be explicit!
SELECT * from table1 where start_Date <= TO_DATE(:dcValue1,'yyyy-mm-dd hh24:mi:ss');
Within your query builder, try something like this, although you will need to escape the single quotes in the format mask. I believe in DBAL that is done by doubling up the quote, but you will need to verify that :
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder->select('*');
$queryBuilder->from('table1');
$queryBuilder->where('startDate <= TO_DATE(' . $queryBuilder->createNamedParameter($startDate, \Doctrine\DBAL\Types\Type::DATETIME) . ' ,''yyyy-mm-dd hh24:mi:ss'')');
Little late to the party,
I am assuming $startDate is a valid Date Object.
$startDate = $startDate->format('d-M-y h:i:s');
$queryBuilder->where('startDate <= ' . $startDate);
Hope this helps some one.
Thanks.

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;

Getting only day and month from a date field

I have a set of dates that are in the format DD-MMM-YYYY. I need to be able to compare dates by using only the DD-MMM part of the date, since the year isn't important.
How would I achieve this?
I have tried reading up on the DATEPART function (edit: which evidently wouldn't work) but I can only theoretically get that to return either the DD or the MMM parts, not both of them at once.
Edit: added oracle tag. Sorry.
Example of date field: 01-MAR-1994
If your column is of type DATE then it doesn't have a format.
If I understand you right, then you want to view the mon-dd part only, so you need to convert it with TO_CHAR function,
i.e.:
select to_char(your_date_column, 'mon-dd') from your_table
Convert your dates using the following format, it will only month and the date part. You have to replace getdate() with you date fields.:
select convert(varchar(5),getdate(),110)
Assuming that you are using SQL Server or Oracle since you attempted using DATEPART, you can just get the day and month using the DAY() and MONTH() functions. Assuming, again, that the dates you are comparing are in two different tables, it would look similar to this:
SELECT MONTH(t1.date), DAY(t2.date)
FROM table AS t1
INNER JOIN table2 AS t2
ON t1.key = t2.key
WHERE MONTH(t1.date) = MONTH(t2.date)
AND DAY(t1.date) = DAY(t2.date)
EDIT: If you are just comparing rows in the same table, you only need a very simple query.
SQLFiddle
select id, TO_CHAR(most_recent, 'mon-dd')
from (
select id, MAX(date1) AS most_recent
from table1
group by id
)
You can also combine month and day into one integer:
EXTRACT(MONTH FROM datecol) * 100 + EXTRACT(DAY FROM datecol) AS MonthDay
Then it's easier to sort and compare.
select FORMAT(yourcoulmn_name, 'dd/MM') from table
This should do the trick
`select CONVERT(varchar(7),datetime_column,100) from your_table`
date_default_timezone_set("Asia/Kolkata");
$m = date("m");//Month
$d = date("d");//Day
$sql = "SELECT * FROM contactdata WHERE MONTH(date) = '$m' AND DAY(date) = '$d' ";
only checks day and month and returns today, day and month from database
SELECT LEFT(REPLACE(CONVERT(varchar(10),GETDATE()-1,3),'/',''),4)
WOuld this work for you?
FROMAT(DATETIME, 'dd-MMM') = FROMAT(DATETIME, 'dd-MMM') use any format you want

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.