Hello stack overflow community. I’ve got a following problem.
Given the following, I have an entries table
CREATE TABLE `entries` (
`name` varchar(50) DEFAULT NULL,
`sort_order` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Which contains the following values:
INSERT INTO `entries` (`name`, `sort_order`) VALUES
('a', NULL),
('c', 2),
('b', 3),
('d', NULL),
('e', NULL),
('f', NULL),
('g', NULL),
('h', NULL),
('i', 5),
('ii', 4);
What is the best possible way to query and sort values by name asc keeping values with defined sort_order in its positions?
I tried different workarounds with ROW_NUMBER() and CTE but nothing worked.
Here’s the query, however it returns incorrect results.
WITH ranked_entries AS (
SELECT
*,
ROW_NUMBER() OVER (ORDER BY `name` ASC) AS `rn`
FROM entries
),
merged_entries AS (
SELECT
*,
COALESCE (`sort_order`, `rn`) AS merged_rank
FROM ranked_entries
)
SELECT * FROM merged_entries ORDER BY merged_rank ASC;
The expected result should be the following:
name | sort_order |
---|---|
a | 1 |
c | 2 |
b | 3 |
ii | 4 |
I | 5 |
d | 6 |
e | 7 |
f | 8 |
g | 9 |
h | 10 |
0