Sql Query, not retrieving correct values with CURDATE() function - mysql

I need to retrieve records from database where my 'dateOfTermination' value is equal to today's date.
I used the below query, but it won't show any results.
select * from user
where CRM_Status='pending' and dateOfTermination = DATE_ADD(CURDATE(), INTERVAL 1 DAY)
It will only work if the query is as below.
select * from user
where CRM_Status='pending' and dateOfTermination < DATE_ADD(CURDATE(), INTERVAL 1 DAY)
Is it because of an issue in date format?

My guess is that dateOfTermination has a time component. Try this:
select u.*
from user u
where u.CRM_Status = 'pending' and
u.dateOfTermination >= CURDATE() AND
u.dateOfTermination < DATE_ADD(CURDATE(), INTERVAL 1 DAY);
You can also express this as:
select u.*
from user u
where u.CRM_Status = 'pending' and
DATE(u.dateOfTermination) = DATE_ADD(CURDATE(), INTERVAL 1 DAY);
Actually, the semantics are slightly different -- but it is unclear what you really intend. The first version is "better" in the sense that it can better make use of indexes for performance.

You can use MySQL DATE_FORMAT function to get the date without the time component and then do the comparison. So the query should look like:
SELECT * FROM user
WHERE CRM_Status='pending' AND
DATE_FORMAT(dateOfTermination,'%d-%m-%Y')=DATE_FORMAT(DATE_ADD(CURDATE(),INTERVAL 1 DAY),'%d-%m-%Y');

Assuming that the time is the problem. Why not just keep it simple?
select * from user
where CRM_Status='pending'
and cast(dateOfTermination as date) = cast(GETDATE() as DATE)

Related

Get users that have payment due in one day sql

This is probably easy to do but I can't seem to get my head around it. I have a user table that has a next_payment DATETIME column which gets update every month. I would like a query to get all the users where their next_payment DATETIME is in one day from the current datetime.
I tried something like this but it also gets me users where their next_payment is due in like 15 minutes. Not good
SELECT * FROM users WHERE next_payment >= NOW() AND next_payment <= NOW() + INTERVAL 1 DAY
I also tried something like this but this doesn't work either as it gives me all users that had next_payment datetime like 2 or 3 months ago (Not good).
SELECT * FROM users WHERE next_payment <= NOW() + INTERVAL 1 DAY
Thanks in advance for any help
Need to Cast the datetime field to date so you can include all data within the period and use between
SELECT * FROM
users
WHERE
cast(next_payment as date)
between cast(NOW() as date)
AND cast(NOW() + INTERVAL 1 DAY as date)
DATEDIFF works fine in MySQL:
SELECT
*
FROM
users
WHERE
DATEDIFF(next_payment, NOW()) = 1
SQL Fiddle for this example.
I would use:
SELECT * FROM users
WHERE TIMESTAMPDIFF(HOUR,NOW(),next_payment) <= 24

Select current months records mysql from timestamp column

I have a mysql DB that has a TIMESTAMP field titled date. How can I select all fields where the month is the current month?
Thanks in advance!
UPDATE
A much better index-friendly way to query your data for a range of dates
SELECT id, FROM_UNIXTIME(timestampfield) timestamp
FROM table1
WHERE timestampfield >= UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH)
AND timestampfield < UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY);
Note: You don't apply any function to your column data, but rather do all necessary calculations on the right side of the conditions (which are constants and are evaluated only once post-execution). This way you allow MySQL to benefit from index(es) that you might have on the timestampfield column.
Original answer:
SELECT id, FROM_UNIXTIME(timestampfield) timestamp
FROM table1
WHERE MONTH(FROM_UNIXTIME(timestampfield)) = MONTH(CURDATE())
AND YEAR(FROM_UNIXTIME(timestampfield)) = YEAR(CURDATE())
Note: Although this query produces the correct results it effectively invalidates the proper usage of the index(es) that you might have on the timestampfield column (meaning MySQL will be forced to perform a fullscan)
Here is SQLFiddle demo
Use this query may this help you,
Query = "SELECT * FROM <table_name> WHERE MONTH(date_entered) = MONTH(CURDATE())";
In my opinion, the following is more readable than the accepted answer...
SELECT id, FROM_UNIXTIME(timestampfield) timestamp
FROM table1
WHERE timestampfield >= DATE_FORMAT(NOW(), '%Y-%m-01')
Note: This would select any records from the next month as well. That usually doesn't matter, because none have been created.
If you want indexes to be used, don't apply any function to the column:
SELECT *
FROM tableX
WHERE `date` >= UNIX_TIMESTAMP((LAST_DAY(NOW())+INTERVAL 1 DAY)-INTERVAL 1 MONTH)
AND `date` < UNIX_TIMESTAMP(LAST_DAY(NOW())+INTERVAL 1 DAY) ;
The functions used can be found in MySQL docs: Date and Time functions
try this
SELECT * FROM table WHERE month(data) = EXTRACT(month FROM (NOW()))
SELECT 'data of your choice '
FROM 'your table'
WHERE
MONTH'datecolumn'=MONTH(CURRENT_DATE )
replace text in ' ' with appropriate from your database
SELECT [columns]
FROM [the_table]
WHERE MONTH([date_column]) = MONTH(CURDATE())
Replace the text between [] (including the []) with your data.
The query below can benefit from the index and no functions applied to the timestamp field for where clause evaluation.
SELECT *
FROM TableName
WHERE TimestampField >=
(CURDATE() - INTERVAL (DAY(CURDATE())-1) DAY)
AND TimestampField <
LAST_DAY(CURDATE()) + INTERVAL 1 DAY;
If your timestamp field is time part is truncated, go for this one,
SELECT *
FROM TableName
WHERE TimestampField BETWEEN
(CURDATE() - INTERVAL (DAY(CURDATE())-1) DAY)
AND
LAST_DAY(CURDATE());
As of 2020, you can use BETWEEN to handle the query from the very beginning.
SELECT *
FROM [TABLE]
WHERE [DATE_FIELD]
BETWEEN
CAST('2020-30-01' AS DATE) AND CAST('2020-10-31' AS DATE);
I know is not the most "automatic" way, but from a SQL perspective it is very friendly and straightforward.
Source
https://www.techonthenet.com/mysql/between.php
Try this one it will work better because of the range. You don't need to calculate month and year for every row. It will slow the process. User range for better performance.
SELECT * FROM table WHERE columnName between DATE_FORMAT(current_date() ,'%Y-%m-01') and current_date();
SELECT
*
FROM
tableName
WHERE
EXTRACT(YEAR_MONTH FROM columnName) = EXTRACT(YEAR_MONTH FROM CURDATE())
I think in MySQL here is the simplest method which i have tried and works well, you want to select rows where timestampfield is in this month.
SELECT * FROM your_table
WHERE MONTH(timestampfield)=MONTH(CURRENT_DATE()) AND
YEAR(timestampfield)=YEAR(CURRENT_DATE());
the above will return all records that the timestampfield is this month in MySQL

sql telling how many days have passed(datediff)

I'm working on a project where I want to display data after 3 days have passed.
What I'm having an issue with is getting the current date dynamically in php/sql. I'm aware of how to get the current date in php, but I dont know how to compare that value to the date that I have in the sql database.
You can do that directly in SQL
select * from your_table
where date_column <= curdate() - interval 3 day
You can use an interval select to limit the records to within 3 days if the column you're checking istimestamp, date, or datetime.
select * from tablename where timestamp_column >= NOW() - INTERVAL 3 DAY
You can use DATEDIFF function to check for days.
SELECT *
FROM tablename
WHERE DATEDIFF(CURRENT_DATE(), datecol) >= 3;

mysql date_sub using a field as interval

I need help with mysql and date_sub(). I have a table call Activity
Activity(id,deadline,alert)
Activity(1,'2011-04-18','1 DAY');
Activity(2,'2011-04-13','1 MONTH');
Every row in A have an 'alert', this field indicate how time before the deadline an activity have to reported.
For example
On 2011-04-17 I have to report the activity with 'id' 1
On 2011-03-14 I have to report the activity with 'id' 2
I trying to use date_sub() functions, but I can't use a field as params of this function. Any idea how to fix this?
SELECT *
FROM `activities`
WHERE date_sub(`deadline`, INTERVAL alert) >= CURDATE();
Split the alert into 2 fields
Alert_count: integer
Alert_period: enum('hour','day','month','week')
And change the query like so:
SELECT *
FROM `activities`
WHERE CASE alert_period
WHEN 'hour' THEN date_sub(`deadline`, INTERVAL alert_count HOUR) >= CURDATE();
WHEN 'day' THEN date_sub(`deadline`, INTERVAL alert_count DAY) >= CURDATE();
...
END CASE
If the number of alerts is small, you could write out a case:
WHERE case
when alert = '1 DAY' then date_sub(`deadline`, INTERVAL 1 DAY)
when alert = '1 MONTH' then date_sub(`deadline`, INTERVAL 1 MONTH)
... etc ...
end >= CURDATE();
Although this solution will work it's not the most efficient way of storing this data because each time you query for this data MySQL must look at the interval value in every row, compute it against deadline date and then return you the answer.
If you were to compute this information just before you insert the data and store alert_date as a DATE column then (assuming you index it too) it'd be very fast for MySQL to find the rows with a query like:
SELECT id FROM activity WHERE alert=CURRENT_DATE();
even more efficient (it'd allow it to be query cached):
SELECT id FROM activity WHERE alert="2011-04-23";
Strings are not allowed after INTERVAL, you can convert your all alert limit to day on one column.
Activity(id,deadline,alert)
Activity(1,'2011-04-18','1');
Activity(2,'2011-04-13','30');
and use as:
SELECT *
FROM `activities`
WHERE date_sub(`deadline`, INTERVAL alert DAY) >= CURDATE();

Select mysql query between date?

How to select data from mysql table past date to current date? For example, Select data from 1 january 2009 until current date ??
My column "datetime" is in datetime date type. Please help, thanks
Edit:
If let say i want to get day per day data from 1 january 2009, how to write the query? Use count and between function?
select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()
or using >= and <= :
select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()
All the above works, and here is another way if you just want to number of days/time back rather a entering date
select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
You can use now() like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59) on the end date or you won't get any results from that day, i.e.:
This WILL include records from 2019-12-02:
SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'
This WON'T include records from 2019-12-02:
SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'