Reputation: 161
I have 2 tables in the database
the relationship between the two tables is one to one relation
Now, I'm trying to filter users by their office and order them by name_ar. I tried two different queries to do this and I expect the same result from the two queries but the result is different in order.
SELECT
`id`, `name_ar`
FROM
`users`
WHERE EXISTS
(
SELECT
*
FROM
`user_profiles`
WHERE
`users`.`id` = `user_profiles`.`user_id` AND `office_id` = 1
) AND(
`group` = "doctor" AND `state` = "active"
) AND `users`.`deleted_at` IS NULL
ORDER BY
`name_ar` IS NULL, `name_ar` ASC
SELECT
`u`.`id`,
`name_ar`
FROM
`users` u
INNER JOIN `user_profiles` up ON
`u`.`id` = `up`.`user_id`
WHERE
`group` = "doctor" AND `state` = "active" AND `up`.`office_id` = 1
ORDER BY
`name_ar` IS NULL, `name_ar` ASC
the two results do not have the same order from the beginning of appearing null value in name_ar column (from the fifth row exactly the order is different between the two results), Can any explain for me why is this happens? Is it because of null values or another reason?
Upvotes: 0
Views: 383
Reputation: 164174
The 1st condition of the ORDER BY
clause:
`name_ar` IS NULL
sends all null
s to the end of the results.
The 2nd:
`name_ar` ASC
sorts the non null
names alphabetically but when it comes to the null
names at the end there is not any defined order for them.
What you can do is add another final condition, like:
`id` ASC
so you have all the null
s (and duplicate names if they exist) sorted by id
:
ORDER BY `name_ar` IS NULL, `name_ar`, `id`
Upvotes: 1