31
Sort records based on multiple columns' values in SQL
We have multiple columns(in one or more tables), these columns are mutually exclusive i.e only one of these columns can have a non-null value at a given time and others will be
null
.tasks
tableid, task_owner, task_type
task_owner
, task_type
can have a non-null value at a given time).Our goal is to sort the records based on the values of all these columns i.e The two columns
task_owner
and task_type
should behave as single data source, and we should be able to sort them based on the values present in this data source.
The solution is a simple one, we're going to use a generated/computed column which we'll use as a data source for sorting purposes.
The COALESCE operator, returns the first
The COALESCE operator, returns the first
non-null
value from its arguments.SELECT *, COALESCE(tasks.task_owner, tasks.task_type) AS sorting_col
FROM tasks
ORDER BY sorting_col;
CREATE TABLE tasks (id int, task_owner varchar(255), task_type varchar(255));
INSERT INTO tasks (id, task_owner, task_type) VALUES
(1, 'Masroor', null),
(2, null, 'Manager'),
(3, 'Alex', null),
(4, 'Yuri', null),
(5, null, 'Supervisor'),
(6, 'David', null),
(7, 'Brendon', null);
31