Advanced Query with a conditional order by

I have an Advanced Query (SQL) that I'm trying to use in Outsystems and trying to include an "ORDER BY" clause, only if a condition of an input parameter evaluates to true.  I'm getting an error when trying to do it. 

Ex.

Input Parameter: isSorted (boolean)

SQL:  SELECT {table1}.{field1} FROM {table1}

          IF (isSorted, ORDER BY COUNT DESC)

The advanced query errors out.  If I don't use it with the IF statement, it allows the query to proceed and so the ORDER BY I'm using is valid.  Any ideas.  Basically, it seems like I should be able to dynamically build the SQL.

Hi,

You should do somehting like below


Regards.

Hi Eric,

Have you tried "Prasad"solution.it will work perfect.

If condition will not work in advance sql you need to use Case statement.

Regards

Rahul Sahu