Concatenate Random Result with Where Condition

Viewed 32

I want to concatenate results of 2 Select Queries from the same table;

my table :

CREATE TABLE "books" (
"id"    INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
"book_title"    TEXT UNIQUE,
"Book_desc" TEXT,
"category"  TEXT)

The first Query :Select * from books where id = 2

The second Query :Select * from books where id != 2 order by random() limit 3

I want the the id=3 to be the first row in results, I tried so many Union queries but It didn't work.

Here is what I did so far :

http://sqlfiddle.com/#!9/4ee515/3

1 Answers

The 2nd query to get 50 random rows without the row of id=100 should be:

select *
from (select * from table1 where id <> 100  order by random() limit 50) 

So use UNION ALL and conditional sorting:

select *
from (
  select * from table1 where id = 100
  union all
  select *
  from (select * from table1 where id <> 100  order by random() limit 50) 
)
order by id = 100 desc
Related