Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8695559
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T01:04:05+00:00 2026-06-13T01:04:05+00:00

SQLFiddle Link I’ve got an SQLite database with a bunch of test/exam questions. Each

  • 0

SQLFiddle Link

I’ve got an SQLite database with a bunch of test/exam questions. Each question belongs to one question category.

My table looks like this:
so_questions table

The goal
What I’m trying to do is select 5 random questions, but the result must contain at least one from each category. The goal is to select a random set of questions with questions from each category.

For example, the output could be question IDs 1, 2, 5, 7, 8, or 2, 3, 6, 7, 8 or 8, 6, 3, 1, 7.

ORDER BY category_id, RANDOM()
I can get a random list of questions from SQLite by executing the SQL below, but how would I make sure that the result contains a question from each of my categories?

SELECT ORDER BY category_id, random

Basically, I’m looking for something like this, the SQLite version.

I would like to get only 5 results, but one(or more) from each category, with all the categories represented in the result set.

Bounty
Added a bounty because I’m curious whether or not it is possible to accomplish this in SQLite only. I can do it in SQLite+Java, but is there a way to do this in SQLite only? 🙂

SQLFiddle Link

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T01:04:06+00:00Added an answer on June 13, 2026 at 1:04 am

    The key to the answer is that there are two kinds of questions in the result: for each category, one question that must be constrained to come from that category; and some remaining questions.

    First, the constrained questions: we just select one record from each category:

    SELECT id, category_id, question_text, 1 AS constrained, max(random()) AS r
    FROM so_questions
    GROUP BY category_id
    

    (This query relies on a feature introduced in SQLite 3.7.11 (in Jelly Bean or later): in a query SELECT a, max(b), the value of a is guaranteed to come from the record that has the maximum b value.)

    We also have to get the non-constrained questions (filtering out the duplicates that are already in the constrained set will happen in the next step):

    SELECT id, category_id, question_text, 0 AS constrained, random() AS r
    FROM so_questions
    

    When we combine these two queries with UNION and then group by the id, we have all the duplicates together. Selecting max(constrained) then ensures that for the groups that have duplicates, only the constrained question remains (while all the other questions have only one record per group anyway).

    Finally, the ORDER BY clause ensures that the constrained questions come first, followed by some random other questions:

    SELECT *, max(constrained)
    FROM (SELECT id, category_id, question_text, 1 AS constrained, max(random()) AS r
          FROM so_questions
          GROUP BY category_id
          UNION ALL
          SELECT id, category_id, question_text, 0 AS constrained, random() AS r
          FROM so_questions)
    GROUP BY id
    ORDER BY constrained DESC, r
    LIMIT 5
    

    For earlier SQLite/Android versions, I haven’t found a solution without using a temporary table (because the subquery for the constrained question must be used multiple times, but does not stay constant because of the random()):

    BEGIN TRANSACTION;
    
    CREATE TEMPORARY TABLE constrained AS
    SELECT (SELECT id
            FROM so_questions
            WHERE category_id = cats.category_id
            ORDER BY random()
            LIMIT 1) AS id
    FROM (SELECT DISTINCT category_id
          FROM so_questions) AS cats;
    
    SELECT ids.id, category_id, question_text
    FROM (SELECT id
          FROM (SELECT id, 1 AS c
                FROM constrained
                UNION ALL
                SELECT id, 0 AS c
                FROM so_questions
                WHERE id NOT IN (SELECT id FROM constrained))
          ORDER BY c DESC, random()
          LIMIT 5) AS ids
    JOIN so_questions ON ids.id = so_questions.id;
    
    DROP TABLE constrained;
    COMMIT TRANSACTION;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Quick update -- SQLFiddle link: http://sqlfiddle.com/#!2/d038f/2 I think it's a relatively straight forward one...
Check this example before reading the question - http://www.sqlfiddle.com/#!2/fcf3e/8 The following data comes from
This sqlfiddle link seems to retain state across invocations: http://sqlfiddle.com/#!2/125bc/1 It contains this schema
This question is similar to but different from other SO questions involving removal of
This is the more advanced sequel to an earlier question. Here's a link to
Check out my SQLFiddle here ( link ) In SQL Server 2008, I have
http://sqlfiddle.com/#!3/e4891/1 for the above resulting query(which pivots data) I want to run my one
I have the following SQLFiddle , i can group the results by time, count
Here's the basic guts of my schema and problem: http://sqlfiddle.com/#!1/72ec9/4/2 Note that the periods
I have these tables in a MySQL database: CREATE TABLE `product` ( `idProduct` int(10)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.