Skip to main content
Inspiring
April 20, 2010
Answered

Year in the where clause

  • April 20, 2010
  • 2 replies
  • 724 views

I need to get only this year's publications. Here's my where clause:

where pubdate = '2010'

and it generates an error.  How can I set the criteria to get only this year's results?

THansk,

Jenn

This topic has been closed for replies.
Correct answer BKBK

where pubdate = 2010


or

where pubdate = #year(now())#

2 replies

BKBK
Community Expert
BKBKCommunity ExpertCorrect answer
Community Expert
April 20, 2010

where pubdate = 2010


or

where pubdate = #year(now())#

Inspiring
April 20, 2010

Ok, if your code errors... make sure to post the error.  Also if you're posting SQL questions, make sure to post the datatype of the columns concerned.  And the DB system you're using.

I suspect your column is a date or timestamp or something?  If so, you cannot compare it to a string, you can only compare the same data types (on the whole... there are some exceptions there, but not relevant to your situation).

Also, if the date value is "2010-04-20" (ie: today), then it's not going to match "2010" is it: because those are two different things.

What you need to do is to consult your DB's docs, and find out if there's a function for extrsacting the year part of a date (in indeed your column is a date), so you can compare like-for-like.  The function name and how it works will be specific to your DB system.

--

Adam

Inspiring
April 20, 2010

In addition to Adam's answer, and assuming that the datatype is date or timestamp, using functions in the where clause are sometimes slower than using the actual fields.  For your specific example,

where datepart(year, YourDateField) = 2010

might not be as optimal as

where YourDateField >= 1 jan this year

and YourDateField < 1 jan next year

Plus, if YourDateField is indexed, you really don't want to use a function.

jenn1Author
Inspiring
April 20, 2010

Thank you all for answering my question!  I appreciate it!