Phil Hong
Phil Hong

Reputation: 1

Proper use of having in SQL

I'm not entirely sure I'm understanding the constraints of using "having". Down below, I'm accessing the Stack Overflow database to see the most downvoted posts in 2015, but am having trouble extracting the year.

select
  Title, Body, Score
From
  Posts
order by
  Score
having
  extract(YEAR from CreationDate) = 2015
;

Upvotes: 0

Views: 47

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269753

You want to use where, not having:

select Title, Body, Score
From Posts
where extract(YEAR from CreationDate) = 2015
order by Score;

However, a better way to write the query is:

select Title, Body, Score
From Posts
where CreationDate >= '2015-01-01' and CreateDate < '2016-01-01'
order by Score;

This allows the query to use an index on CreationDate.

Upvotes: 1

Related Questions