Reputation: 3293
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)?
Upvotes: 4
Views: 6620
Reputation: 181
This should work for SQL Query:
SELECT * FROM myTable
WHERE registerDate=YEAR(CURDATE())
Upvotes: 0
Reputation: 23992
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.
Upvotes: 6
Reputation: 10882
If by chance your flavor of sql is Microsoft TSql then this works:
SELECT * FROM Student Where datepart(yy,registerDate) = datepart(yy,GetDate())
Upvotes: 3