1

I am creating a function where I want to check if a user exists in my users table before inserting a message into my messages table.

SELECT user_id from users WHERE username = 'user1'

If the user exists, the query returns the user_id and my second query uses the user_id to insert a new message into my "messages" table.

user_id would be used in the recipient_id parameter for the query below:

INSERT INTO messages(thread_id, date_posted, subject, body, creator_username, 
    creator_id, is_root, recipient_username, recipient_id, recipient_read)
    VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)

If both queries succeed, the function would return any identifer true/false/null/ or "Some sort of string" so that I can process it in node. And if the first query fails and it can't find a user with the username "user1" it would skip the second query and then return another identifier so I can process the query result. How would I go upon doing this?

1 Answer 1

1

You can do this in one query, using INSERT... SELECT:

INSERT INTO messages(thread_id, date_posted, subject, body, creator_username, 
    creator_id, is_root, recipient_username, recipient_id, recipient_read)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, user_id, $10
FROM users WHERE username = 'user1'
RETURNING recipient_id;

If the user does not exist, nothing will be inserted or returned. If the user does exist, you'll get the user_id returned.

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

1 Comment

Thanks a bunch! much appreciated

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.