Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Get unique values across multiple columns in alphabetical order

Tags:

mysql

If my table looks like this:

id | colA   | colB | colC
===========================
1  | red    | blue | yellow
2  | orange | red  | red
3  | orange | blue | cyan

What SELECT query do I run such that the results returned are:

blue, cyan, orange, red, yellow

Basically, I want to extract a collective list of distinct values across multiple columns and return them in alphabetical order.

I am not concerned with performance optimization, because the results are being parsed to an XML file that will serve as a cache (database is hardly updated). So even a dirty solution would be fine.

Thanks for any help!

like image 537
RuCh Avatar asked May 10 '10 07:05

RuCh


People also ask

How can I get distinct values for multiple columns in MySQL?

To select distinct values in two columns, you can use least() and greatest() function from MySQL.

How do I sort by alphabetical order in MySQL?

Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order.

How do I count distinct values of multiple columns in SQL?

To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.

How do I get distinct on all columns?

SELECT DISTINCT FIELD1, FIELD2, FIELD3 FROM TABLE1 works if the values of all three columns are unique in the table. If, for example, you have multiple identical values for first name, but the last name and other information in the selected columns is different, the record will be included in the result set.


2 Answers

(SELECT DISTINCT colA AS color FROM table) UNION
(SELECT DISTINCT colB AS color FROM table) UNION
(SELECT DISTINCT colC AS color FROM table)
ORDER BY color
like image 169
reko_t Avatar answered Oct 14 '22 06:10

reko_t


Just do it the normal way:

create table new_tbl(col varchar(50));


insert into new_tbl(col)
select cola from tbl
union
select colb from tbl
union
select colc from tbl

Then sort:

select col from new_tbl order by col

Or if you don't want staging table, just do:

select cola as col from tbl
union
select colb from tbl
union
select colc from tbl
order by col

Note: UNION automatically remove all duplicates, if you want to include duplicates, change the UNION to UNION ALL

like image 31
Michael Buen Avatar answered Oct 14 '22 05:10

Michael Buen