Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Random Row Sampling Query
00:00
5 left

Random Row Sampling Query

HardSQL · PostgreSQL

Problem

A large product catalog needs an efficient way to retrieve one randomly selected catalog row without sorting the entire table. Write a PostgreSQL query that returns exactly one row from big_table while avoiding a full-table ORDER BY random() operation.

Output

  1. Return at most one row with columns id and name.
  2. Select the row through an efficient sampling strategy, with a fallback for cases where the primary sampling method returns no rows.
  3. Preserve NULL values in name when the selected row has no name.
  4. Return no rows when the table is empty.

Schema

big_table
ColumnTypeDescription
idPKINTEGERUnique catalog row identifier
nameVARCHAR(200)Catalog item name
Tablesbig_table
Interviewer

Your question is Random Row Sampling Query. Start with the requirements and the one table in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePostgreSQL
You need to log in / sign up to run or submit.Ln 1
Run your query to see results here.