SELECT * FROM table WHERE product like '%abc%' OR product like '%cde%'
Is it possible to display all products with
both 'abc' and 'cde' first
and then products with
either 'abc' or 'cde'
SELECT * FROM table WHERE product like '%abc%' OR product like '%cde%'
Is it possible to display all products with
both 'abc' and 'cde' first
and then products with
either 'abc' or 'cde'
ORDER BY a case expression that returns 1 if both abd and cde, or else 2.
SELECT *
FROM table
WHERE product like '%abc%' OR product like '%cde%'
ORDER BY case when product like '%abc%' AND product like '%cde%' then 1
else 2
end
Try using a correlated query in the ORDER BY clause :
SELECT t.*
FROM table t
WHERE product like '%abc%' OR product like '%cde%'
ORDER BY (SELECT COUNT(DISTINCT product) FROM table s
WHERE t.<Relation> = s.<Relation>
AND s.product like '%abc%' OR s.product like '%cde%') DESC
Replace <Relation> with the tables key .
For refined ordering:
SELECT * FROM table
WHERE product like '%abc%' OR product like '%cde%'
ORDER BY
CASE
/* First show products with 'abc' AND 'cde'... */
WHEN product LIKE '%abc%' AND product LIKE '%cde%' THEN 1
/* ...2nd products with with 'abc' */
WHEN product LIKE '%abc%' THEN 2
/* ...and finally products with with 'cde' */
WHEN product LIKE '%cde%' THEN 3
ELSE 4 /* not actually necessary in this case */
END