Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Insert Query With Condition

I am trying to insert values into 1 column of a table when a condition is satisfied.

Note: The table already contains data for all the columns but for 1 which is empty. I would like to insert value into this 1 column depending on the WHERE clause.

I have this query:

INSERT INTO <TABLE_NAME>
(COLUMN_NAME)
(VALUE)
WHERE <CONDITION>

I am getting an exception:

Incorrect Syntax Near WHERE Keyword

I am able to do this using UPDATE:

UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>

But was wondering why the INSERT query was failing. Any advise appreciated.

like image 980
Xavi Avatar asked Aug 16 '15 19:08

Xavi


People also ask

Can we write WHERE condition in insert query?

You Should not use where condition in Insert statement. If you want to do, use insert in a update statement and then update a existing record.

How do I insert a specific value in a column in SQL?

INSERT INTO Syntax 1. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...)

How do you add based on condition?

IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue') UPDATE Table1 SET (...) WHERE Column1='SomeValue' ELSE INSERT INTO Table1 VALUES (...) Based on the where-condition, this updates the row if it exists, else it will insert a new one.


2 Answers

As I understand your problem, you already have data in one row, and one column in that row does not have value, so you want to add value in to that column.

This the scenario for Update existing row, not the insert new row. You have to use UPDATE clause when data already present and you want to modify record(s). Choose insert when You want to insert new row in table.

So in your current scenario, Update Clause is your friend with Where Clause as you want to modify subset of records not all.

UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>

INSERT Clause does not have any Where Clause as per any RDBMS syntax(I think). Insert is condition less sql query, While SELECT, UPDATE, DELETE all are conditional commands, you can add Where Clause in all later ones.

like image 64
HaveNoDisplayName Avatar answered Sep 27 '22 16:09

HaveNoDisplayName


In order to add a value into the one column when the rows are already populated, you will need to use the update statement.
If you need to insert a new row that has a where clause, you will need to use an insert into select statement:

INSERT INTO <table> (<columns>)
SELECT <columns>
FROM <table>
WHERE <condition>;
like image 41
TheBrokenSpoke Avatar answered Sep 27 '22 18:09

TheBrokenSpoke