SQL: Unrecongnized statement near conditional (IF) - mysql

I've never used IF's before in SQL. I need to update a row where institution is a specific number if it exists and insert it if it doesn't. In order to avoid using first a select and then a insert or update I wanted to try my hand at an IF statement. I figured from what I've read in the documentation that it should go something like this:
IF (NOT EXISTS(SELECT evaluations FROM tEvaluations WHERE institution = 0))
BEGIN
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
END
ELSE
BEGIN
UPDATE tEvaluations SET evaluations = 10 WHERE institution = 0
END
However I get this error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'BEGIN
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
END' at line 2
I'm trying to run this query in phpmyadmin to test out how the query should be.

You can't have if..else block in normal SQL statement unless it's inside a procedural block. To me looks like you are looking for INSERT ON DUPLICATE KEY UPDATE like
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
ON DUPLICATE KEY UPDATE evaluations = 10;
Per documentation, either of your column should have a UNIQUE constraint defined against it. Quoting from documentation
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be
inserted would cause a duplicate value in a UNIQUE index or PRIMARY
KEY, an UPDATE of the old row occurs. For example, if column a is
declared as UNIQUE and contains the value 1

Related

Syntax Error in MYSQL clausules

Hello stackoverflow's friends i need your help with this sql clausule this is the error into mysql:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE email='Tysaic0344#gmail.com'' at line 1")
and this is my code:
INSERT INTO user (token) VALUES (1) WHERE email='example#email.com'
You cannot insert values into an existing row. You can either update or delete the existing records. In your case, I think you want to update the existing row. You can use UPDATE.
UPDATE user SET token = 1 WHERE email = 'example#email.com';
If you want to add records to the table use INSERT
INSERT INTO user VALUES (1, 'example#email.com');
Here is the link for your reference
https://msdn.microsoft.com/en-us/library/bb243852(v=office.12).aspx
You can't INSERT with a WHERE clause.
If you need to UPDATE the record where you have the email from:
UPDATE user
Set token = 1
WHERE email='example#email.com'
Or INSERT with email
INSERT INTO user (token, email)
VALUES (1, 'example#email.com')
(or without)
INSERT INTO user (token)
VALUES (1)
These kind of errors you MUST be able to fix by yourself, the error even tells you where it went wrong (at the end it says "near 'WHERE...").
Check the docs that dns_nx included (especially https://dev.mysql.com/doc/refman/5.7/en/update.html ) for the correct syntax to do an update.
You cannot INSERT a value into an existing row. The WHERE clause is invalid with INSERT. If you want to update an existing row, then you have to UPDATE the field like this:
UPDATE
user
SET
token = 1
WHERE
email='example#email.com'
Please review the docs about INSERT and UPDATE
https://dev.mysql.com/doc/refman/5.7/en/update.html
https://dev.mysql.com/doc/refman/5.7/en/insert.html
INSERT inserts new rows into a table. The WHERE clause is used to filter existing rows from a table. It doesn't make sense in a INSERT query; that's why the INSERT statement does not contain a WHERE clause.
The WHERE clause is used to filter the rows to fetch from the table (the SELECT statement), the rows to modify (the UPDATE statement) or to remove from the table (the DELETE statement).
Your query looks like you want to modify the data already existing in the table. The UPDATE statement you need looks like this:
UPDATE user SET token = 1 WHERE email = 'example#email.com'

MySQl I need to make a column unique only for certain values of another column

I have two columns Name,IsDelete in a table T
There can only be unique names for IsDelete=0
For IsDelete=1, there can be duplicate names.
I'm using this query
CREATE UNIQUE INDEX ix ON T(Name) WHERE IsDelete = 0;
But I'm getting the error,
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 IsDeleted = 0 at line 1
How can I use triggers to solve this?
Unique indices must have references to ALL RECORDS.
They cannot be conditional creation of unique index construction.
The requirement you set could be covered by another table structure where the deleted or not is not part of the record.
You must redesign the data to use a master table with unique IDs and alter the current to link to the master table.
It is a basic theoretical lesson in data normalisation.
Yeah, so I got a trigger that would check for the condition to be true.
DELIMITER $$
CREATE TRIGGER testing4
BEFORE INSERT ON biomitra_user
FOR EACH ROW BEGIN
IF EXISTS (select mobile_number from biomitra_user where is_deleted=0) THEN
SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Duplicate';
else
set new.mobile_number=new.mobile_number;
END IF;
END$$
DELIMITER ;
This is working fine

Mysql Insert Where Column is Like Wildcard Query

I'm attempting to inset values into every row where one of the column values contains a specific string.
INSERT INTO `cases_index`(`related`) VALUES (`Alabama`) WHERE `court` LIKE '%Alabama%'
So int eh above example I have a row with three columns:
court | federal | related
I want to insert the word 'Alabama' into the 'related' column for any row where the court column contains the word 'Alabama' (i.e. 'District Court of Alabama').
The above line spits out the following syntax 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 cases_index(court) LIKE '%Alabama%'' at line 1
Any ideas what I am doing wrong?
Apart from the syntax error in your query, if you want to update existing rows you should use an UPDATE query:
UPDATE cases_index
SET related='Alabama'
WHERE court LIKE '%Alabama%'
Just for completeness, INSERT queries add new rows to the table, so a WHERE clause in an INSERT is not allowed.
While the UPDATE answers are what you are looking for, INSERT does allow WHERE clause.
Refer to MySQL documentation
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
But the answer to this is what trgdor wrote:
UPDATE cases_index
SET related='Alabama'
WHERE court LIKE '%Alabama%'

mysql if exists giving error wrong syntax?

I am trying to use IF EXISTS in MySQL but i keep getting syntax errors and I have researched for correct syntax but everything isnt working...
What i need is:
If query exists then UPDATE else INSERT new...
$queryString = "IF EXISTS (SELECT * FROM $ONCALL_TABLE WHERE uid='$contextUser' AND submitid='$submitid' AND submitstatus=3) THEN UPDATE $ONCALL_TABLE SET uid='$contextUser', start_time='$onStr', end_time='$offStr', amount='$amount' ELSE INSERT INTO $ONCALL_TABLE (uid, start_time, end_time, amount) VALUES ('$contextUser','$onStr', '$offStr', '$amount') END IF";
Error message:
Can't perform query: 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 'IF EXISTS (SELECT * FROM timesheet_oncall WHERE uid='admin' AND submitid='136545' at line 1
REPLACE INTO is what you need. http://dev.mysql.com/doc/refman/5.0/en/replace.html
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
In your case
REPLACE INTO
$ONCALL_TABLE (uid, start_time, end_time, amount)
VALUES ('$contextUser','$onStr', '$offStr', '$amount')
WHERE uid='$contextUser';
Assuming uid is a PRIMARY KEY or UNIQUE KEY
NOTE: Since the code in your question contains SQL injection flaws I would recommend you to read this article. http://php.net/manual/en/security.database.sql-injection.php

mysql insertion where not exists syntax error. I have no idea what is wrong

insert into creditcard_info (member_id,card_type,card_number)
values ('1','Discover','555')
where not exists (
select * from creditcard_info
where card_number='555' and
card_type='Discover')
I want to be able to check if a card number already exists..
If card_number exists and card card_type exists then don't add
else insert this new card number along with card type
I am having difficultly with inserting into a table where a certain number does not exists.
Im getting this error:
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 not exists (select * from
creditcard_info where card_number='555')' at line 2
Thank you all in advance for helping me :)
It looks like you're trying to perform an INSERT ... SELECT statement.
However, adding a unique index in both fields should be more efficient.
You need to create a multi-column unique index. The code is as below:
ALTER TABLE creditcard_info ADD UNIQUE idx_card_number_card_type(card_number,card_type);
This should run as a separate query. And you need to add it once.
The other possible option is to add before insert trigger if the condition is more complicated than a simple unique check.
Here is the create trigger syntax:
Create Trigger card_type_unique_card_number_exists Before Insert on creditcard_info
FOR EACH ROW BEGIN
DECLARE it_exists INT;
Set it_exists=(select count(*) from creditcard_info where card_number='555' and card_type='Discover');
If it_exists>0 Then
#Throw a meaningful exception by let's say inserting into a table which doesn't exist or something
END IF;
END