SQL column name with a pound sign - mysql

I'm new to SQL and recently I've had problems working with my table that contains a column name of 'S#'.
So what I currently have is
SELECT S#, SNAME FROM S WHERE CITY = 'London';
but the S# part gives me an operator error. I've tried casting it as a varchar and doing [S#] but nothing works. Any help would be appreciated.
Thanks

Use backticks or double quotes to escape the name:
SELECT `S#`, SNAME
FROM S
WHERE CITY = 'London';
When you design your own databases, don't use such characters in names. Stick to letters, numbers, and underscore.

Using Backticks, Double Quotes, and Single Quotes in any MySQL database can be summarized into two points:
Quotes (Single and Double) are used around strings.
Backticks are used around table and column identifiers.
Using backticks in your query,
SELECT `S#`, SNAME
FROM S
WHERE CITY = 'London';
These backticks are called quoted identifiers and they tell the parser to handle the text between them as a literal string. They are useful for when you have a column or table that contains a keyword or space or some special character.

In my case, the backticks around that column name work but double quotes don't.

Related

"a"+'b'+"c",What does two double quotes and one single quote combination mean in mysql

For example
SELECT "hello"'jacky'"hi" as value from dual;
the result is hellojackyhi
But it confuse me that the use of this pattern "a"+'b'+"c".
What does this pattern exactly mean?It's a use of double quotes and single quote, is it mean I can always combine 3 string using this pattern "a"+'b'+"c"?
MySQL has a "feature" where it concatenates strings that are adjacent (and separated by a space):
select 'a' 'b' 'c'
---> abc
This works for both single quotes and double quotes. Of course, double quotes might also be a column name.
So, this is a short-cut for string concatenation. I strongly recommend that you use CONCAT() instead, so the intention is clear.

How to correctly format quotation marks and double quotes in mysql query

I'm currently using PDO connection for perform some mysql queries and since I use the command $conn->prepare("HERE THE QUERY") I want to know how to format characters like quotes and double quotes.
When I have cases like this one:
$conn->prepare("SELECT * FROM ('SELECT DISTINCT (user_id) FROM table1')");
This is fine because in the nested SELECT there isn't a particular character that can cause problems. But how can we handle special cases like that?
Here a strange example (forget the mysql.. this is quite irrelevant, focus on the quotes situation) with quotes and double quote inside the nested SELECT:
$conn->prepare("SELECT * FROM ('SELECT user_id, CONCAT('[\"",GROUP_CONCAT(DISTINCT(cat) ORDER BY user_id DESC SEPARATOR "\",\""),"\"]') cat_grouped FROM table_1') select1");
What should be the right quotation mark syntax according to this example query? If i use ' instead of " when I prepare the query the problem is quite fixed, but I want to understand if there is a smart way to maintain the double quotes.
firstly I recommend using single quotes - they're faster :D
The main issue is using the same quotes with each other. Doing this causes pre-mature closing, and I'm sure you'd like to save that pre-mature embarrassment.
See in simple terms:
"string has star"ted"
As you can see, the first double quote the file gets to is the one after star. This closes the string after star, rendering the ted" in a fatal error.
What you want to do is escape the quotes that conflicts with the opening quote. Single quotes inside double quotes are fine, and vice versa.
Escape single quotes inside single quotes and double quotes inside double quotes - the rest should be ok to leave. Also I recommend using backticks for your mysql tables and fields to avoid some errors down the road if they deiced to add some new keyword that just so happens to match your table/field name
e.g.
if using single quotes:
$conn->prepare('SELECT * FROM table WHERE string_field = \'value\'');
if using double quotes:
$conn->prepare("SELECT * FROM table WHERE string_field = \"value\"");
if mixing:
$conn->prepare('SELECT * FROM table WHERE string_field = "value"');
\ is the escape character used for situations like this :)
The alternative is concatting strings:
$conn->prepare('SELECT * FROM table WHERE field = '. $foo);
so breaking it up, you declare string same was as usual with preferred quotes, then to add stuff to it, you use . to concat

Escaping a forward slash in an SQL name? It can be "escaped", but SQL believes it to be multiple columns

The last person in my job has flooded column names with special characters such as (?,!, and /), as well as used many reserved keywords for column names (more often than not, timestamp or user is used).
Normally, I step around this by using double quotes or brackets to escape the SQL object. A subset of the full list of columns are below:
DriverID,
Department,
Odometer,
MerchantState,
MerchantCity,
gallons/Units,
timestamp,
tax
Inside my query, I wrap the two columns in question (gallons/units and timestamp) inside double quotes. Timestamp because it's a reserved keyword, and Gallons/units, because without the quotes, SQL reads the query, stops at the slash, and tells me "Gallons" is not a column inside the table.
If I do wrap double quotes around the column name, SQL returns a different error: "Operand should contain 1 column(s)".
I've tried every variant (only capturing the slash in quotes, quoting both, using brackets, mixing brackets and quotes, etc. but with to no avail).
Is there anything I can do to fix this query short of renaming the column name and changing the associated code in the program that pulls from it? (the really tedious task I'm trying to avoid).
In SQL Server, identifiers can be delimited using square brackets, e.g.
SELECT [gallons/units] ...
In MySQL, identifiers can be delimited using backticks, e.g.
SELECT `gallons/units` ...
(NOTE: If MySQL SQL_MODE includes ANSI_QUOTES, then double quotes are treated as delimiters for identifiers, similar to the way Oracle handles double quotes; absent that setting, double quotes are handled as delimiters for string literals. With ANSI_QUOTES included SQL_MODE, "gallons/units" will be interpreted as an identifier (column name). Without ANSI_QUOTES, MySQL will see it as a string literal, as if it were enclosed in single quotes.)
FOLLOWUP:
As far as an error "operand should contain only 1 column(s)", that's usually a problem with query semantics, not an issue with escaping identifiers.
A subquery in the SELECT list can return only a single expression, for example, this would throw an error:
Query: SELECT 'foo' , ( SELECT 'fee' AS fee, 'fi' AS fi )
Error Code: 1241
Operand should contain 1 column(s)
You can try backticks instead of double quotes
`gallons/units`
There are a couple of options. First, have you tried using %/ to escape the slash?
Example: "select * from 'gallons%/units';"
Second one I've found, which may or may not be helpful, is to provide an escape character definition, such as
http://blogs.msdn.com/b/zainala/archive/2008/08/17/using-and-escape-clause-in-sql-server-like-query.aspx
select * from MyTable where Description like '|[summary|]%' escape '|'
In your case
select * from 'gallons|/units' escape '|'
You indicate both mysql and sql-server in your tags, so I'm not sure which server support I should be looking for exactly.

sql query with \ as value to check

I have a query in the following way.....i have a column named location_ns and it contains
'Marriott\256 Hotel & Convention Centre' as it's value. But query is not resulting any id.
when i remove \ in both value and query it is working.
SELECT id
FROM notice
WHERE
lon = 78.48693966865540000000
AND lat = 17.42434596639255000000
AND location_ns = 'Marriott\256 Hotel & Convention Centre'
AND notice_type="text"
Please let me know if any one has a solution for it
As documented under String Literals:
Within a string, certain sequences have special meaning unless the NO_BACKSLASH_ESCAPES SQL mode is enabled. Each of these sequences begins with a backslash (“\”), known as the escape character. MySQL recognizes the escape sequences shown in Table 9.1, “Special Character Escape Sequences”. For all other escape sequences, backslash is ignored. That is, the escaped character is interpreted as if it was not escaped. For example, “\x” is just “x”.
Therefore, you must escape your backslash:
AND location_ns = 'Marriott\\256 Hotel & Convention Centre'
However, you would do well to pass your literals to MySQL as parameters to a prepared statement.
\ is an escape sequence in MySQL. If you had a record with value:
Marriott\256 Hotel & Convention Centre
You would need to query for it like
AND location_ns = 'Marriott\\256 Hotel & Convention Centre'
This let's MySQL know you are looking for a literal \.

mysql select syntax

What is the purpose of this symbol in MySQL queries?
`
For example:
SELECT `show` FROM table WHERE id = "4"
In MySQL the backtick is used to quote column names. It is normally optional but here it is needed because SHOW is a reserved word.
A list of reserved words can be found here.
There is a difference between quotation marks (' and ") and backticks (`) in mysql.
Backticks are known as an "identifier quote" and are used to surround identifiers, such as:
tables
columns
indexes
stored functions
etc.
Quote go around strings, often used when inserting, updating, or trying to match against a string in the database (eg a WHERE clause)
Backticks are known as an "identifier quote" and are used to surround identifiers, such as: you can live without them but but they are necessary when
identifiers name contains spaces e.g. a column name is `customer name `
identifiers name is a reserved work e.g. a column name is `name `