메뉴 건너뛰기

XEDITION

MYSQL

MySQL Insert Where query

엘리후 2016.02.19 00:25 조회 수 : 171

What's wrong with this query:

INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

It works without the WHERE clause. I've seemed to have forgot my SQL..

 

MySQL INSERT Syntax does not support the WHERE clause so your query as it stands will fail. Assuming your id column is unique or primary key:

If you're trying to insert a new row with ID 1 you should be using:

INSERT INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145);

If you're trying to change the weight/desiredWeight values for an existing row with ID 1 you should be using:

UPDATE Users SET weight = 160, desiredWeight = 145 WHERE id = 1;

If you want you can also use INSERT .. ON DUPLICATE KEY syntax like so:

INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145

OR even like so:

INSERT INTO Users SET id=1, weight=160, desiredWeight=145 ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145

It's also important to note that if your id column is an autoincrement column then you might as well omit it from your INSERT all together and let mysql increment it as normal.

 

You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware-

  1. INSERT specifying values

    INSERT INTO Users(weight, desiredWeight) 
    VALUES (160,145)
  2. INSERT using a SELECT statement

    INSERT INTO Users(weight, desiredWeight) 
    SELECT weight, desiredWeight 
    FROM AnotherTable 
    WHERE id = 1
shareimprove this answer
 

You use the WHERE clause for UPDATE queries. When you INSERT, you are assuming that the row doesn't exist.

In MySQL, if you want to INSERT or UPDATE, you can use the REPLACE query with a WHERE clause. If the WHERE doesn't exist, it INSERTS, otherwise it UPDATES.

EDIT

I think that Bill Karwin's point is important enough to pull up out of the comments and make it very obvious. Thanks Bill, it has been too long since I have worked with MySQL, I remembered that I had issues with REPLACE, but I forgot what they were. I should have looked it up.

That's not how MySQL's REPLACE works. It does a DELETE (which may be a no-op if the row does not exist), followed by an INSERT. Think of the consequences vis. triggers and foreign key dependencies. Instead, use INSERT...ON DUPLICATE KEY UPDATE.

 

 

Insert query doesn't support where keyword*

Conditions apply because you can use where condition for sub-select statements. You can perform complicated inserts using sub-selects.

For example:

INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'Newark';

By placing a "select" in the insert statement, you can perform multiples inserts quickly.

With this type of insert, you may wish to check for the number of rows being inserted. You can determine the number of rows that will be inserted by running the following SQL statement before performing the insert.

SELECT count(*)
FROM customers
WHERE city = 'Newark';

You can make sure that you do not insert duplicate information by using the EXISTS condition.

For example, if you had a table named clients with a primary key of client_id, you could use the following statement:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);

This statement inserts multiple records with a subselect.

If you wanted to insert a single record, you could use the following statement:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);

The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.

See also How to insert with where clause

 

The right answer to this question will be sth like this:

a). IF want select before insert :

INSERT INTO Users( weight, desiredWeight ) 
  select val1 , val2  from tableXShoulatNotBeUsers
  WHERE somecondition;

b). IF record already exists use update instead of insert:

 INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

Should be

Update Users set weight=160, desiredWeight=145  WHERE id = 1;

c). If you want to update or insert at the same time

Replace Users set weight=160, desiredWeight=145  WHERE id = 1;

Note):- you should provide values to all fields else missed field in query 
        will be set to null

d). If you want to CLONE a record from SAME table, just remember you cann't select from table to which you are inserting therefore

 create temporary table xtable ( weight int(11), desiredWeight int(11) ;

 insert into xtable (weight, desiredWeight) 
    select weight, desiredWeight from Users where [condition]

 insert into Users (weight, desiredWeight) 
    select weight , desiredWeight from xtable;

I think this pretty covers most of the scenarios

 
 
 

Insert into = Adding rows to a table

Upate = update specific rows.

What would the where clause describe in your insert? It doesn't have anything to match, the row doesn't exist (yet)...

 

It depends on the situation INSERT can actually have a where clause.

For example if you are matching values from a form.

Consider INSERT INTO Users(name,email,weight, desiredWeight) VALUES (fred,bb@yy.com,160,145) WHERE name != fred AND email != bb@yy.com

Makes sense doesn't it?

 

The simplest way is to use IF to violate your a key constraint. This only works for INSERT IGNORE but will allow you to use constraint in a INSERT.

INSERT INTO Test (id, name) VALUES (IF(1!=0,NULL,1),'Test');

 

 

After WHERE clause you put a condition, and it is used for either fetching data or for updating a row. When you are inserting data, it is assumed that the row does not exist.

So, the question is, is there any row whose id is 1? if so, use MySQL UPDATE, else use MySQL INSERT.

 
 

correct syntax for mysql insert into statement using post method is:

$sql="insert into ttable(username,password) values('$_POST[username]','$_POST[password]')";

 

 

If you are specifying a particular record no for inserting data its better to use UPDATE statement instead of INSERT statement.

This type of query you have written in the question is like a dummy query.

Your Query is :-

INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

Here , you are specifying the id=1 , so better you use UPDATE statement to update the existing record.It is not recommended to use WHERE clause in case of INSERT.You should use UPDATE .

Now Using Update Query :-

UPDATE Users SET weight=160,desiredWeight=145 WHERE id=1;

 

 

Does WHERE-clause can be actually used with INSERT-INTO-VALUES in any case?

The answer is definitively no.

Adding a WHERE clause after INSERT INTO ... VALUES ... is just invalid SQL, and will not parse.

The error returned by MySQL is:

mysql> INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 1' at line 1

The most important part of the error message is

... syntax to use near 'WHERE id = 1' ...

which shows the specific part the parser did not expect to find here: the WHERE clause.

 

You simply cannot use WHERE when doing an INSERT statement:

 INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

should be:

 INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 );

The WHERE part only works in SELECT statements:

SELECT from Users WHERE id = 1;

or in UPDATE statements:

UPDATE Users set (weight = 160, desiredWeight = 145) WHERE id = 1;

 

 

its totall wrong. INSERT QUERY does not have a WHERE clause, Only UPDATE QUERY has it. If you want to add data Where id = 1 then your Query will be

UPDATE Users SET weight=160, desiredWeight= 145 WHERE id = 1;

 

I think your best option is use REPLACE instead INSERT

REPLACE INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145);

DO READ THIS AS WELL

It doesn't make sense... even literally

INSERT means add a new row and when you say WHERE you define which row are you talking about in the SQL.

So adding a new row is not possible with a condition on an existing row.

You have to choose from the following:

A. Use UPDATE instead of INSERT

B. Use INSERT and remove WHERE clause ( I am just saying it...) or if you are real bound to use INSERT and WHERE in a single statement it can be done only via INSERT..SELECT clause...

INSERT INTO Users( weight, desiredWeight ) 
SELECT FROM Users WHERE id = 1;

But this serves an entirely different purpose and if you have defined id as Primary Key this insert will be failure, otherwise a new row will be inserted with id = 1.

 

You can do conditional INSERT based on user input. This query will do insert only if input vars '$userWeight' and '$userDesiredWeight' are not blank

INSERT INTO Users(weight, desiredWeight )
select '$userWeight', '$userDesiredWeight'  
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
번호 제목 글쓴이 날짜 조회 수
55 MySQL 데이터 복구하기 엘리후 2016.10.06 85
54 플래시로 DB테이블 연동 기초~ 엘리후 2016.09.07 62
53 [문제해결 일지] systemctl start mariadb 실행시 Failed to issue method call: No such file or directory. 에러 엘리후 2016.05.10 83
52 알기 쉬운 게임DB 이야기 엘리후 2016.02.28 248
51 mysql 이벤트 스케줄 사용법 엘리후 2016.02.20 1866
50 MySql 문자열 합치기 엘리후 2016.02.19 239
» MySQL Insert Where query 엘리후 2016.02.19 171
48 [MySQL]이벤트 스케줄러를 사용해서 데이터 삭제하기 엘리후 2016.02.02 215
47 mysql 이벤트 스케쥴러 사용하기 엘리후 2016.02.02 85
46 SQL FULL OUTER JOIN Keyword 엘리후 2016.01.28 132
45 mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead… 엘리후 2015.12.01 67
44 mysql 명령어로 접속시도시 발생되는 오류 엘리후 2015.12.01 328
43 MYSQL: AND & OR CONDITIONS 엘리후 2015.11.26 32
42 [MY-SQL] 현재(오늘)부터 특정일 까지를 구하는 Query문(between, subdate) + 오늘 기준 이번주, 이번달 구하는 Query문 엘리후 2015.11.20 201
41 mysql에서 가장 오래된 row select 쿼리는? 엘리후 2015.11.19 158
40 MySQL 함수를 활용한 날짜비교 쿼리문 작성하기 [출처] MySQL 함수를 활용한 날짜비교 쿼리문 작성하기|작성자 네오 에이치 엘리후 2015.11.18 60
39 MySQL 기본쿼리 : DELETE 문 엘리후 2015.11.02 45
38 [서버관리] phpMyAdmin을 통한 DB 및 사용자추가 엘리후 2015.10.28 116
37 Ubuntu MySQL 원격 접속 허용 엘리후 2015.10.22 56
36 [mysql] mysql 중복 제거 쿼리 (dist, group by) 엘리후 2015.10.21 137
위로