I have a table with a varchar field called slldate. This field contains dates in this format:
2010-08-30
(YYYY-MM-DD)
Now I would like to select the records containing the current month using a mysql query.
Anyone?
as you used a char field instead a date field, you have to cast the value and then use the normal date functions. like
SELECT * FROM table WHERE MONTH(CAST(slidate as date)) = MONTH(NOW()) AND YEAR(CAST(slidate as date)) = YEAR(NOW())
Try this:
SELECT * FROM table_name WHERE MONTH(slldate) = date('m') AND YEAR(slldate) = date('Y');
I have a table with a varchar field called slldate. This field contains dates
Then you should change it to a date field. You (should) know it's the right thing to do.
The method below will work with your varchar strings - but can be simplified somewhat for dates.
Note that since your date strings are already big-endian, you don't need to cast them and loose the benefit of index optinmisation:
SELECT *
FROM yourtable
WHERE slldate >= CONCAT(DATE_FORMAT('%Y-%m-', NOW()),'01')
AND slldate < CONCAT(DATE_FORMAT('%Y-%m-', NOW() + INTERVAL 1 MONTH), '01')
SELECT * FROM table_name WHERE YEAR(savedate) = YEAR(CURDATE()) AND MONTH(savedate) = MONTH(CURDATE())
Related
I have some code with me:
$sql = "SELECT * FROM palash ORDER BY id DESC LIMIT 31";
I want the LIMIT 31 to be LIMIT END OF THE MONTH
Use the LAST_DAY() function.
Takes a date or datetime value and returns the corresponding value for
the last day of the month. Returns NULL if the argument is invalid.
mysql> SELECT LAST_DAY('2003-02-05');
-> '2003-02-28'
mysql> SELECT LAST_DAY('2004-02-05');
-> '2004-02-29'
mysql> SELECT LAST_DAY('2004-01-01 01:01:01');
-> '2004-01-31'
mysql> SELECT LAST_DAY('2003-03-32');
-> NULL
In your case do this:
SELECT *
FROM palash
WHERE your_date_column <= LAST_DAY(CURDATE())
ORDER BY id DESC
Avoid solutions like OlivierH's (no offense, Olivier). Functions applied on your columns make it impossible for MySQL to use an index.
You can limit to current month with this conditions :
SELECT *
FROM palash
WHERE MONTH(my_date_column) = MONTH(CURDATE())
AND YEAR(my_date_column) = YEAR(CURDATE())
You can then adjust it to get previous dates too.
EDIT / Other way : to stay close to your original idea and to still have a full SQL solution, you can get number of days in current month with LAST_DAY :
DAY(LAST_DAY(my_date_column))
Here is one way you can do it
CREATE TABLE [dbo].[Dates](
[DateColumn] [datetime] NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Dates]
([DateColumn])
VALUES
('2015-01-04 13:00:00'),
('2015-01-06 13:00:00'),
('2015-02-05 14:00:00')
GO
----Last Day of Current Month
Declare #LastDayOfCurrentMonth datetime = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
SELECT *
FROM Dates
Where DateColumn < #LastDayOfCurrentMonth
I do not understand how to get output from my sql table .
the table date is stored in int . for example date output from one row is like 1362157869 .
i want to show today orders in query :
php : $today = date("y-m-d", time());
query : SELECT * FROM test WHERE date = '$today'
but it didn't work . i also try this :
SELECT * FROM test WHERE date LIKE '$today'
Query without PHP var:
SELECT * FROM test WHERE date = DATE(NOW());
You are storing your date as a UNIXTIMESTAMP, so you have to convert it to DATETIME using FROM_UNIXTIME, and then you have to extract only the date part, ignoring the time, using the DATE() function:
SELECT * FROM test WHERE DATE(FROM_UNIXTIME(date)) = CURDATE()
Please see fiddle here. You can then extract yesterday records with something like this:
SELECT * FROM test WHERE DATE(FROM_UNIXTIME(date)) = CURDATE() - INTERVAL 1 DAY
Or a specific date with this:
SELECT * FROM test WHERE DATE(FROM_UNIXTIME(date)) = '2013-03-01'
To make use of an index
Assiming that your date column could contain not only the date part but also the time, you could also use this that will return all today records:
SELECT * FROM test WHERE date >= UNIX_TIMESTAMP(CURDATE())
and this for yesterday:
SELECT * FROM test WHERE date >= UNIX_TIMESTAMP(CURDATE() - INTERVAL 1 DAY)
AND date < UNIX_TIMESTAMP(CURDATE())
or this for a specific date:
SELECT * FROM test WHERE date >= UNIX_TIMESTAMP('2013-03-01')
AND date < UNIX_TIMESTAMP('2013-03-01' + INTERVAL 1 DAY)
Use PHP and MySQL. In my table, there is date field (datetime) recorded by NOW() sql function. Example value of data in this field is 2010-10-07 10:57:36. How can I SELECT all data which day-month-year is today. I try to use code as below:
SELECT * FROM table WHERE date=????
Try this:
SELECT * FROM table WHERE date > CURDATE();
CURDATE() will return the current date as 2011-10-07 which will be cast to 2011-10-07 00:00:00 when comparing datetimes to it.
Note that if you use DATE(date) = CURDATE() you will run a date conversion for every row in the table, which will be really bad for your perfomance if you have many rows and/or you need to run the query often. Also make sure you have an index on date, otherwise both methods will be even slower.
SELECT * FROM table where DATE(date)=CURDATE()
SELECT * FROM tableName WHERE DATE(fieldDate) = DATE(NOW());
The date_format function allows you to easily switch between various granularities:
Select everything from the same day:
select * from table
where date_format(date, '%Y-%m-%d') = date_format(now(), '%Y-%m-%d');
From the same month:
select * from table
where date_format(date, '%Y-%m') = date_format(now(), '%Y-%m');
From the same year:
select * from table
where date_format(date, '%Y') = date_format(now(), '%Y');
From the same hour:
select * from table
where date_format(date, '%Y-%m-%d %H') = date_format(now(), '%Y-%m-%d %H');
and so on.
Try this
SELECT * FROM table WHERE DATE(my_date)=DATE(now())
my_date -> column name
SET #day = '2017-12-12' ;
SELECT * FROM table WHERE dateColumn BETWEEN DATE(#day) AND DATE_ADD(DATE(#day), INTERVAL 1 DAY ) ;
use something like this it exactly works on my code(access database):
select * from Table t where t.column>=Date() and t.column< Date() + 1
use between.
select * from table date between '2010-10-06' and '2010-10-08';
I have a sql statement, i select a few items, but I need to make sure that the date i have saved is greater then the current date.
SELECT * FROM table WHERE column_date > current_date
How do I make the code over, working?
Column date is saved like this 0000-00-00 00:00:00 (usual save, in other words).
This is what I try to achieve: AND time > current_date OR time == NULL But it ain't working. The time column is currently 0000-00-00 00:00:00 which is NULL, right?
Or how can I do, it must be greater than or equal to 0000-00-00 00:00:00
If you are using MySQL, NOW() should do the trick.
SELECT * FROM table WHERE column_date > NOW()
If you want to eliminate the time value and just compare to date value, following could be used:
SELECT * FROM table WHERE column_date > CURDATE()
You could use the Mysql Function NOW():
SELECT * FROM table WHERE column_date > NOW()
As per this documentation article, 0000-00-00 is a "dummy date" that can be used instead of NULL, which means 0000-00-00 itself is not NULL.
Given that 0000-00-00 cannot be greater than any other date, you should use either a condition with OR:
SELECT * FROM table WHERE column_date > NOW() OR column_date = '0000-00-00'
or a union:
SELECT * FROM table WHERE column_date > NOW()
UNION ALL
SELECT * FROM table WHERE column_date = '0000-00-00'
Alternatively you could use a construct like this:
SELECT *
FROM table
WHERE IFNULL(NULLIF(column_name, '0000-00-00'), '9999-12-31') > NOW()
But that would probably prohibit the query from taking advantage of the index on column_date, if any.
I want to be able to fetch results from mysql with a statement like this:
SELECT *
FROM table
WHERE amount > 1000
But I want to fetch the result constrained to a certain a month and year (based on input from user)... I was trying like this:
SELECT *
FROM table
WHERE amount > 1000
AND dateStart = MONTH('$m')
...$m being a month but it gave error.
In that table, it actually have two dates: startDate and endDate but I am focusing on startDate. The input values would be month and year. How do I phrase the SQL statement that gets the results based on that month of that year?
You were close - got the comparison backwards (assuming startDate is a DATETIME or TIMESTAMP data type):
SELECT *
FROM table
WHERE amount > 1000
AND MONTH(dateStart) = {$m}
Caveats:
Mind that you are using mysql_escape_string or you risk SQL injection attacks.
Function calls on columns means that an index, if one exists, can not be used
Alternatives:
Because using functions on columns can't use indexes, a better approach would be to use BETWEEN and the STR_TO_DATE functions:
WHERE startdate BETWEEN STR_TO_DATE([start_date], [format])
AND STR_TO_DATE([end_date], [format])
See the documentation for formatting syntax.
Reference:
MONTH
YEAR
BETWEEN
STR_TO_DATE
Use the month() function.
select month(now());
Try this:
SELECT *
FROM table
WHERE amount > 1000 AND MONTH(dateStart) = MONTH('$m') AND YEAR(dateStart) = YEAR('$m')
E.g.
$date = sprintf("'%04d-%02d-01'", $year, $month);
$query = "
SELECT
x,y,dateStart
FROM
tablename
WHERE
AND amount > 1000
AND dateStart >= $date
AND dateStart < $date+Interval 1 month
";
mysql_query($query, ...
This will create a query like e.g.
WHERE
AND amount > 1000
AND dateStart >= '2010-01-01'
AND dateStart < '2010-01-01'+Interval 1 month
+ Interval 1 month is an alternative to date_add().
SELECT Date('2010-01-01'+Interval 1 month)-> 2010-02-01
SELECT Date('2010-12-01'+Interval 1 month)-> 2011-01-01
This way you always get the first day of the following month. The records you want must have a dateStart before that date but after/equal to the first day of the month (and year) you've passed to sprintf().
'2010-01-01'+Interval 1 month doesn't change between rows. MySQL will calculate the term only once and can utilize indices for the search.
Try this
SELECT *
FROM table
WHERE amount > 1000
AND MONTH(datestart)
GROUP BY EXTRACT(YEAR_MONTH FROM datestart)
Try this if(date field is text then convert this string to date):
SELECT * FROM `table_name` WHERE MONTH(STR_TO_DATE(date,'%d/%m/%Y'))='11'
//This will give month number MONTH(STR_TO_DATE(date,'%d/%m/%Y'))
//If its return 11 then its November
// Change date format with your date string format %d/%m/%Y
Works in: MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23
Day:
SELECT EXTRACT(DAY FROM "2017-06-15");
Month:
SELECT EXTRACT(MONTH FROM "2017-06-15");
Year:
SELECT EXTRACT(YEAR FROM "2017-06-15");