Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select if Date column is as same as current year

Tags:

sql

This is my Student table

Id(int) | Name(varchar) | registerDate(Date)
1         John            2012-01-01

How can I write the appropriate query to check if the person's registerDate value is as same as current year (2012)?

like image 797
Cute Bear Avatar asked Dec 06 '22 15:12

Cute Bear


2 Answers

SELECT *
FROM Student
WHERE YEAR(registerDate) = YEAR(getdate())
like image 181
Taryn Avatar answered Dec 15 '22 00:12

Taryn


The most direct solution would be to use the YEAR or DATEPART function in whatever flavor of SQL you're using. This will probably meet your needs but keep in mind that this approach does not allow you to use an index if you're searching the table for matches. In this case, it would be more efficient to use the BETWEEN operator.

e.g.

SELECT id, name, registerDate 
FROM Student 
WHERE registerDate BETWEEN 2012-01-01 and 2012-12-31

How you would generate the first and last day of the current year will vary by SQL flavor.

Because you're using a range, and index can be utilized. If you were using a function to calculate the year for each row, it would need to be computed for each row in the table instead of seeking directly to the relevant rows.

like image 23
Code Magician Avatar answered Dec 14 '22 22:12

Code Magician