Why do these MySQL queries give different results? - mysql

SELECT * FROM tbl_custum_advertisement WHERE 'group' = 1
SELECT * FROM `tbl_custum_advertisement` WHERE `group`=1

You first query is comparing a literal 'group' to a literal 1.
Your second query is comparing the value of the field group to a literal 1.
MySQL uses backticks to indicate fields, and single quotes to indicate strings (or double quotes, actually)

Backticks (`) are to be used as an identifier for tables and columns
Single quotes (') should be used for strings and string comparisons
Please refer to this question for further understanding
When to use single quotes, double quotes, and backticks in MySQL

Quotes (') and backticks
`
are different.
'blah' is a literal string. But
`blah`
is a column (or other) name.
'group' = 1 is never true. But a column named group might contain the value 1, so
`group` = 1
could possibly be true.

Related

Why does using '' or "" doesn't sort column aliases via ORDER BY in MySQL?

Today in a live learning session with a friend of mine Dumisani Ndubane, we found out a slight change in behavior when using ORDER BY to sort a result set with column alias by using the ``, '' or "" quote types.
'' and "" aren't affect by the sorting, only `` works but all quotes are allowed to do column aliasing. See queries below;
This sort the Full name in ascending order (using `` quotes on column alias):
SELECT
CONCAT_WS(', ', lastName, firstname) `Full name`
FROM
employees
ORDER BY
`Full name`;
This doesn't sort the result set. Note we used '' quotes
SELECT
CONCAT_WS(', ', lastName, firstname) 'Full name'
FROM
employees
ORDER BY
'Full name';
This doesn't sort the result set. Note we used "" quotes
SELECT
CONCAT_WS(', ', lastName, firstname) "Full name"
FROM
employees
ORDER BY
"Full name";
Also, we where using MySQL version mysql Ver 8.0.19 for osx10.13 on x86_64 (Homebrew) on Mac. Is this intentional, is there an explanation to this behavior? Also, why not stick with backticks(``) with MySQL identifiers and '' or "" for string literals. Why mix them?
I think this could be a user experience (UX) improvement for MySQL because the current status quo seems confusing for a newbie trying to learn.
What do the SO community think and thanks for your help in advance.
Single quotes (and, in MySQL, double quotes) stand for literal strings. So 'Full name' is just that: a literal string. Using that for sorting makes no sense, since the value is constant for all rows: as a result, the ordering of rows is undefined, meaning that the database is free to return rows in whatever order it likes.
Instead, use backticks, that are used for identifiers, so the order by refers to the expression aliases in the select clause.
Or better yet, use an alias that does not requires quoting, so you don’t have to worry about this all.
The second example uses
ORDER BY 'Full Name'
This is a string literal, which is a constant value. It does not refer to the column alias of the same characters.
Any ORDER BY of a constant value results in an arbitrary order, because every row has an equal chance of being ordered before any other row. They are all tied.
Double-quoted strings are also treated as string literals by default in MySQL. This is different from ANSI SQL, where double-quotes are identifier delimiters. MySQL does that if you set sql_mode=ANSI or sql_mode=ANSI_QUOTES.

Where do we use backticks and quotes in MySQL?

I am new to SQL and still learning but one thing I am confused about is where we use ` and ' operators in MySQL/MariaDB. Can anyone explain this?
Backticks (`) are used to indicate database, table, and column names. Unless you're using reserved or conflicting words for table and database names, you'll not need to use them.
Quotes (' or ") are used to delimit strings, and differentiate them from column names.
For example:
SELECT * FROM `database`.`table` WHERE `column` = "value";
As I mentioned, backticks aren't needed, if you use reasonable table and column names:
SELECT * FROM mydb.users WHERE username = "jim";
But strings will always need quotes. This query is comparing the value in the column username against a value in the column bob, rather than the string value "bob":
SELECT * FROM mydb.users WHERE username = bob;

Find MySQL DB rows with a match in a pipe delimited column

I'm querying a table that has a column with member_ids stuffed in a pipe delimited string. I need to return all rows where there is an 'exact' match for a specific member_id. How do I deal with other IDs in the string which might match 'part' of my ID?
I might have some rows as follows:
1|34|11|23
1011
23|1
5|1|36
64|23
If I want to return all rows with the member_id '1' (row 1, 3 and 4) is that possible without having to extract all rows and explode the column to check if any of the items in the resulting array match.
MySQL's regular expressions support a metacharacter class that matches word boundaries:
SELECT ...
FROM mytable
WHERE member_ids REGEXP '[[:<:]]1[[:>:]]'
See http://dev.mysql.com/doc/refman/5.6/en/regexp.html
If you don't like that, you can search using a simpler regular expression, but you have to escape the pipes because they have special meaning to regular expressions. And you also have to escape the escaping backslashes so you get literal backslashes through to the regular expression parser.
SELECT ...
FROM mytable
WHERE member_ids REGEXP '\\|1\\|'
You can do this in one expression if you modify your strings to include a delimiter at the start and the end of the string. Then you don't have to add special cases for beginning of string and end of string.
Note this is bound to do a table-scan. There's no way to index a regular expression match in MySQL. I agree with #MichaelBerkowski, you would be better off storing the member id's in a subordinate table, one id per row. Then you could search and sort and all sorts of other things that the pipe-delimited string makes awkward, inefficient, or impossible. See also my answer to Is storing a delimited list in a database column really that bad?
'|' has a specific meaning in REGEXP. So suppose that the ids are separated by another delimiter like '~'.
Then you can run this code:
SELECT * FROM `t1`
where (Address Regexp '^1~') or
(Address Regexp '~1$') or
(Address Regexp '^1$') or
(Address Regexp '~1~')

Selecting records with single quotes escaped by double backslashes only

We have some records in this table in production environment where a particular field called compiledlimitation contains values where single quotes are escaped by multiple backslashes.
E.g. Test\\'s
We tried selecting only such records, but a query like the following returns those records which have single backslash (proper records) in addition to those which have double backslashes -
select * from tablename where compiledlimitation like "%\\'%"
The above query returns both these rows -
Test\\'s
Test\'s
How can I modify the query to fetch only rows with double backslashes.
The field compiledlimitation is a text field.
Update
Problem not solved yet. Both of these queries return both the records -
select * from tablename where compiledlimitation like "%\\\\\'%"
select * from tablename where compiledlimitation like "%\\\'%"
SELECT * FROM my_table WHERE my_column RLIKE '[\\]{2}';
or something like that
To escape two slashes, you should just need to use four in your LIKE:
LIKE "%\\\\%"
See http://dev.mysql.com/doc/refman/5.0/en/string-literals.html
Table 9.1. Special Character Escape Sequences
...
\\ => A backslash (“\”) character.
...
\ is an escape character, so to consider 2 \ you need to escape it with an additional \
select * from tablename where compiledlimitation like "%\\\'%"

How to escape value keyword in mysql while using Select statement

I am facing a problem while using Select statement where I have a column name as 'Value', and I want to retrieve the values based on the 'value' column with SELECT and LIKE operators.
Code:
SELECT compo.clecompo
FROM compo compo
ON (compo.clecompo = metadatas_compo.clecompo)
AND ((metadatas_compo.value LIKE '%%NOM%%')
OR (metadatas_values.metavalues_name LIKE '%%NOM%%'))
I highlighted the value keyword.. It's a sample of my query where i am not getting any results.
Note: (metadatas_compo.value) metadatas_compo is table name.
You escape literals in MySQL using backticks `
SELECT compo.clecompo FROM compo compo ON (compo.clecompo = metadatas_compo.clecompo) AND ((metadatas_compo.`value` LIKE '%%NOM%%') OR (metadatas_values.metavalues_name LIKE '%%NOM%%'))
However, it is advised to not use reserved literals in your table/column names. For a list of reserved words:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html