Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server select random AND not random

I have one table and I want to select 10 rows randomly. But I also need to select any rows that are on "sale". I only want only 10 rows, there may be 2 sale rows there may be 9, I need to fill the remaining with random rows. I need a single query.

SELECT TOP 10 BookTitle, BookAuthor, BookCategory
FROM TheTable
ORDER BY newid()

SELECT TOP 10 BookTitle, BookAuthor, BookCategory
FROM TheTable
WHERE BookCategory LIKE 'Sale%' 

I keep striking out, I may be over / under thinking this ....

Thanks.

like image 656
nope_four Avatar asked Jun 22 '26 10:06

nope_four


1 Answers

Not very efficient for a large table but...

SELECT TOP 10 BookTitle,
              BookAuthor,
              BookCategory
FROM   TheTable
ORDER  BY CASE
            WHEN BookCategory LIKE 'Sale%' THEN 0
            ELSE 1
          END,
          newid()  

If your table is large you should probably do 2 queries. One to get sale items and then the second to get the "top up" number of random non sale items only if required.

like image 163
Martin Smith Avatar answered Jun 24 '26 23:06

Martin Smith