Immutable Brick
Immutable Brick

Reputation: 820

Sql multiple columns orders

Not really sure how to explain this on the title so it might be wrong.
SQL is not my main strength so sorry in advance if this is a stupid question :)
Using MySql by the way.

I have this query:

SELECT
ru.user_id AS "User Id",
ru.first_name AS "First Name"
FROM member_referral_users AS ru
ORDER BY ru.user_id DESC, ru.first_name ASC

the result set looks like this:

result set

I want the order to be Admin,angelo,emma,emma,carlos,chris,emma

I guess the order should be name first but I want those users (guests really) to be on the bottom since they have 0 as user_id

All the help is very appreciated.

Upvotes: 0

Views: 65

Answers (2)

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

SELECT
  ru.user_id    AS "User Id",
  ru.first_name AS "First Name"
FROM member_referral_users AS ru
ORDER BY ru.first_name ASC , ru.user_id ASC

Upvotes: 0

fthiella
fthiella

Reputation: 49049

SELECT
  ru.user_id AS "User Id",
  ru.first_name AS "First Name"
FROM member_referral_users AS ru
ORDER BY 
  ru.user_id = 0,
  ru.first_name ASC

ru.user_id = 0 will be evaluated either to TRUE (=1) or to FALSE (=0) and ordering by ru.user_id = 0 will put records with user_id=0 at the bottom.

Please see fiddle here.

Upvotes: 5

Related Questions