I have a table products with 3 columns:
– id_product
– quantity_in_stock
– product_name
I want to have all the rows ORDERED BY product_name with quantity_in_stock at the bottom of my result if it’s = 0.
I tried this query but it doesn’t work:
(SELECT *
FROM products
WHERE quantity_in_stock != 0
ORDER BY product_name ASC)
UNION
(SELECT *
FROM products
WHERE quantity_in_stock = 0
ORDER BY product_name ASC)
Maybe there is a simpler way to do that but it’s monday! 😉
The
ORDER BYcan contain an arbitrary expression, so you can evaluate those which= 0and assign them a higher value which sorts later:Because of MySQL’s boolean evaluation returning 1 or 0, you can simplify this as below. It won’t work in every RDBMS though:
Beware though, if
quantity_in_stockis not indexed, query performance could be affected negatively by this.