DRYing two very similar SQL conditional inserts

Posted on

Problem

I have two very similar SQL statements

INSERT INTO user_profile (user_id, setting_id, value)
    SELECT id, 18, true
    FROM users
        WHERE NOT EXISTS (
            SELECT user_id, setting_id FROM user_profile
            WHERE id=user_id AND setting_id=18);

INSERT INTO user_profile (user_id, setting_id, value)
    SELECT id, 16, true
    FROM users
        WHERE NOT EXISTS (
            SELECT user_id, setting_id FROM user_profile
            WHERE id=user_id AND setting_id=16);

I’m repeating everything except for the setting_id. Is there a way to combine these two statements?

Solution

You’ll want to create a stored procedure that takes your setting ID

    CREATE OR REPLACE FUNCTION InsertUserProfile(id INTEGER) 
RETURNS void AS $$
	BEGIN
	  INSERT  INTO user_profile
					( user_id ,
					  setting_id ,
					  value
					)
					SELECT  id ,
							id ,
							true
					FROM    users
					WHERE   NOT EXISTS ( SELECT user_id ,
												setting_id
										 FROM   user_profile
										 WHERE  id = id
												AND setting_id = @ID );
	END;
	$$ LANGUAGE plpgsql;

You’ll then want to call it like this:

SELECT usp_InsertUserProfile(16)

Leave a Reply

Your email address will not be published. Required fields are marked *