SQL - Get result of current year only - mysql

How can I get the result of the current year using SQL?
I have a table that has a column date with the format yyyy-mm-dd.
Now, I want to do select query that only returns the current year result.
The pseudo code should be like:
select * from table where date is (current year dates)
The result should be as following:
id date
2 2015-01-01
3 2015-02-01
9 2015-01-01
6 2015-02-01
How can I do this?

Use YEAR() to get only the year of the dates you want to work with:
select * from table where YEAR(date) = YEAR(CURDATE())

Using WHERE YEAR(date) = YEAR(CURDATE()) is correct but it cannot use an index on column date if exists; if it doesn't exist it should.
A better solution is:
SELECT *
FROM tbl
WHERE `date` BETWEEN '2015-01-01' AND '2015-12-31'
The dates (first and last day of the year) need to be generated from the client code.

When I tried these answers on SQL server, I got an error saying curdate() was not a recognized function.
If you get the same error, using getdate() instead of curdate() should work!

--========= Get Current Year ===========
Select DATEPART(yyyy, GETDATE())

SELECT id, date FROM your_table WHERE YEAR( date ) = YEAR( CURDATE() )

SELECT
date
FROM
TABLE
WHERE
YEAR (date) = YEAR (CURDATE());

If the date field contains a time component, you want to include December 31 so you have to go to January 1 of the next year. You also don't have to use code to insert dates into the SQL. You can use the following
SELECT * FROM table
WHERE date BETWEEN MAKEDATE(YEAR(CURDATE()), 1) AND MAKEDATE(YEAR(CURDATE())+1, 1)
This will give you January 1st of the current year through January 1st at midnight of the following year.
As #Clockwork-Muse pointed out, if the date field does not contain a time component, you would want to exclude January 1 of the following year by using
WHERE date >= MAKEDATE(YEAR(CURDATE()), 1) AND date < MAKEDATE(YEAR(CURDATE())+1, 1)

You can do this using SQL DATE_FORMATE(). like below:
SELECT
date
FROM
TABLE
WHERE
DATE_FORMAT(date, '%Y') = YEAR (CURDATE());

SELECT [ID]
,[datefield]
FROM [targettable]
WHERE DATEPART(YYYY, [datefield]) = (SELECT TOP 1(MAX(DATEPART(YYYY, [datefield])))
FROM [targettable]
)
/*
This will find the newest records in the table regardless of how recent the last time data was entered.
To grab the oldest records from the table do this
SELECT [ID]
,[datefield]
FROM [targettable]
WHERE DATEPART(YYYY, [datefield]) = (SELECT TOP 1(MIN(DATEPART(YYYY, [datefield])))
FROM [targettable]
)
*/

Related

MYSQL: How to get rows till specific month's end from very start

I'm working on a project for a Fuel Pump. Here is my table for the records:
I want to display rows from very start (2019-07-03) till the end of the specific month (e.g 2019-09-29) . How could i do achieve this?
A simple WHERE clause will do the trick
SELECT id, date, total_amount, total_paid
FROM table
WHERE date <= LAST_DAY(CURDATE())
CURDATE() will return current date i.e. 2019-09-08
LAST_DAY() will return the last date of current month i.e. 2019-09-30
WHERE clause will return all rows with date <= 2019-09-30
Update
If you want to filter records based on user input which is month and year ( 2019-09 ) then either it can done by appending '-01' at scripting side or using CONCAT at MySQL level,
WHERE date <= LAST_DAY(CONCAT('2019-09', '-01'))
I think this will work. You can change dates accordingly.
Select *
From table
Where date>='2019-07-03' AND date<='2019-09-29'

Retrieve data of last month uploads

I'm trying to retrieve some data from a database using MySQL. I would like to SELECT just the records that I uploaded in the last month and not the previous ones. This script has to be dynamic : I mean that on 1st of February it should retrieve data from 1st of January to 1st of February and so on.
My table structure is really simple : the upload date is stored in the column 'reg_date' that is a TIMESTAMP type.
Does anyone know how to do this in a single query? Thanks!
This can all be done in a single SQL query using the CURDATE() and INTERVAL functions so no PHP date calculation is required.
SELECT *
FROM `TABLE`
WHERE `reg_date` BETWEEN CURDATE() - INTERVAL 1 MONTH AND CURDATE()
You can filter the data like so:
select *
from your_table
where reg_date between date_sub(curdate(), interval 1 month) and curdate()
just use this query:
select * from your_table_name where reg_date between '2017-03-01' and '2017-03-31';

Calculate difference between dates

The title might be a bit misleading, but what I want is:
SELECT * FROM table ORDER BY pid ASC
And in one of the columns I have a DATE(). I want to compare the current date (not time) and return how many days are left till that date. Let's say the date is 2013-04-20 and today's date is 2013-04-16 I don't want to get any data if it's < current date. If it is I want it returned in days.
I've been looking around here and I've found no way to do it, and I can't for the love of me figure it out.
If you're looking for the difference between two date you can use the GETDATE function in MS SQL
SELECT DATEDIFF(DD, DateOne, DateTwo) FROM TABLE
This will return the difference in number of days between the two dates.
If you only want rows where the date field is less than or equal to today's date you can use:
SELECT DATEDIFF(DD, DateField, GETDATE())
FROM TableName
WHERE DateField <= GETDATE()
If you're using MySQL you can use DATEDIFF()
SELECT
DATEDIFF(NOW(), date_column) AS days_diff
FROM
tablename
Get the difference between two dates (ANSI SQL)
select the_date_column - current_date as days_left
from the_table
where the_date_column - current_date <= 4;
SQLFiddle: http://sqlfiddle.com/#!12/3148d/1

Select data between December of previous year and November of current year, MySQL

I am trying to retrieve statistical data between December of the previous year and November of the current year. The date column of my table has the data type of date.
The following SQL works fine with the obvious problem that it only works if the year is manually changed. How would one accomplish the same with a dynamically changing year for this time period?
SELECT date, SUM(numCalls) AS callTotal FROM callstats_callData
WHERE date BETWEEN '2011-12-01' AND '2012-11-01'
GROUP BY date ORDER BY date
The data is being retrieved from a MySQL table by PHP.
UPDATE
The code below works but I was hoping to have an SQL based solution.
$date1 = (date("Y") - 1) . '12-01';
$date2 = date("Y") . '-11-01';
$fetchTotals = $this->contentDB->prepare("SELECT date, SUM(numCalls) AS callTotal FROM callstats_callData
WHERE date BETWEEN ? AND ?
GROUP BY date ORDER BY date");
$fetchTotals->execute(array($date1, $date2));
$totals = $fetchTotals->fetchAll();
Working Example
This is to retrieve the call data for the Total Calls chart here. The results need to be retrieved in a loop in order to display the total for each month in that period of time. This page is currently working properly using the PHP & MySQL code above, just hoping for an SQL based solution.
This gives you a bit of flexibility in selecting arbitrary month and day values for updated queries - as you set in your posted PHP code:
SELECT date, SUM(numCalls) AS callTotal
FROM callstats_callData
WHERE DATE(date)
BETWEEN CONCAT(YEAR(CURDATE())-1,'-12-01') AND CONCAT(YEAR(CURDATE()),'-11-01')
GROUP BY date ORDER BY date;
You can create a Stored Procedure with your above query and taking arguments startDate & endDate.
The sql function YEAR(GETDATE()) returns the current year. You can try to use it in your query.
You could do something like that:
SELECT
date, SUM(numCalls) AS callTotal
FROM
callstats_callData
WHERE
(MONTH(date) >= 12 AND YEAR(date) = (YEAR(NOW()) - 1)) OR
(YEAR(date) = YEAR(NOW()) AND MONTH(date) < 11);
GROUP BY
date
ORDER BY
date
EDIT:
Seeing your comment, I suppose the best way to do it would be:
SELECT
date, SUM(numCalls) AS callTotal
FROM
callstats_callData
WHERE
(MONTH(date) >= 12 AND YEAR(date) = (YEAR(NOW()) - 1)) OR
(YEAR(date) = YEAR(NOW()) AND MONTH(date) < 11);
GROUP BY
YEAR(date), MONTH(date)
ORDER BY
date

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'