0

I read so many questions/answers on stack overflow but no one give the answer which I want to require.

Here is the my result query. I have required result of sort by price low-> high but it gives me a result that starts with records that have the price 0. This is correct, but I don't want the 0 price records first. Result should start with prices greater than 0 and 0 price records should be displayed last.
Please help me to solve my this query.

For example, the result should start start with price 125.0, 125.0 ... 0, 0

3
  • what's the query you have so far?
    – Marius
    Commented Jun 14, 2016 at 12:16
  • @Marius, I have done following query SELECT product_id, quantity, price FROM product ORDER BY product.price ASC LIMIT 0 , 30 Commented Jun 14, 2016 at 12:18
  • I have required attached file result (This image was edited by mspaint) link Commented Jun 14, 2016 at 12:24

2 Answers 2

1

You can try this:

SELECT 
    product_id, quantity, price, 
    CASE price WHEN 0 
        THEN 1
        ELSE 0
    END
    as is_price_zero
FROM
    product
ORDER BY
    is_price_zero ASC,
    price ASC
5
  • #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'THEN 1 ELSE 0 END as is_price_zero FROM product ORDER BY ' at line 4 Commented Jun 14, 2016 at 12:26
  • There are some syntex error near CASE price = 0. Commented Jun 14, 2016 at 12:28
  • @VipulJethva attach sql file for table data here . Commented Jun 14, 2016 at 12:33
  • @VipulJethva. Sorry for that. I've updated the query. give it an other try
    – Marius
    Commented Jun 14, 2016 at 12:37
  • @Marius It's working brother. Thanks for helping. Commented Jun 14, 2016 at 12:51
0

Okay I think you need all the Price accending products first and than the products with 0 price

So you can run a query to get your data without 0 price values

SELECT * FROM 
(SELECT * FROM `product` WHERE price > 0
ORDER BY  price ASC LIMIT 0 , 30) as first_query

Than run a query to get data of 0 price values

SELECT * FROM `product` WHERE price = 0

and than union so final query will be

SELECT * FROM 
(SELECT * FROM `product` WHERE price > 0
ORDER BY  price ASC LIMIT 0 , 30) as first_query UNION SELECT * FROM `product` WHERE price = 0

Just change your field name as per your requirements.

2
  • Sourabh, I know this query. I don't want without 0 record. I have required attached file result (This image was edited by mspaint) link Commented Jun 14, 2016 at 12:31
  • @VipulJethva I have edited the answer please check if this is what you want. Commented Jun 14, 2016 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.