1

I want to insert a data if not exists in db at mysql .

I used following query:

INSERT INTO market 
VALUES('DZ','PM','23') 
WHERE NOT EXISTS (Select name from market where name ='DZ')

but it did not work.

Could you tell me a way how to fix it?

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
Tonyukuk
  • 5,745
  • 7
  • 35
  • 63

1 Answers1

3

The generic solution for this is:

INSERT INTO market 
SELECT * FROM (SELECT 'DZ','PM','23') x
WHERE NOT EXISTS (select name from market where name = 'DZ')

The reason you need a subquery is that you can't have a WHERE without a FROM.


In Oracle, you can do it without a subquery by using DUAL:

INSERT INTO market 
SELECT 'DZ','PM','23'
FROM DUAL  -- Simpler in Oracle
WHERE NOT EXISTS (select name from market where name = 'DZ')
Bohemian
  • 412,405
  • 93
  • 575
  • 722