Mega Code Archive

 
Categories / MySQL / Aggregate Functions
 

Total number of the table vs unique values count

mysql> mysql> CREATE TABLE IF NOT EXISTS rings     -> (     ->   id             INT             AUTO_INCREMENT PRIMARY KEY,     ->   stone          CHAR(10)        NOT NULL,     ->   price          DECIMAL(3,2)    NOT NULL     -> ); Query OK, 0 rows affected (0.00 sec) mysql> mysql> INSERT INTO rings (stone, price) VALUES ("Ruby", 40.00); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> INSERT INTO rings (stone, price) VALUES ("Emerald", 40.00); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> INSERT INTO rings (stone, price) VALUES ("Diamond", 60.00); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> INSERT INTO rings (stone, price) VALUES ("Diamond", 50.00); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> INSERT INTO rings (stone, price) VALUES ("Garnet", 40.00); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> mysql> # display all data in the "rings" table mysql> SELECT * FROM rings; +----+---------+-------+ | id | stone   | price | +----+---------+-------+ |  1 | Ruby    |  9.99 | |  2 | Emerald |  9.99 | |  3 | Diamond |  9.99 | |  4 | Diamond |  9.99 | |  5 | Garnet  |  9.99 | +----+---------+-------+ 5 rows in set (0.00 sec) mysql> mysql> # get the total number of rows mysql> SELECT COUNT(price) AS num_prices     -> FROM rings; +------------+ | num_prices | +------------+ |          5 | +------------+ 1 row in set (0.00 sec) mysql> mysql> # get the number of unique rows mysql> SELECT COUNT(DISTINCT price) AS num_distinct_prices     -> FROM rings; +---------------------+ | num_distinct_prices | +---------------------+ |                   1 | +---------------------+ 1 row in set (0.00 sec) mysql> mysql> # get all the unique stone values mysql> SELECT DISTINCT stone AS unique_stone_names FROM rings; +--------------------+ | unique_stone_names | +--------------------+ | Ruby               | | Emerald            | | Diamond            | | Garnet             | +--------------------+ 4 rows in set (0.00 sec) mysql> mysql> # delete this sample table mysql> DROP TABLE IF EXISTS rings; Query OK, 0 rows affected (0.00 sec) mysql>