Thursday, September 7, 2017

SQL SELECT: make a certain column value as the first row returned

For example, you have a PURCHASE table.

product             amount       payType          payment
----------------    ----------     ----------------   -------------
product1           20              Credit card        40
product2           15              Cash                 60
product3           30              Account            90

You want to query the table and you want the Cash payType to be returned as the first row and the rest rows order in alphanumeric order.

You expect this

product             amount       payType          payment
----------------    ----------     ----------------   -------------
product2           15              Cash                 60
product3           30              Account            90
product1           20              Credit card        40


Select * from PURCHASE order by payType;
returns this

product             amount       payType          payment
----------------    ----------     ----------------   -------------
product3           30              Account            90
product2           15              Cash                 60
product1           20              Credit card        40

This query will get what you want.

Select * from PURCHASE order by CASE WHEN upper(payType) = 'CASH' THEN 1 ELSE 2 END, payType;

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment