BBampaa

Lessons › SQL › Deep Dive: Advanced Joins & Subqueries

SQL lesson

RANDOM() and ORDER BY RANDOM() for random sampling

Random sampling shuffles all rows into a completely unpredictable order and then grabs the first few.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Taking Retail QA Samples with ORDER BY RANDOM()

SELECT order_id, status, revenue
FROM orders
ORDER BY RANDOM()
LIMIT 5

Result:

order_idstatusrevenue
random rowvariesvaries
random rowvariesvaries
random rowvariesvaries
random rowvariesvaries
random rowvariesvaries

Step by step

  1. After SELECT, list the column names you want, separated by commas.
    SELECT order_id, status, revenue
  2. FROM tells SQL which table to pull the data from.
    SELECT order_id, status, revenue
    FROM orders
  3. ORDER BY puts the rows in your chosen order.
    SELECT order_id, status, revenue
    FROM orders
    ORDER BY RANDOM()

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed