Insert data and if already inserted then update in sql Insert data and if already inserted then update in sql sql sql

Insert data and if already inserted then update in sql


The standard SQL statement for INSERT (if new) or UPDATE (if exists) is called MERGE.

Since you didn't specify which DBMS dialect you're asking about, I'll refer you to the Wikipedia article "Merge (SQL)", which covers most DBMS dialects. Summary:

MERGE INTO tablename USING table_reference ON (condition)WHEN MATCHED THEN  UPDATE SET column1 = value1 [, column2 = value2 ...]WHEN NOT MATCHED THEN  INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...])

Database management systems Oracle Database, DB2, Teradata, EXASOL, CUBRID, MS SQL and Vectorwise support the standard syntax. Some also add non-standard SQL extensions.

MySQL: INSERT ... ON DUPLICATE KEY UPDATE

SQLite: INSERT OR REPLACE INTO

PostgreSQL: INSERT INTO ... ON CONFLICT


You could use the EXISTS keyword to check for the existance of rows:

IF EXISTS (SELECT TOP 1 * FROM...)BEGIN    UPDATE....ENDELSEBEGIN   INSERT...END


Just identify the unique item in your data set (like Id or a code). Then by using that try to do a SELECT query first. If the Resultset is empty, do the INSERT else try to UPDATE the details.