Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres COUNT FILTER syntax error - why?

can someone find me why this query is producing a syntax error? This is a simple ad database, it has categories and ads in them. The query is getting a list of ad categories, plus counts how many ads and how many active ads it has, the latter meaning ads not older than 2 weeks. PostgreSQL says:

Syntax error at or near "(" LINE 5: FILTER(WHERE ads....^

The other COUNT works just fine. I don't get what's its problem with the FILTER clause. Thanks!

    $data = pg_query($dbconn, 'SELECT categories.id,
                                  categories.name,
                                  COUNT(ads.id) AS ads_count,
                                  COUNT(ads.id) 
                                      FILTER (WHERE ads.date > '.strtotime('-2 weeks').') 
                                      AS ads_active_count
                           FROM erpatak.ads_categories AS categories
                           LEFT JOIN erpatak.ads AS ads ON ads.category = categories.id'
                           .$filter.'
                           GROUP BY categories.id, categories.name
                           ORDER BY name 
                           OFFSET '.$offset.' 
                           LIMIT '.$maxcount);
like image 845
Tamás Polgár Avatar asked May 11 '26 07:05

Tamás Polgár


1 Answers

OK, I found the solution. As Kamil G. revealed to me, COUNT can't be FILTERed in version 9.1 which I have here. The solution is:

COUNT(CASE WHEN ads.date > '.strtotime('-2 weeks').' THEN 1 END) AS ads_active_count

like image 88
Tamás Polgár Avatar answered May 13 '26 04:05

Tamás Polgár