Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - order by column if value exists, otherwise second column

How to order SQL result by column name and if there is not set name, order it by email.

+----+-------+-----------------+
| ID | name  |      email      |
+----+-------+-----------------+
|  1 | John  | [email protected]  |
|  2 | ---   | [email protected] |
|  3 | ---   | [email protected] |
|  4 | Peter | [email protected] |
+----+-------+-----------------+

Result should looks like that:

John, [email protected], [email protected], Peter

Answer:

$users = $this->em->createQueryBuilder()
        ->select('a.id, coalesce(concat(a.firstName, concat(\' \', a.lastName)), a.email) as orderColumn')
        ->from('Company\User\Admin', 'a')
        ->orderBy('orderColumn','ASC')
        ->getQuery()
        ->getScalarResult();
like image 898
MattBuk Avatar asked Feb 23 '26 13:02

MattBuk


2 Answers

What means "not set name"? Is it NULL or '---'? However, you can use CASE:

SELECT 
    CASE WHEN Name IS NULL THEN Email ELSE Name END AS User
FROM 
    dbo.TableName
ORDER BY
    CASE WHEN Name IS NULL THEN Email ELSE Name END ASC, Email ASC
like image 69
Tim Schmelter Avatar answered Feb 26 '26 01:02

Tim Schmelter


Try this

SELECT MyName = CASE 
        WHEN NAME = '---'
            THEN Email
        ELSE NAME
        END
FROM YourTable
ORDER BY CASE 
        WHEN NAME = '---'
            THEN Email
        ELSE NAME
        END ASC
like image 44
Krishnraj Rana Avatar answered Feb 26 '26 02:02

Krishnraj Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!