What is the reason that the following two queries give wildly different results?
MariaDB [mydatabase]> SELECT COUNT(DISTINCT(`price`)) FROM `products`; --
Please find MariaDB's documentation about identifier names and string literals:
https://mariadb.com/kb/en/mariadb/identifier-names/
https://mariadb.com/kb/en/mariadb/string-literals/
Backquotes always quote identifier namens. Single quotes always quote string literals.
Identifier names get replaced by their value, string literals don't:
SELECT `price`, 'price' FROM products;
+-------+-------+
| 1 | price |
| 1 | price |
| 2 | price |
| 3 | price |
| 3 | price |
+-------+-------+
'price' (apostrophes or quotes) is a string. It never changes, so the count is always 1.
`price` (backtics) refers to the column price
. So it could be more than 1.
The inner parentheses are irrelevant. COUNT(DISTINCT price)
is the same as your backtic version.
SELECT COUNT(*) FROM tbl WHERE ...
is a common way to ask how many rows.SELECT foo, COUNT(*) FROM tbl GROUP BY foo
is a common way to ask how many rows for each distinct value of foo
.SELECT foo, COUNT(foo) FROM tbl GROUP BY foo
is the same as above, but does not count rows where foo IS NULL
.SELECT DISTINCT ... GROUP BY ...
is a nonsense statement. Either use DISTINCT or use GROUP BY.
A straight single quote (') is used for string literals (along with straight double quote (")).
A backtick quote (`) is for quoting identifiers.
Identifiers must be quoted if they match a reserved word, or if they contain special characters. Quoted identifiers also can specify lowercase in case-insensitive fields (which otherwise might be shown as uppercase).
CREATE TABLE MyTable (Field INT);
DESCRIBE MyTable;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| FIELD | INT | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
See also ANSI quote mode.