Insert a new row only if a row with the same subset of values doesn't exist yet
16:19 23 Feb 2026

Imagine I have a table called preferences tracking users' e-mail preferences. It has the following columns:

  • preferences_id (primary key)

  • user_id (link to the user table, not unique for various reasons)

  • marketing_emails (boolean)

  • security_emails (boolean)

  • handwritten_emails (boolean)

Now, by default, I consider all e-mail types to be enabled, however, for various reasons, I cannot create a row in the preferences table for every user right after they register, only after they change their preferences.

So when a user disables marketing e-mails, I want to either:

  1. Insert a new row like: INSERT INTO preferences (user_id, marketing_emails, security_emails, handwritten_emails) VALUES (?,0,1,1,);

    OR

  2. Update an existing row for the user like: UPDATE preferences SET marketing_emails = 0 WHERE user_id = ?;

Is there a way to combine both cases in a single query in MySQL, or do I have to first do a separate check if a row for the given user_id already exists and then execute one of the two queries?

sql mysql dataset unique