Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to run a store procedure/function on my database that shows all the users with giftlists < 5. I get an error "syntax error at or near IF" I've run the SQL statements separately and it works fine.

--function counts the number of giftlists per user
--and put their names into a new table

CREATE OR REPLACE FUNCTION foo()
  RETURNS TABLE(users_id users.users_id%TYPE, first_name users.first_name%TYPE, last_name      users.last_name%TYPE) AS
$func$
BEGIN

 -- if number of giftlists < 5
 IF(SELECT gift_lists.users_id, COUNT (gift_lists.gift_lists_id) as number_giftlists < 5    FROM gift_lists LEFT  JOIN users ON gift_lists.users_id =
  users.users_id GROUP BY gift_lists.users_id)
  RETURN QUERY
  SELECT v.users_id, v.first_name, v.last_name 
  FROM   my_view v;
ELSE
  RETURN QUERY
  SELECT v.users_id, v.first_name, v.last_name 
  FROM   my_view v;
END IF;
END
$func$  LANGUAGE sql STABLE;
share|improve this question
    
Just leave it out? (the IF and the ELSE block contain the same query) –  wildplasser Mar 23 '14 at 15:47
2  
Your if doesn't make sense. It has a group by, suggesting that it will return multiple rows, but it is in a context where only a scalar subquery can be used. –  Gordon Linoff Mar 23 '14 at 16:16
1  
IF ... THEN ... ELSE ... END IF; <- you are missing THEN –  Buella Gábor Mar 23 '14 at 18:06

1 Answer 1

You can't use IF at the top level in standard SQL, or in PostgreSQL's SQL dialect.

Use CASE .. WHEN ... THEN ... END instead, or use the PL/PgSQL language. PL/PgSQL allows you to use IF statements.

Separately, this:

 COUNT (gift_lists.gift_lists_id) as number_giftlists < 5

makes no sense. I think you mean:

SELECT
  gift_lists.users_id,
  COUNT (gift_lists.gift_lists_id) as number_giftlists
FROM gift_lists 
  LEFT  JOIN users ON gift_lists.users_id = users.users_id 
GROUP BY gift_lists.users_id
HAVING COUNT (gift_lists.gift_lists_id) < 5
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.