Order from IF EXISTS

Is there a way to sort by column if it really exists?

those.: SELECT * ORDER BY IF(EXISTS(order_column), order_column ASC, name_column DESC)

Thanks!

+3
source share
4 answers

You can use ISNULL instead

ORDER BY
    ISNULL(order_column, name_column)

Not sure how to add DESC or ASC ...

+2
source

Here is my unverified assumption:

ORDER BY IF(ISNULL(order_column), "", order_column) ASC, name_column DESC

If order_column is NULL, an empty string will be replaced that will not affect sorting. If it is not NULL, it will be sorted before the name column.

If Mysql does not allow you to use an expression in ORDER BY, you can always create an “artificial” column in SELECT:

SELECT 
  IF (ISNULL(order_column), "     ", order_column) 
     AS my_order_column, 
  name_column 
FROM table 
ORDER BY my_order_column ASC, name_column DESC.
+1
source

, EXISTS WHERE. , ? " "?

0

The best way to do this is to create an expression that evaluates to if as part of the select query. You can have an expression return order_column or name_column

the implementation depends on the SQL you use, but here you can use us IIf (...) as standard, but you may need to check for null

0
source

Source: https://habr.com/ru/post/1723444/


All Articles