Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering an SQL query with exceptions

I have a table of products, and I need to write an SQL query which orders these products alphabetically according to their manufacturer.

i.e.

SELECT * FROM ProductsTable ORDER BY Manufacturer

But the complication is that we are trying to promote one particular manufacturer. So all the products for this manufacturer need to come at the top and not be alphabetised with the rest.

e.g.

+---------+------------+
|Product  |Manufacturer|
+---------+------------+
|pears    |Jim         |
|apples   |Fred        |
|tomatoes |Adam        |
|oranges  |Bob         |
|bananas  |Fred        |
|grapes   |Carl        |
+---------+------------+

If we are promoting Fred, the query would result in

+---------+------------+
|Product  |Manufacturer|
+---------+------------+
|apples   |Fred        |
|bananas  |Fred        |
|tomatoes |Adam        |
|oranges  |Bob         |
|grapes   |Carl        |
|pears    |Jim         |
+---------+------------+

Is there a way to do this?

like image 998
Urbycoz Avatar asked Dec 06 '25 18:12

Urbycoz


2 Answers

Try:

SELECT *, CASE WHEN Manufacturer = 'Fred' THEN 0 ELSE 1 END AS Ordering
FROM ProductsTable 
ORDER BY Ordering, Manufacturer
like image 148
Firoz Ansari Avatar answered Dec 08 '25 08:12

Firoz Ansari


Next to manufacturer, put a new field: Weight, and give weight 1 to promoting manufacturer, and 0 to others, then write your query:

SELECT * FROM ProductsTable ORDER BY Weight, Manufacturer

to promote manufacturer Fred, use:

UPDATE ProductsTable SET Weight = 0;
UPDATE ProductsTable SET Weight = 1 WHERE Manufacturer='Fred';

(it would be good to wrap those two update queries into transaction)

like image 37
Aleksandar Vucetic Avatar answered Dec 08 '25 07:12

Aleksandar Vucetic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!