IF NOT EXISTS (SELECT 1 FROM Products WHERE name='Iphone1' AND manufacturer='appl') THEN
INSERT INTO Products(product_id, name, category, manufacturer)
VALUES (10000, 'IphoneZ', null, 'appl');
ERROR: syntax error at or near "IF" LINE 1: IF NOT EXISTS (SELECT 1
FROM Products WHERE name='Iphone1' A...
Can anyone help me understand what I am doing wrong?
MySQL only supports the IF statement in programming blocks -- stored procedures, functions, and triggers. Hence you cannot do what you want that way.
Instead, you can just write a single query:
INSERT INTO Products (product_id, name, category, manufacturer)
SELECT product_id, name, category, manufacturer
FROM (SELECT 10000 as product_id, 'IphoneZ' as name, null as category, 'appl' as manufacturer) t
WHERE NOT EXISTS (SELECT 1 FROM Products p WHERE p.name = t.name and p.manufacturer = t.manufacturer);
Actually, though, it is best to have the database directly enforce this sort of uniqueness. You can do so with a unique constraint/index:
CREATE UNIQUE INDEX unq_product_manufacturer_name ON product(manufacturer, name);
Then you can write an query to ignore errors by doing:
INSERT INTO Products (product_id, name, category, manufacturer)
VALUES (10000, 'IphoneZ', null, 'appl')
ON DUPLICATE KEY UPDATE category = VALUES(category);
The ON DUPLICATE KEY doesn't do anything -- it just serves to avoid returning an error if a duplicate value is inserted.
You are missing END IF keyword at the end of IF statement. And also, this SQL statement can be only used in a Routine block such as Stored Procedure or Stored Function.
Your SQL should be like this:
IF NOT EXISTS (SELECT 1 FROM Products WHERE name='Iphone1' AND manufacturer = 'appl') THEN
INSERT INTO Products(product_id, name, category, manufacturer)
VALUES (10000, 'IphoneZ', null, 'appl');
END IF;
Is it MySQL or SQL server?
I think you type wrongly : name='Iphone1' . It should be 'IphoneZ'.
You used single quotes in some places and double quotes in some places.
If it is mysql then try below query
INSERT INTO Products(product_id, name, category, manufacturer)
SELECT * FROM (select 10000,'IphoneZ', null, 'appl') AS tmp_table
WHERE NOT EXISTS (SELECT 1 FROM Products_arun WHERE name='IphoneZ'
AND manufacturer='appl') LIMIT 1;
If it is SQL server then try below query
IF NOT EXISTS (SELECT 1 FROM product WHERE name='IphoneZ' AND manufacturer='appl')
INSERT INTO product(product_id, name, category, manufacturer)
VALUES (10000, 'IphoneZ', null, 'appl');
Related
I'm trying to insert a new row with the same ID into a simple table but only want to insert if the values are different.
This table is to track price history of an item. The table has the following columns:
id, timestamp, productID, price
I only want to insert a new record if either the product doesn't exist or the product does exist but the price has changed.
Unfortunately I'm having a brain block due to my limited knowledge and would appreciate help in where to turn so I don't have any trials at the code to do this.
Thanks!
you can try something like this:
SET #PRODUCT = 1; # product id
SET #PRICE = 1; # new product price
insert into `t`(`product`, `timestamp`, `price`)
select v.product, now(), v.price
from
(select #PRODUCT as `product`, #PRICE as `price`) as v
left outer join
(select `product`, `price` from `t` where `product`=#PRODUCT order by `id` desc limit 1) as p
on (v.product=p.product)
where
(p.price is null) or
(p.price <> v.price);
so, this statement either insert new row (for new product or new price) or does nothing
u need composite primary key
ALTER TABLE products ADD PRIMARY KEY(product,price);
after this query if you insert if the product and price is same in your table returns error with duplicate entry
or it will insert the query even one field value changes
I have a query that inserts using a SELECT statement:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
Is it possible to only select "name, location" for the insert, and set gid to something else in the query?
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.
Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
Of course you can.
One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).
So be careful.
Here is the syntax of the command:
INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;
Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:
SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).
We all know this works.
INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT `col-1`,`col-2`
===========================
Below method can be used in case of multiple "select" statements. Just for information.
INSERT INTO `TableName`(`col-1`,`col-2`)
select 1,2 union all
select 1,2 union all
select 1,2 ;
The right Syntax for your query is:
INSERT INTO courses (name, location, gid)
SELECT (name, location, gid)
FROM courses
WHERE cid = $cid
I have read all most of the answers and even tried them. But this is my case where I'm inserting record from a .csv file into the database. I want to insert a record if it does not exist.
Here is my query
INSERT INTO retailer(retailerCode, contact, shopName, address,
retailerType, lastVisit, officeID, createDate)
VALUES ('', '$emapData[1]', '$emapData[2]', '$emapData[3]',
'$emapData[4]', '', '$id', CURDATE())
WHERE NOT EXISTS (SELECT retailerID
FROM retailer
WHERE contact = '$emapData[1]')
Here $emapData is a PHP array that saves the records of the .csv file. The insert statement works fine without this part
WHERE NOT EXISTS (SELECT retailerID
FROM retailer
WHERE contact = '$emapData[1]')
But my goal is not achieved.
You cannot use WHERE with INSERT in that way.
What you can do:
As #Sylwit suggested, create unique index on contact and use INSERT IGNORE
alter table retailer add unique (contact)
Use INSERT INTO SELECT syntax
INSERT INTO retailer(retailerCode,contact,shopName,address,retailerType,lastVisit,officeID,createDate)
select '','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','','$id', CURDATE()
from retailer
WHERE NOT EXISTS (SELECT retailerID FROM retailer WHERE contact='$emapData[1]')
I want to insert values to a row in my customer table if the Name value I'm providing do not already exist,
After some searching I used this sql query to do it and it does not work :(
IF NOT EXISTS (SELECT Name FROM customer WHERE Name = 'Riyafa')
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
VALUES ('Riyafa', 'ABC', '555','1000');
Please instruct me why that is incorrect.
The if statement is only allowed in stored procedures, functions, and triggers. One way you can do this is:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT name, address, contactno, total_amount
FROM (SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount) t
WHERE NOT EXISTS (SELECT 1 FROM customer c WHERE c.name = t.name);
A better approach, however, is to have the database enforce uniqueness on the name. Start by creating a unique index or name:
CREATE UNIQUE INDEX idx_customer_name ON customer(name);
Then use a construct such as on duplicate key update:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount
ON DUPLICATE KEY UPDATE Name = VALUES(Name);
The expression ON DUPLICATE KEY UPDATE Name = VALUES(Name) actually doesn't do anything, but it prevents the INSERT from returning an error.
I have a query that inserts using a SELECT statement:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
Is it possible to only select "name, location" for the insert, and set gid to something else in the query?
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.
Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
Of course you can.
One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).
So be careful.
Here is the syntax of the command:
INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;
Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:
SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).
We all know this works.
INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT `col-1`,`col-2`
===========================
Below method can be used in case of multiple "select" statements. Just for information.
INSERT INTO `TableName`(`col-1`,`col-2`)
select 1,2 union all
select 1,2 union all
select 1,2 ;
The right Syntax for your query is:
INSERT INTO courses (name, location, gid)
SELECT (name, location, gid)
FROM courses
WHERE cid = $cid