1

Let's say I have a table of customer addresses:

Name           |   AddressLine
-------------------------------
John Smith      | 123 Nowheresville
Jane Doe        | 456 Evergreen Terrace
John Smith      | 999 Somewhereelse
Joe Bloggs      | 1 Second Ave

I would like to return two random rows from this table, but I do not want to return two rows with the same Name (example of what I don't want):

Name           |   AddressLine
-------------------------------
John Smith      | 123 Nowheresville
John Smith      | 999 Somewhereelse

How can I do this in Postgres?

0

1 Answer 1

3

Here is one method:

select distinct on (name) t.*
from t
order by name, random();
Sign up to request clarification or add additional context in comments.

2 Comments

Will that ever return the second row for John Smith? 999 Somewhereelse?
@LukeSchlangen . . . It could. random() is random.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.