SQL Like is not taking _ - mysql

I would like to query only string that contains this exact string string_.
I tried this:
select * from table where name like "%string_%"
and results also include string-, but I need only exact _.
Any help?
Thanks

_ is the wildcard in SQL for a single character. If you want to search for _ you need to escape it:
select *
from some_table
where name like '%string\_%' escape '\'
Additionally: string literals are put into single quotes in SQL. If you ever want to use a more standard compliant DBMS (Oracle, Postgres) you should get used to using single quotes for strings. Double quotes are only for identifiers (and should essentially be avoided in the first place)

Related

SQL - match last two characters in a string

I have a small mysql database with a column which has format of a field as following:
x_1_1,
x_1_2,
x_1_2,
x_2_1,
x_2_12,
x_3_1,
x_3_2,
x_3_11,
I want to extra the data where it matches last '_1'. So if I run a query on above sample dataset, it would return
x_1_1,
x_2_1,
x_3_1,
This should not return x_2_12 or x_3_11.
I tried like '%_1' but it returns x_2_12 and x_3_11 as well.
Thank you!
A simple method is the right() function:
select t.*
from t
where right(field, 2) = '_1';
You can use like but you need to escape the _:
where field like '%$_1' escape '$'
Or use regular expressions:
where field regexp '_1$'
The underscore character has special significance in a LIKE clause. It acts as a wildcard and represent one single character. So you would have to escape it with a backslash:
LIKE '%\_1'
RIGHT does the job too, but it requires that you provide the proper length for the string being sought and is thus less flexible.
Duh, I found the answer.
Use RIGHT (col_name, 2) = '_1'
Thank you!

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.

Search of String value having special character in MySQL

I have one table emp in MySQL database having column as name. In that name column, the value is 'abc\xyz'. I want to search this value. I have tried using following query:
select * from emp where name like 'abc\xyz';
Also i have tried
select * from emp where name like 'abc\xyz' escape '\\';
But i did not found any output. Could you please help me in finding such strings? Such strings can have special character at any location.
Thanks in advance.
You may try like this:
select * from emp
where empname like '%abc\\\\xyz%'
SQL Fiddle Demo
From the docs:
Because MySQL uses C escape syntax in strings (for example, “\n” to represent a newline character), you must double any “\” that you use in LIKE strings. For example, to search for “\n”, specify it as “\\n”. To search for “\”, specify it as “\\\\”; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.
SELECT REPLACE(text,'\\','') FROM tbl
You can use REPLACE to remove some special chars :)

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 \.