This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
This is the error message and my code. I just don't see the error.
Description:
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 'key='cbd1f3bb822e8617b624301774287490d3fcd97e' LIMIT 1' at line 1
Query:
SELECT *
FROM wp_wpsc_api_keys
WHERE name='MichelleAllen17'
AND key='cbd1f3bb822e8617b624301774287490d3fcd97e'
LIMIT 1
Any ideas of what can be the issue in my sql are welcome
KEY is a reserved keyword, it must be escaped with backtick.
SELECT *
FROM wp_wpsc_api_keys
WHERE name = 'MichelleAllen17' AND
`key` = 'cbd1f3bb822e8617b624301774287490d3fcd97e'
LIMIT 1
MySQL Reserved Keywords
put backtiks around the field names
...where `name`=... `key`
As an alternative to backticks, another "best practice" pattern is to QUALIFY all column names with the table_name, or a convenient table alias, e.g.
SELECT t.*
FROM wp_wpsc_api_keys t
WHERE t.name='MichelleAllen17'
AND t.key='cbd1f3bb822e8617b624301774287490d3fcd97e'
LIMIT 1
This prevents MySQL from seeing the column name "key" as a reserved word.
Let's be clear: the problem in your query isn't a lack of backticks... the problem is that MySQL is seeing a token in your query text (in this case "key") as a reserved word, rather than as the name of the column. The solution is to prevent MySQL from seeing that token as a keyword. Using backticks is one way to accomplish that, but they aren't required.
Using backticks is entirely valid, and can be done along with qualifying the column names. The backicks are required when the column name contains spaces or special characters. Here is the same query, with the table and column names enclosed in backticks:
SELECT t.*
FROM `wp_wpsc_api_keys` t
WHERE t.`name`='MichelleAllen17'
AND t.`key`='cbd1f3bb822e8617b624301774287490d3fcd97e'
LIMIT 1
I just happen to find it annoying to have to look at, or type, backticks that are unnecessary. It is MUCH MORE useful use of keystrokes (for me) to have the column names qualified ("t."), even if that isn't required, just because I am SO used to seeing column names qualified whenever there is more than one table in a query (which happens a LOT for a lot of really useful queries.)
Related
One of my columns is called from. I can't change the name because I didn't make it.
Am I allowed to do something like SELECT from FROM TableName or is there a special syntax to avoid the SQL Server being confused?
Wrap the column name in brackets like so, from becomes [from].
select [from] from table;
It is also possible to use the following (useful when querying multiple tables):
select table.[from] from table;
If it had been in PostgreSQL, use double quotes around the name, like:
select "from" from "table";
Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.
These are the two ways to do it:
Use back quote as here:
SELECT `from` FROM TableName
You can mention with table name as:
SELECT TableName.from FROM TableName
While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).
SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName
Your question seems to be well answered here, but I just want to add one more comment to this subject.
Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is reserved word.
More information:
"Reserved keywords should not be used
as object names. Databases upgraded
from earlier versions of SQL Server
may contain identifiers that include
words not reserved in the earlier
version, but that are reserved words
for the current version of SQL Server.
You can refer to the object by using
delimited identifiers until the name
can be changed."
http://msdn.microsoft.com/en-us/library/ms176027.aspx
and
"If your database does contain names
that match reserved keywords, you must
use delimited identifiers when you
refer to those objects. For more
information, see Identifiers (DMX)."
http://msdn.microsoft.com/en-us/library/ms132178.aspx
In Apache Drill, use backquotes:
select `from` from table;
If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.
select [select]
from [table]
I have also faced this issue.
And the solution for this is to put [Column_Name] like this in the query.
string query= "Select [Name],[Email] from Person";
So it will work perfectly well.
Hi I work on Teradata systems that is completely ANSI compliant. Use double quotes " " to name such columns.
E.g. type is a SQL reserved keyword, and when used within quotes, type is treated as a user specified name.
See below code example:
CREATE TABLE alpha1
AS
(
SEL
product1
type_of_product AS "type"
FROM beta1
) WITH DATA
PRIMARY INDEX (product1)
--type is a SQL reserved keyword
TYPE
--see? now to retrieve the column you would use:
SEL "type" FROM alpha1
I ran in the same issue when trying to update a column which name was a keyword. The solution above didn't help me. I solved it out by simply specifying the name of the table like this:
UPDATE `survey`
SET survey.values='yes,no'
WHERE (question='Did you agree?')
The following will work perfectly:
SELECT DISTINCT table.from AS a FROM table
Some solid answers—but the most-upvoted one is parochial, only dealing with SQL Server. In summary:
If you have source control, the best solution is to stick to the rules, and avoid using reserved words. This list has been around for ages, and covers most of the peculiarities. One tip is that reserved words are rarely plural—so you're usually safe using plural names. Exceptions are DIAGNOSTICS, SCHEMAS, OCTETS, OFFSETS, OPTIONS, VALUES, PARAMETERS, PRIVILEGES and also verb-like words that also appear plural: OVERLAPS, READS, RETURNS, TRANSFORMS.
Many of us don't have the luxury of changing the field names. There, you'll need to know the details of the RDBM you're accessing:
For SQL Server use [square_braces] around the name. This works in an ODBC connection too.
For MySQL use `back_ticks`.
Postgres, Oracle and several other RDBMs will apparently allow "double_quotes" to be used.
Dotting the offending word onto the table name may also work.
You can put your column name in bracket like:
Select [from] from < ur_tablename>
Or
Put in a temprary table then use as you like.
Example:
Declare #temp_table table(temp_from varchar(max))
Insert into #temp_table
Select * from your_tablename
Here I just assume that your_tablename contains only one column (i.e. from).
In MySQL, alternatively to using back quotes (`), you can use the UI to alter column names. Right click the table > Alter table > Edit the column name that contains sql keyword > Commit.
select [from] from <table>
As a note, the above does not work in MySQL
Judging from the answers here and my own experience. The only acceptable answer, if you're planning on being portable is don't use SQL keywords for table, column, or other names.
All these answers work in the various databases but apparently a lot don't support the ANSI solution.
Simple solution
Lets say the column name is from ; So the column name in query can be referred by table alias
Select * from user u where u.from="US"
In Oracle SQL Developer, pl/sql you can do this with double quotes but if you use double quotes you must type the column names in upper case. For example, SELECT "FROM" FROM MY_TABLE
I'm creating raw MySQL queries to insert into my DB using the Laravel 'DB' facade. I've gotten this same type of query to work with another database table, but it's throwing errors on this specific one.
1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 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 'group,originating_attorney,practice_area,responsible_attorney,statute_of_limitat' at line 1")
/home/vagrant/Code/proj/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452
2 PDO::prepare("INSERT INTO firm_matters(id,etag,display_number,custom_number,description,status,location,client_reference,billable,maildrop_address,billing_method,open_date,close_date,pending_date,client,contingency_fee,custom_rate,group,originating_attorney,practice_area,responsible_attorney,statute_of_limitations,user,account_balances,custom_field_vals,custom_field_set_associations,created_at,updated_at) VALUES (...)
I've checked the reserved keywords for MySQL and I don't think I'm violating any rules. Could someone more versed in MySQL check to see if my query is correct.
I've checked the reserved keywords for MySQL
No you didn't
syntax to use near 'group,originating
^^^^^ here
GROUP is reserved word https://dev.mysql.com/doc/refman/5.7/en/keywords.html
simply don't create "raw MySQL queries" and you'll be fine next time. you are smart enough to use framework yet you use "raw MySQL queries". just don't do it.
check the manual that corresponds to your MySQL server version for the right syntax to use near 'group, ...
Here's a tip about MySQL syntax errors: When the SQL parser encounters a word in your query that confuses it, the error message shows you exactly where it got confused. In this case, the word group is the one that the parser wasn't expecting in that place in the query.
Others have answered that group is a reserved word in MySQL. You can use reserved words as identifiers (table names, column names, etc.) if you put them in back-ticks to delimit them and make it clear they are identifiers, not SQL keywords.
INSERT INTO firm_matters(id, etag, display_number, custom_number, description,
status, location, client_reference, billable, maildrop_address, billing_method,
open_date, close_date, pending_date, client, contingency_fee, custom_rate,
`group`,
originating_attorney, practice_area,responsible_attorney, statute_of_limitations,
user, account_balances, custom_field_vals, custom_field_set_associations,
created_at, updated_at) VALUES (...)
The recommendation from #Peter to use a framework is because many frameworks automatically delimit ALL identifiers in back-ticks, just in case they are reserved words.
But you can resolve this error yourself without adopting a complex framework. Either delimit your identifiers, at least those that match MySQL reserved words, or else don't use reserved words as identifiers in the first place.
There's nothing wrong with writing SQL directly.
depends on your MySQL version, at least group is reserved keyword
https://dev.mysql.com/doc/refman/5.7/en/keywords.html#keywords-5-7-detailed-G
when you write a raw query, change all the
column to `column`
This question already has answers here:
Are you allowed to use numbers as table names in MySQL?
(5 answers)
Closed 6 years ago.
I have a MySQL table whose columns are like: s_no, prop, room, price, date, 1, 2, … , 30.
Now when I am inserting data into the column named 28. through PHP, I am recieving this error:
SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near '28='120' where s_no='10''
How do I insert data into this column?
According to MariaDB's Identifiers Names reference :
Identifiers may be quoted using the backtick character - `. Quoting is optional for identifiers that don't contain special characters, or is a reserved word.
You should wrap the columns names with ``:
`28` = '...'
However I really recommend changing your schema to have meaningful colum names
You can do that by using back ticks
UPDATE table SET `30`='100' WHERE id='1'
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
$time=date("G:i:s j.n.Y");
$wholetime="$time";
mysql_query("INSERT INTO rivase_chat_posts SET sender='$user', content='$msg', time='$wholetime', 'to'='$affectuser'");
$msg="";
I am doing a private chat thing. That is my code. It results 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 ''to'='gs'' at line 1 ($user="gskartwii", $msg="HI",
$affectuser='gs')
For column names, use backticks rather than single-quotes:
`to`='$affectuser'
Single quotes are there for strings only. Backticks (normally left of the number 1 on your keyboard) are the things to use for column or table names in mysql.
Edit: As Michael Berkowski correctly points out, the reason you have to do this for the column name is because to is a reserved word in mysql - which is a lovely way of saying that it is a special word that mysql sees to mean something within a query normally. on that note, it really might not be the best idea to use the reserved words as columns in your table - you will have to backtick them in every single instance that you use them. You might want to consider renaming it to something like toUser which will probably make the rest of your project easier to SQL out :)
You put the 'to' between single quotes. Column names are not quoted, or between backquotes. Single quotes are for strings. You cannot update a string, hence SET 'to'='user' is an error.
INSERT INTO rivase_chat_posts
SET `sender`='$user', `content`='$msg', `time`='$wholetime', `to`='$affectuser'
UPDATE: comments say to is a reserved word and should always be escaped - using backquotes.
To is a reserved word. Escape it:
INSERT INTO rivase_chat_posts
SET sender='$user', content='$msg', time='$wholetime', `to` ='$affectuser'
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
So I have a primary key column called key. I'm trying to select the row with key = 1 via this code:
$query ="SELECT * FROM Bowlers WHERE key = '1'";
$result = mysql_query($query) or die(mysql_error());
For some reason, I'm getting this result:
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 'key = '1'' at line 1
The mysql statement works for using other keys, ie WHERE name = 'djs22'.
Any ideas?
key is a reserved word, try putting ticks around it:
$query ="SELECT * FROM `Bowlers` WHERE `key` = '1'";
$result = mysql_query($query) or die(mysql_error());
To see all the reserved words, go here and scroll down:
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
'key' is a reserved keyword, put backtick quotes around it:
"SELECT * FROM Bowlers WHERE `key` = '1'"
Without checking, it's likely that "key" is a reserved word in MySQL.
Try wrapping it in backticks
$query ="SELECT * FROM Bowlers WHERE `key` = '1'";
You should write the column name key in quotes
$query ="SELECT * FROM Bowlers WHERE `key` = '1'";
Otherwise it is a keyword
I run into that all the time. MySQL has a crap load of reserved words. And when you come across one, the mysql error function is not even nice enough to let you know what is wrong.
The only thing you can do is change the column name. I accidentally used "date, to and from" the other day. Was pulling my hair out when it dawned on me, DuHH!!! those are DB reserved.
You can wrap all kind of quotes around it, it does not matter when it references a column name. Reserved is reserved!
It is common practice to to do a couple of things.
1) When making tables: Split resource type with resource name using underscore. Example: xref_userMessages
This would mean it is a cross reference table for User messages.
2) Other examples of table names: msg_Messages | sys_Settings | cli_Logins
So any other table made related to messages would be called msg_??? , not only does this keep them grouped together in phpMyadmin but makes remembering the names easier too.
3) When Making columns: Never use a reserved. Thus causing key columns to always be 6 didgets. Example: admkey | usrkey | msgkey | clikey grpkey
Obviously Admin Key | User Key | Message Key | Client Key | Group Key
So this means "msg_Messages" keys are "msgkey" and the xref table would be xref_Messages and its keys are xref_msgkey. Following this logic you not only know what to name everything without even thinking about it, but you never run into any reserved words doing it.
4) Examples of Column names: dateInsert dateStart timeCreate admName admAddress admPhone admCell
Just like above there is a logic to it. Placing purpose/owner and noun/item together makes the name and again avoids reserved words.
Last Example:
Table: users_Admins users_Clients
Key: admkey usrkey
Table: msg_Messages
Columns: msgkey admkey usrkey msgRead msgMessage msgTitle
Just in this short example I avoided 2 reserved words. Key and Read
So in short, your problem is not reading a primary key. It is a problem with column names.
MySQL is seeing your code as having a syntax that has commands out of place. SELECT read ... or SELECT key ... it doesnt matter if you put quotes around it or not. MySQL is basically seeing ...
SELECT (SELECT,WHERE,FROM) FROM select,from,where
WHERE SELECT = WHERE & FROM = SELECT. hehehehehehehe
Putting a different kind of quote around this will not change the confusion level you just sent to MySQL.
Mixing my mistake and your mistake together looks like this...
SELECT key,from,to,date FROM my_table WHERE key='1';
// Same as...
SELECT SELECT,SELECT,SELECT,SELECT FROM my_table WHERE SELECT='1';
The first one you can't really tell by looking at it there is anything wrong with it. The second one it is obvious that it is not right and won't work. However, according to MySQL they are the SAME THING.
MySQL receives this syntax as so... SELECT? You told me to SELECT 5 times, never told me what to even select. You get the FROM right, but then you ended with a left hook telling to select something else, not only did you not tell me what to select again but you threw in an NULL='1'; what the heck is that all about?
This is why when you make these kinds of errors the error function doesn't even report what the heck happened. There were so many errors it can't throw you an error number so it just stops.
So this means your syntax is like this
SELECT * FROM Bowlers WHERE SELECT = '1';
Sometimes I get frustrated and say, "I wish MySQL was smarter than this!!!" But then I realize i would have to trade the key words in for a lesser valued database. Each one of those reserved words represents a word that is doing a whole lot more work on the database side for me. When I first started to learn programming I had to write my own text input field sub routines, so I appreciate all the neat things MySQL does for me.