Gunakan insert . . . select
:
INSERT INTO USER (name, email)
SELECT 'John', '[email protected]'
WHERE NOT EXISTS
(SELECT id FROM USER WHERE email = '[email protected]');
Saya akan menulis ini sebagai:
INSERT INTO USER (name, email)
SELECT name, email
FROM (SELECT 'John' as name, '[email protected]' as email) t
WHERE NOT EXISTS (SELECT 1 FROM USER u WHERE u.email = t.email);
Tetapi pendekatan yang lebih baik mungkin hanya memasukkan indeks unik sehingga database melindungi data:
create unique index idx_users_email on user(email);