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.
Related
Here is my query:
INSERT INTO table (id, actions, date, comments, type, url, rating)
SELECT * FROM (SELECT 'b7d54d99bf11', 'Information Exchanged', '1430463600', '', 'routine', 'http://example.com', '') AS tmp
WHERE NOT EXISTS (SELECT url FROM table WHERE url = 'http://example.com')
I get a SQL Error that says Duplicate column name: '' because there is no rating or comments passed in for some records.
How can I avoid the error? Is there a better way to achieve this?
You have to include alias for your columns
INSERT INTO table (id, actions, date, comments, type, url, rating)
SELECT * FROM (SELECT 'b7d54d99bf11' as id,
'Information Exchanged' as actions,
'1430463600' as date,
'' as comments,
'routine' as type,
'http://example.com' as url,
'' as rating) AS tmp
You don't need a subquery that complicated at all:
INSERT INTO table (id, actions, date, comments, type, url, rating)
SELECT 'b7d54d99bf11', 'Information Exchanged', '1430463600', '', 'routine', 'http://example.com', ''
FROM (SELECT 1 as x) t
WHERE NOT EXISTS (SELECT url FROM table WHERE url = 'http://example.com');
However, a better method is to let the database do the check. Create a unique constraint/index and then phrase the insert to ignore the update when there are duplicates:
alter table t add constraint unq_table_url unique(url);
insert into table (id, actions, date, comments, type, url, rating)
select 'b7d54d99bf11', 'Information Exchanged', '1430463600', '', 'routine', 'http://example.com', ''
on duplicate key update url = values(url);
This has the advantage that the database will ensure uniqueness for all inserts and updates -- and the code that does the database changes does not have to check each time.
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 have 2 tables: users with columns (id,username, password), and user_failed with columns (user_id, failed, time). is there any possible way i can insert into table user_failed by only using username? i try this code but it failed:
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (SELECT user_id FROM users WHERE username = 'pokemon','',3)
Your SQL query is incorrect for several reasons.
The following should work if I have interpreted your query correctly.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
SELECT id, '', 3 FROM users WHERE username = 'pokemon'
INSERTing into a table from a SELECT does not require VALUES ( ... ). Here is an example of how you would use VALUES ( ... ):
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (1, '', 3)
Also, your sub query SELECT user_id FROM users WHERE username = 'pokemon','',3 the WHERE clause is invalid. Specifically the '',3 part which I assume is the values you wanted to insert for time and failed.
This will work....you have to add plain parentheses before and after statements.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`) VALUES ((SELECT user_id FROM users WHERE username = 'pokemon'),'',3)
If I'm inserting data into a table with the following fields:
serialNumber active country
I need to only insert duplicate serialNumbers if active is no.
So for example: I want to insert a record with serialNumber 1234.
If the serial number doesn't already exist in the table go ahead and add it. If it does already exist, check the value of 'active' active is yes then don't add the new record, if it's no then do add the record.
Any ideas how to achieve this in MYSQL?
If the table lacks the necessary unique keys and you do not have permission, or don't want to set the keys you would need, you can use this alternative:
INSERT INTO `table1`
(`field1`,
`field2`)
SELECT value1,
value2
FROM (SELECT 1) t_1
WHERE NOT EXISTS (SELECT 1
FROM `table1`
WHERE `field1` = value1
AND `field2` = value2);
For yor question it could be written as
INSERT INTO `activity`
(`serialNumbers`,
`active`)
SELECT 1234,
'yes'
FROM (SELECT 1) t_1
WHERE EXISTS (SELECT 1
FROM `activity`
WHERE `serialNumbers` = 1234
AND `active` = 'no');
You can use the ON DUPLICATE KEY statement after an INSERT INTO query to update the row if it already exists. Documentation : https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (serialNumber , active, country) VALUES (1010, 'no', 'FR')
ON DUPLICATE KEY UPDATE active='yes';
You can use the insert ... on duplicate key update in MySQL. It is similar to the MERGE used in other SQL databases, but MySQL does not provide the MERGE statement so this is the next best.
INSERT INTO TABLE (serialNumber, active, country)
VALUES (1234, 'active', 'GB') ON DUPLICATE KEY UPDATE country = 'ND';
Also, use INSERT IGNORE if you don't want to generate errors.
I have a task to update existing multiple product-related tables with new entries if product name doesn't exist (no update). Thing is that this is one time action so product name column is not and will not be set as unique, primary, etc (and it is not possible for me to change it anyway).
I would be delighted if i could access the database remotely and use PHP, but due to security reasons i have access only to PhpMyAdmin on that server.
After googling for couple of hours i realized that either all results are about single INSERT IGNORE or similar constructions, or they are too complicated for me non-mysql brain to understand or solutions just won't work (like IF statement throws syntax error on that 5.5.8 MySQL server.
So thing is - there are 7 tables with all kinds of information on product (product, variant, image, category, product relation to category, prices, discounts). I have to check if product name doesn't exist and if true then insert new entries in all 7 tables. Additionaly i should create new product category entry if such doesn't exist (again, by name, not id)
In my humble opinion it would be like this:
IF (SELECT ProductName from `product` where ProductName='Pony') IS NULL THEN
INSERT INTO `product` VALUES ('', 'Pony');
#productId = (SELECT LAST_INSERT_ID());
INSERT INTO `category` (Name) SELECT 'Everything Nice' FROM `category` WHERE NOT EXISTS (SELECT Name FROM `category` WHERE Name='Everything Nice') LIMIT 1;
SET #categoryId = (SELECT CategoryId FROM `category` WHERE Name='Everything Nice');
INSERT INTO `product_rel_category` VALUES (#productId, #categoryId);
INSERT INTO `variant` VALUES ('', 'Nice');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
INSERT INTO `variant` VALUES ('', 'Sweet');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
INSERT INTO `variant` VALUES ('', 'Pink');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
... etc ...
ENDIF;
MySQL yells about syntax on IF in such query. I also tried working all kinds of procedures, but since I know only 'insert, update, select, delete', there is nothing much i can compose now.
So do you have an advise on solution on how i can make multiple INSERT/SELECT queries if a value in one table doesn't exist.
Sincerely thanks.