1

I'm starting with Postgress, and I need to make a query with four ids as params, these can be NULL, only the first is mandatory, so I'm trying to get a data list with data of every id. How can I check if id param IS NOT NULL inside a WHERE condition. I'll give you an example (not working)

CREATE OR REPLACE FUNCTION sp_lock(
    IN p_id_1 character varying, 
    IN p_id_2 character varying DEFAULT NULL, 
    IN p_id_3 character varying DEFAULT NULL, 
    IN p_id_4 character varying DEFAULT NULL)
RETURNS SETOF character varying AS
$BODY$
BEGIN 
    UPDATE stock
    SET lock = 1
    FROM  (
      SELECT s.id
      FROM  stock s
      WHERE
        (ls.id = p_id_1 or p_id_1 is null) OR
        (ls.id = p_id_2 or p_id_2 is null) OR
        (ls.id = p_id_3 or p_id_3 is null) OR
        (ls.id = p_id_4 or p_id_4 is null) AND
        ls.lock = 0
      FOR UPDATE OF s
    ) i
    WHERE i.id = stock.id;

Here I need to check first, if the param IS NOT NULL, and then concatenate to the condition, with OR exp.

2
  • What exactly is wrong with this query? Commented Sep 25, 2015 at 21:11
  • I'm not sure of what would happen if p_id_3 is null for example, can only ensure that p_id_1 will be come always. Commented Sep 25, 2015 at 21:17

1 Answer 1

1

Your can use in operator in the where condition

WHERE 
    s.id in (p_id_1, p_id_2, p_id_3, p_id_4) AND
    s.lock = 0;

Btw, you do not need a subquery:

UPDATE stock
SET lock = 1
WHERE
    id in (p_id_1, p_id_2, p_id_3, p_id_4) AND
    lock = 0;

does exactly the same but quicker.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.