Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sql to handle potential for null result from subquery during insert statement

I am performing an insert, and using a subquery to select an email address for the insert statement, as such:

INSERT INTO users (id, email, date) VALUES (
123,
(
  SELECT email from list_of_emails WHERE email = 'abc@yahoo.com'
),
now() 
)

The users table has a non-null constraint on an email address, so what I am trying to catch is the potential that there may not be an email address that matches the subquery, in which case a not-null constraint violation occurs.

Any suggestion on how to catch this value error during the subquery and return some error message like "email address was not found"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just use INSERT ... SELECT ...; form:

INSERT INTO users (id, email, date)
SELECT DISTINCT 123, email, now()
  FROM email
 WHERE email = 'abc@yahoo.com'
;

This avoids attempting to insert when no email rows are found. Hopefully, you don’t have duplicate email entries, as that would have been a problem in the original as well. I added a DISTINCT just in case, since I don’t know your schema. Remove the DISTINCT if email is guaranteed unique in the email table.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading