+2 votes
1 view
in SQL by (20.3k points)
edited by

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example,

insert into table (id, name, age) values(1, "A", 19)

Let’s say the unique key is id, and in my database there is a row with id = 1. In that case I want to update that row with these values. Normally this gives an error. If I use insert IGNORE it will ignore the error, but it still won’t update.

1 Answer

+3 votes
by (40.3k points)
edited by

Try INSERT syntax with ON DUPLICATE KEY UPDATE

Are you interested in learning SQL from scratch! Have a look at this interesting video on SQL provided by Intellipaat:

QUERY:

INSERT INTO table (id, name, age) VALUES (1, "A", 19) ON DUPLICATE KEY UPDATE    name="A", age=19

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...