0

I've a table as shown in the SQL Fiddle.

CREATE TABLE `test` (
  `id` varchar(250) NOT NULL,
  `name` varchar(512) NOT NULL,
  `description` text NOT NULL,
  `priority` int(11) DEFAULT NULL,
  `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


 INSERT INTO `test` (`id`, `name`, `description`, `priority`, `created_date`) VALUES
('1', 'John', 'kasdjkaksdj', 3, '2018-07-12 07:37:25'),
('2', 'Doe', 'updations', 1, '2018-07-12 08:56:27'),
('3', 'Matt', 'sdasd', NULL, '2018-07-12 09:09:08'),
('4', 'Jiss', 'vghjgfghj', 1, '2018-07-13 12:33:19'),
('5', 'Noel', 'sdfsdf', NULL, '2018-07-13 12:33:29');

The priority column is NULL by default. User can specify any integer values to this column. I want to sort the table based on the priority asc and for rest of the records (which have NULL priority) sort by created_date asc.

I tried with the query

SELECT * FROM `test` ORDER BY priority, created_date 

Result :

id    name    description priority    created_date

3     Matt    sdasd        (null)      2018-07-12T09:09:08Z

5     Noel    sdfsdf       (null)      2018-07-13T12:33:29Z

2     Doe     updations     1          2018-07-12T08:56:27Z

4     Jiss    vghjgfghj     1          2018-07-13T12:33:19Z

1     John    kasdjkaksdj   3          2018-07-12T07:37:25Z

But this is showing priorities with NULL values first followed by records sorted by priority.

Excepted result:

id    name    description priority    created_date

2     Doe     updations     1          2018-07-12T08:56:27Z

4     Jiss    vghjgfghj     1          2018-07-13T12:33:19Z

1     John    kasdjkaksdj   3          2018-07-12T07:37:25Z

3     Matt    sdasd        (null)      2018-07-12T09:09:08Z

5     Noel    sdfsdf       (null)      2018-07-13T12:33:29Z

Can anyone help me to find the correct query. Thanks in advance.

2 Answers 2

2

You can try this code

SELECT * FROM `test` ORDER BY ISNULL(priority) ,priority, created_date

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

Your query is working fine, but there is only one issue that is :

You need to just add "name" in after ORDER BY:

for reference : go to demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.