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
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.)
I want to add a prefix to tables and have recently written a PHP script to extract all tables in a string SQL query.
$sql = 'UPDATE festivals SET desc = "Starts from July"';
preg_match_all('/(from|into|update|table|join) (`?\w+`?)\s/i', $sql, $matches);
It works good but the only problem is that it extracts July because it does not distinguish between a SQL value and a real table name, so it assumes that July would be a table too.
Now I think the solution should be something to prevent extract what wrapped in a single or double quotation but don't know how to do that.
Your regex is better off this way:
"/((?:^select .+?(?:from|into))|^update|^table|join) (`?\w+`?)\s/I"
But I still agree with nvartolomei.
If you were more strict in your query-writing, you would wrap all your database, table and column names in backticks ` and they would be extremely easy to extract - just get the first match of a string between them: just make the backticks required instead of optional.
That said, I'm not entirely sure how your regex is matching from July since the July is not followed by whitespace...
INSERT INTO expense (date,desc,price,out,method)
VALUES ('$time','$desc','$price','$out','$method');
What is wrong in the MySQL statement above? I have checked all the other stuff in my code but only this seems to be buggy.
I am passing this statement to mysql_query() function in PHP. It gives me an error and does not insert the data in the row.
All the variables above are also present.
So what could be the problem?
desc is keyword in SQL (order by `key` desc). You cannot use barewords which are also keywords in SQL. In this case, you should escape desc with ` symbol (like `desc`). date is also keyword, but MySQL decided to allow it's incorrect usage because of common usage before making it keyword. But not every database engine allows this, so be careful.
But, it's good practice to actually quote all keys, even if it's not needed - this way you could protect against adding keywords in SQL which would break your queries.
ORDER BY
List of keywords (in MySQL)
'date' is a MySQL keyword (for the date field type). You should enclose the field name with backticks like this:
INSERT INTO expense (`date`,desc,price,out,method)
(I think the other fields are fine, but you could add backticks to those as well if you like)
I'm using the joomla CMS to write to my db and have written a custom front end.
I'm trying to obtain the contents of the 'fulltext' row. I've tried mysql_fetch_assoc['fulltext'] and mysql_result($sql, 0, 'fulltext'). Both return fulltext. Here's the query string:
SELECT created, modified, title, introtext, 'fulltext', state, urls, created_by
FROM table_content
WHERE id='$id'
It's probably something really obvious I've missed because fulltext seems to conflict with sql without the quotation marks around it.
Any assistance would as always be appreciated!
You can use SQL keywords as field names, with appropriate escaping with backticks. You're using single quotes, which turns the word into a string that contains the word "fulltext".
Try
SELECT .... introtext, `fulltext`, state, ...
^--------^--- backticks
instead.