Dima Dz
Dima Dz

Reputation: 538

mysql combine columns into one and sort in alphabetic order

I have a the following table in Mysql:

id | Name                  | Abbreviation  |
---+-----------------------+---------------+
 1 | aaaa                  | a             |
 3 | bbbb                  | NULL          |
 2 | cccc                  | c             |
 4 | dddd                  | d             |
 8 | eeee                  | NULL          |
---+-----------------------+---------------+

I'd like a query to return the following. If the abbreviation is specified, then return the abbreviation, if no abbreviation, then return name, but abbreviation and name should be ordered alphabetically, so something like this

id | Result   |
---+----------+
1  | a        |
3  | bbbb     |
2  | c        |
...

How can I do this?

Upvotes: 0

Views: 205

Answers (1)

Dima Dz
Dima Dz

Reputation: 538

bumped into solution myself. since Abbreviation column can be NULL or have value, I can use COALESCE that'll get me the first not null column, in other words:

select id, coalesce(abbreviation, name) as thename from sometable order by thename;

Upvotes: 1

Related Questions