Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to get a random row from my table by id.

My table:

ID|Word     |Dificult|Category_id|
1 |'Dumb'   |'Easy'  | 3         |
2 |'Leopard'|'Medium'| 6         |

If my user selects a category and a difficult, I have pick a random word with user parameters, like:

idRaffle :=;
   -- = An id that postgres will bring me by some raffle function. 
d := 'Easy';
c := 3;
select * from words where id=idRaffle and Dificult=d and Category_id=c

I don't know how to get that random row id (

Note that it must follow the user's selection conditions.

share|improve this question
So you want a random row (from the many) that fit the Difficult = 'Easy' AND Category_id = 3 ? – ypercubeᵀᴹ Oct 14 '12 at 23:23
Excacly, how can I do this? – Bernardo Vale Oct 15 '12 at 0:00
Closely related question on SO. ORDER BY random() LIMIT 1 is actually rather slow because it needs to scan and sort the whole table. Fine for small tables, impractical for big tables. – Erwin Brandstetter Oct 15 '12 at 22:20
up vote 2 down vote accepted

To pick a random row, see:

quick random row selection in Postgres

FROM words
WHERE Difficult = 'Easy' AND Category_id = 3
ORDER BY random()
share|improve this answer
Work fine, thanks xD – Bernardo Vale Oct 15 '12 at 0:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.