1

I have a table called notification, with two columns:

  • provider
  • email

The values look like this:

For all providers that do not have the email [email protected], I want to insert another row with the provider and the email [email protected]. For example, in the above query, the result of the INSERT statement would be: INSERT INTO notification VALUES ('apple', '[email protected]').

I have a table with thousands of rows like this, how would I write such an INSERT statement?

3
  • use t-sql - transact sql has conditional expressions to execute different statements based on logical expressions Commented Mar 26, 2012 at 21:45
  • Given your test data, wouldn't you also want to insert a row for abc? Commented Mar 26, 2012 at 22:00
  • The provider abc also lacks the email [email protected] (but does have [email protected]). Commented Mar 27, 2012 at 7:40

2 Answers 2

2
INSERT INTO notification
SELECT DISTINCT provider, '[email protected]'
FROM notification
WHERE provider NOT IN
(SELECT DISTINCT provider
FROM notification
WHERE email = '[email protected]')
Sign up to request clarification or add additional context in comments.

2 Comments

distinct on the inner query is there, and it's better performance wise too (slightly) (compared to having distinct on the outer select)
This can insert duplicate rows (in this case for "abc").
0

This should get you what you're after:

insert into notification (provider, email)
select distinct provider, '[email protected]'
from notification
where provider not in (
        select provider
        from notification
        where email like '[email protected]'
    )

2 Comments

Nope. That would insert a new record for every record that wasn't like [email protected], as opposed to one for each provider that doesn't have a [email protected].
I deleted that nearly as fast as I posted it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.