Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query where() date's year is $year

Tags:

sql

php

I store dates in my database in a column of date data type.

Let's say I have column date where I store data like this "2011-01-01", "2012-01-01", "2012-02-02" etc.

Now I need to make SQL that selects only rows where date is equal to 2012

SELECT * FROM table WHERE date=hasSomehowYearEqualTo=2012

What would be the query like?

like image 226
simPod Avatar asked Feb 08 '12 01:02

simPod


People also ask

How do I query a specific year in SQL?

Use SQL Server's YEAR() function if you want to get the year part from a date. This function takes only one argument – a date, in one of the date and time or date data types.

Can we use year function in where clause in SQL?

Use YEAR in where clause : Year « Date Time « SQL / MySQL %m returns the month (01-12), %d returns the day (01-31), and %Y returns the year in four digits. Get the payment number and the year of each penalty paid after 1980.

How do you check if date is in the current year SQL?

Just run these SQL queries one by one to get the specific element of your current date/time: Current year: SELECT date_part('year', (SELECT current_timestamp)); Current month: SELECT date_part('month', (SELECT current_timestamp)); Current day: SELECT date_part('day', (SELECT current_timestamp));

How do you check if the date is in YYYY MM DD format in SQL?

SQL has IsDate() function which is used to check the passed value is date or not of specified format, it returns 1(true) when the specified value is date otherwise it return 0(false).


2 Answers

Do NOT use YEAR(date) - this will calculate YEAR(date) for all dates, even for those, you never use. It will also make use of an index impossible - worst case on the DB layer.

Use

$sql="SELECT * FROM table WHERE `date` BETWEEN '$year-01-01' AND '$year-12-31'"

As a general rule: If you have the choice between a calculation on a constant and a calculation on a field, use the former.

like image 141
Eugen Rieck Avatar answered Sep 20 '22 18:09

Eugen Rieck


Check out the YEAR() docs function for MySQL

SELECT * FROM table WHERE YEAR(date)=2012
like image 21
Gabriele Petrioli Avatar answered Sep 20 '22 18:09

Gabriele Petrioli