MySQL syntax variation - mysql

I am learning Php/MySQL from online tutorials (not that I expect you to watch it, but as a reference: http://www.youtube.com/watch?v=rJ3tDQfJt4k)
I am using MySQL 5.5.27 through phpMyAdmin 3.5.2.2
In the tutorial, this code is given (and works):
INSERT INTO 'posts' ('title', 'contents') VALUES('this is the first post', 'Yes it is.')
However, I receive this error message:
"#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..."
This syntax (which I found through trial and error) works for me:
INSERT INTO posts (title, contents) VALUES('this is the first post', 'Yes it is.')
I would like someone to explain why this is the case, and how to identify correct syntax - or to be linked to some documentation which would make this distinction comprehensible for a beginner. (I am unlikely to be able to follow the manual at this point in my learning.) Thanks for any help you can provide.

MySQL identifiers (column and table names) are optionally encased by backticks "`", not single quotes. The video is a little blurry and I can see why you would mistake them.
Try:
INSERT INTO `posts` (`title`, `contents`) VALUES('this is the first post', 'Yes it is.')

By default, identifiers can be escaped with backquotes, not single quotes. The default condition is due to the sql_mode mysqld starts with.
You could use double quotes if you configure ANSI_QUOTES for the sql_mode.
I wrote about this in the DBA StackExchange : How to convert MySQL Keyword to normal column

Related

I keep getting SQL Error (1064) for my AFTER INSERT Trigger [duplicate]

When issuing a command to MySQL, I'm getting error #1064 "syntax error".
What does it mean?
How can I fix it?
TL;DR
Error #1064 means that MySQL can't understand your command. To fix it:
Read the error message. It tells you exactly where in your command MySQL got confused.
Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.
Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.
Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).
Aaaagh!! What does #1064 mean?
Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.
As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.
What is this "syntax" of which you speak? Is it witchcraft?
Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.
For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):
This sentence contains syntax error a.
What does that have to do with MySQL?
Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.
It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.
How do I fix it?
Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…
Read the message!
MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:
UPDATE my_table WHERE id=101 SET name='foo'
That command yields the following error message:
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=101 SET name='foo'' at line 1
MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE at that point.
Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.
Examine the actual text of your command!
Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:
$result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
If you write this this in two lines
$query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
$result = $mysqli->query($query);
then you can add echo $query; or var_dump($query) to see that the query actually says
UPDATE userSET name='foo' WHERE id=101
Often you'll see your error immediately and be able to fix it.
Obey orders!
MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.
I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE command. The very first thing on the page is the command's grammar (this is true for every command):
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.
We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.
A note of reservation
Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.
I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:
UPDATE my_table SET where='foo'
Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn't intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.
[ deletia ]
The identifier quote character is the backtick (“`”):
mysql> SELECT * FROM `select` WHERE `select`.id > 100;
If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:
mysql> CREATE TABLE "test" (col INT);
ERROR 1064: You have an error in your SQL syntax...
mysql> SET sql_mode='ANSI_QUOTES';
mysql> CREATE TABLE "test" (col INT);
Query OK, 0 rows affected (0.00 sec)
It is late but will help others and ofcourse will save time :)
My query was working in MySQL 5.7 in local system but on live we have version MySQL 8 and query stop working.
Query:
SELECT t.*
FROM groups t
ORDER BY t.id DESC
LIMIT 10 OFFSET 0
Output in MySQL 8:
Error in query (1064): Syntax error near 'groups t ORDER BY t.id DESC'
at line ...
I came to know groups is reserved word so I have to wrap groups with `` quotes or change the table name to solve this issue.
For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.
For example, Before it was:
DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
After putting DELIMITER it was like this:
DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
$$
DELIMITER ;

Simple SQL update query not working

I need to run this query but I get an error:
UPDATE wp_usermeta
SET meta_value = "a:1:{s:16:\"client_special\";b:1;}"
WHERE user_id = "1009";
But I get 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 'UPDATE wp_usermeta
SET meta_value = "a:1:{s:16:\"cliente_especial\";b:1;}" W' at line 1
It is ok for me, I escaped the " with \ character.
As you discovered, and as my comment alluded, non-printing or hidden characters in your SQL statement can lead to unexpected syntax errors.
When confronted with what appears to be ludicrous messages, I find carefully retyping the statement into a different program helps decide whether it is a hidden character issue or a legitimate syntax issue.
It is the act of careful retyping that sanitizes the statement and rules out the non-printing characters. More than once I've done this and I imagine I will continue to do this for the rest of my career!

How do I change this SELECT stement into a DELETE statement to work with mysql [duplicate]

When issuing a command to MySQL, I'm getting error #1064 "syntax error".
What does it mean?
How can I fix it?
TL;DR
Error #1064 means that MySQL can't understand your command. To fix it:
Read the error message. It tells you exactly where in your command MySQL got confused.
Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.
Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.
Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).
Aaaagh!! What does #1064 mean?
Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.
As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.
What is this "syntax" of which you speak? Is it witchcraft?
Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.
For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):
This sentence contains syntax error a.
What does that have to do with MySQL?
Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.
It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.
How do I fix it?
Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…
Read the message!
MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:
UPDATE my_table WHERE id=101 SET name='foo'
That command yields the following error message:
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=101 SET name='foo'' at line 1
MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE at that point.
Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.
Examine the actual text of your command!
Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:
$result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
If you write this this in two lines
$query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
$result = $mysqli->query($query);
then you can add echo $query; or var_dump($query) to see that the query actually says
UPDATE userSET name='foo' WHERE id=101
Often you'll see your error immediately and be able to fix it.
Obey orders!
MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.
I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE command. The very first thing on the page is the command's grammar (this is true for every command):
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.
We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.
A note of reservation
Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.
I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:
UPDATE my_table SET where='foo'
Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn't intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.
[ deletia ]
The identifier quote character is the backtick (“`”):
mysql> SELECT * FROM `select` WHERE `select`.id > 100;
If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:
mysql> CREATE TABLE "test" (col INT);
ERROR 1064: You have an error in your SQL syntax...
mysql> SET sql_mode='ANSI_QUOTES';
mysql> CREATE TABLE "test" (col INT);
Query OK, 0 rows affected (0.00 sec)
It is late but will help others and ofcourse will save time :)
My query was working in MySQL 5.7 in local system but on live we have version MySQL 8 and query stop working.
Query:
SELECT t.*
FROM groups t
ORDER BY t.id DESC
LIMIT 10 OFFSET 0
Output in MySQL 8:
Error in query (1064): Syntax error near 'groups t ORDER BY t.id DESC'
at line ...
I came to know groups is reserved word so I have to wrap groups with `` quotes or change the table name to solve this issue.
For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.
For example, Before it was:
DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
After putting DELIMITER it was like this:
DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
$$
DELIMITER ;

MYSQL: Check if table exists does not work

IF OBJECT_ID(N`db_291702_2`.`aaCoRrankingDateManage`, N'U') IS NOT NULL
BEGIN
PRINT 'Table Exists'
END
What is wrong with this? Why do I get errors?
Neither of the suggested ways in how-to-check-if-a-table-exists-in-sql-server/ works for me.
PS. "does not work" means errors like
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 ''db_291702_2'.'aaCoRrankingDateManage' LIMIT 0, 30' at line 1
Additional info:
I am using phpMyAdmin, my two databases are called db_291702_1 and db_291702_2, the latter has two tables, one of them is called aaCoRrankingDateManage
If you want to escape table or column names then use backticks
select `group` from table1
A static string must be included in quotes
select * from users where name = 'john'
And the syntax of every DB engine is a little bit different. The above works for MySQL, but SQL-Server has a different syntax. There you use brackets [] to escape names.
But you only need to escape names if you use reserved words. You don't have to escape everything.
The given source code is no MySQL Code.

I am getting this error ?? can anyone advise why I can not see why

SQL query:
"INSERT INTO `ORDER_HEADER` (`order_ID`, `customer_ID`, `time_of_sale`, `net_total`)
VALUES (NULL, {$_SESSION['customer_ID']}, NOW(), '{$_SESSION['grand_total']}')"
MySQL said: Documentation
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 '"INSERT INTO ORDER_HEADER (order_ID, customer_ID, time_of_sale, `net_tot' at line 1
I think you have an extra quote at the beginning,from your error.You have to look just before mysql tells you about the error in your query.
'"INSERT
Hey bro you forgot to enclose this value within single quotes
(') {$_SESSION['customer_ID']}
Hence you r getting syntax error
Happy Coding :)
According to your error you seem to have an extra quote in the beginning. You could also be having an issue with the string concatenation of your $_SESSION variables.
Have you tried using php PDO statements? The will make your life MUCH easier, and they can be used to prevent SQL injection attacks and generally just make your code more secure.
Here's my favorite tutorial:
http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
And the docs:
http://php.net/manual/en/book.pdo.php