views:

33

answers:

1

Dear all, I wanted a guidance for one problem . Suppose i have one table alphabets (alpha, id).
In column alpha having value a-z and in column id all values are 1.

a  1
b  1
.  .
.  .
z  1

Now i want a database query to insert data like a-z but with id=2 .

Can anybody help me out .

+6  A: 
INSERT INTO alphabets (alpha, id)
SELECT alpha, 2
  FROM alphabets a
 WHERE id = 1
   AND NOT EXISTS (
        SELECT * FROM alphabets
         WHERE alpha = a.alpha
           AND id = 2
       )

Note that the WHERE clause makes this query idempotent, i.e., it won't duplicate the id=2 rows if you run it twice.

Marcelo Cantos