Ankita
Ankita

Reputation: 165

Union returning different outputs with limit postgresql

I have to fetch 12 questions from my question set based on the difficulty level. Following is the query I have written.

(SELECT q.question_text, q.option_a, q.option_b, q.option_c, q.option_d,
        q.correct_answer, q.image_link, q.question_type
        FROM questions_bank q
        JOIN sports_type st ON st.id = q.sports_type_id
        JOIN difficulty_level dl ON dl.id = q.difficulty_level_id
        WHERE st.game_type = LOWER('cricket') AND dl.value = 'E'
        ORDER BY random()
        LIMIT 7) 
UNION 
(SELECT q.question_text, q.option_a, q.option_b, q.option_c, q.option_d,
        q.correct_answer, q.image_link, q.question_type
        FROM questions_bank q
        JOIN sports_type st ON st.id = q.sports_type_id
        JOIN difficulty_level dl ON dl.id = q.difficulty_level_id
        WHERE st.game_type = LOWER('cricket') AND dl.value = 'M'
        ORDER BY random()
        LIMIT 4)
UNION 
(SELECT q.question_text, q.option_a, q.option_b, q.option_c, q.option_d, 
        q.correct_answer, q.image_link, q.question_type
        FROM questions_bank q
        JOIN sports_type st ON st.id = q.sports_type_id
        JOIN difficulty_level dl ON dl.id = q.difficulty_level_id
        WHERE st.game_type = LOWER('cricket') AND dl.value = 'H'
        ORDER BY random()
        LIMIT 1);

The issue is that whenever I run this query, each time it gives me a different number of results instead of the static 12. Sometimes I get 12, sometimes 10, sometimes 15. I expect 12 rows in output, not less, not more.

What is wrong in this query?

Upvotes: 0

Views: 456

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125254

It can be reduced to a single select by using a window function:

select *
from (
    select
        row_number() over (partition by dl.value order by random()) as rn,
        dl.value,
        q.question_text, q.option_a, q.option_b, q.option_c, q.option_d,
        q.correct_answer, q.image_link, q.question_type
    from
        questions_bank q
        inner join
        sports_type st on st.id = q.sports_type_id
        inner join
        difficulty_level dl on dl.id = q.difficulty_level_id
    where st.game_type = lower('cricket') and dl.value in ('E','M','H')
) s
where 
    value = 'E' and rn <= 7 or
    value = 'M' and rn <= 4 or
    value = 'H' and rn = 1

Upvotes: 5

Related Questions