SQL if not exists - mysql

I have a SQL syntax error with my IF NOT EXISTS on line 1 when I tried to do this request on MySQL, and I can't figure why.
IF NOT EXISTS (SELECT * FROM `my_table` WHERE first_name = 'Testfn')
BEGIN
INSERT INTO `my_table` (first_name)
VALUES ('Testfn')
END;
I'm trying to insert first_name only if there is no other same first name in my_table.
I also tried this syntax, but I still have the error 1064 "You have an error in your SQL syntax" :
IF NOT EXISTS (SELECT * FROM `my_table` WHERE first_name = 'Testfn') THEN
INSERT INTO `my_table` (first_name)
VALUES ('Testfn')
END IF;
I tried SELECT * FROMmy_tableWHERE first_name = 'Testfn' separately, and it works.
And like this doesn't work too :
INSERT INTO `my_table` (first_name)
VALUES ('Testfn')
WHERE NOT EXISTS (SELECT * FROM `my_table` WHERE first_name = 'Testfn');
EDIT : first_name is UNIQUE in the database.

You have not need to write a column name, without specifying you can try to insert because we already checked condition on above. So basically you can do it using Merge Statement like.
MERGE INTO my_table
USING (
SELECT first_name
) t
ON t.first_name = my_table.first_name
WHEN NOT MATCHED THEN
INSERT (first_name) VALUES (t.first_name);
Hope this help you!

Related

How to select a list of data in MySQL and insert with one Query with SQL Language

I have a Select Statement that fetches more than 1 data
set #name := select name from users;
Now I want to insert all of them with one Query
for example
insert into users2 (name , created) Values (#name , NOW())
it returns this error
Error Code: 1242
Subquery returns more than 1 row
is there any way to do this without a loop?
The syntax must be like this
insert into users2 (name , created)
select name, NOW() from users
Try this
insert into users2 (name , created)
select name, NOW() from users;

How to use select statement to insert values on a table

I am trying to insert theses values to my table student but I have an error
insert into student(first_name,last_name,student_number,professor_id)
values(Eden,Yuan,323744573,
select professor_id from PROFESSORS where professor_name = 'Chu ')
I get an error
saying missing expression
you can use this way (assuming that professor_id is the column you need)
insert into student(first_name,last_name,student_number,professor_id)
select 'Eden', 'Eden', 323744573, column_professor_id
from PROFESSORS where professor_name = 'Chu ' ;
(In your query is missing the column in the select )

Insert new row unless ONE of the values matches another row?

I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
insert into `mytable` (`id`, `name`) values (10, `Fred`)
I want to be able to check to see if any other row in the table already has name = 'Fred'. How can this be done?
Thanks!
EDIT
What I tried (can't post the exact statement, but here's a representation):
INSERT IGNORE INTO mytable (`domain`, `id`)
VALUES ('i.imgur.com', '12gfa')
WHERE '12gfa' not in (
select id from mytable
)
which throws the error:
#1064 - 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 '12gfa' not in ( select id from mytable)' at line 3
First of all, your id field should be an autoincrement, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for id for each row.
If it's not the case, you should create a primary key for the table that includes ALL the fields you don't want to duplicate and use the INSERT IGNORE command.
Here's a good read about what you're trying to achieve.
You could use something like this
INSERT INTO someTable (someField, someOtherField)
VALUES ("someData", "someOtherData")
ON DUPLICATE KEY UPDATE someOtherField=VALUES("betterData");
This will insert a new row, unless a row already exists with a duplicate key, it will update it.
DELIMITER |
CREATE PROCEDURE tbl_update (IN id INT, IN nm VARCHAR(15))
BEGIN
DECLARE exst INT;
SELECT count(name) INTO exst FROM mytable WHERE name = nm;
IF exst = 0 THEN
INSERT INTO mytable VALUES(id, name);
END IF;
END
|
DELIMITER ;
or just make an attribute name as UNIQUE

Cannot insert row when table is empty in MySql

I wanna insert a row when the name not exists in the table.
When the table is empty,it cannot insert anything, anyone can help me?
Here is my code:
INSERT INTO `ediftpdb`.`users`(
name
,passwd
,vendor
)
SELECT
'L001'
,'12345678a'
,'MKTPLS'
FROM `ediftpdb`.`users`
WHERE NOT EXISTS (SELECT * FROM `ediftpdb`.`users` WHERE name='L001' AND vendor = 'MKTPLS' ) LIMIT 1;
P.S.
I found a funny stuff, when ediftpdb.users is empty, code like below returns nothing.
SELECT
'L001'
,'12345678a'
,'MKTPLS'
FROM `ediftpdb`.`users`
The better way to do this is to create a unique multi-part index on name and vendor columns:
CREATE UNIQUE INDEX name_vendor ON ediftpdb.users( name, vendor )
Then:
INSERT IGNORE INTO ediftpdb.users ( name, passwd, vendor )
VALUES ( 'L001', '12345678a', 'MKTPLS' )
will do exactly what you want to do.
As #Martin Smith pointed, when the table ediftpdb.users is empty the FROM ediftpdb.users
results in no rows. If it had 100 rows, then your statement would try to INSERT 100 (identical) records into the table.
Try this:
INSERT INTO
...
SELECT
'L001'
,'12345678a'
,'MKTPLS'
FROM (SELECT 1) AS dummy
WHERE NOT EXISTS ...

SQL - How to make a conditional INSERT

Using only MySQL, I'm seeing if it's possible run an insert statement ONLY if the table is new. I successfully created a user variable to see if the table exists. The problem is that you can't use "WHERE" along with an insert statement. Any ideas on how to get this working?
// See if the "country" table exists -- saving the result to a variable
SELECT
#table_exists := COUNT(*)
FROM
information_schema.TABLES
WHERE
TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'country';
// Create the table if it doesn't exist
CREATE TABLE IF NOT EXISTS country (
id INT unsigned auto_increment primary key,
name VARCHAR(64)
);
// Insert data into the table if #table_exists > 0
INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands') WHERE 0 < #table_exists;
IF #TableExists > 0 THEN
BEGIN
INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands');
END
Use an if statement instead of the where clause:
http://dev.mysql.com/doc/refman/5.0/en/if-statement.html