woshitom
woshitom

Reputation: 5131

Randomly SELECT two distinct rows on a table

| postid | value | title   |
----------------------------
| 1      | 0     | Title 1 | 
| 2      | 1     | Title 2 | 
| 3      | 1     | Title 3 | 
| 4      | 0     | Title 4 | 
| 5      | 4     | Title 5 |

I am trying to select two randomly distinct rows from my table. Is there a way to do it with SQL?

I've tried

SELECT postid
FROM table
WHERE postid > 0.9
ORDER BY RAND( )
LIMIT 2 

Upvotes: 2

Views: 88

Answers (2)

Moyed Ansari
Moyed Ansari

Reputation: 8461

Try this

SELECT DISTINCT postid 
FROM tablename
ORDER BY RAND()
LIMIT 2

Upvotes: 3

Michael Berkowski
Michael Berkowski

Reputation: 270637

Yes, using DISTINCT along with ORDER BY RAND() and LIMIT:

SELECT
  DISTINCT
  postid,
  value,
  title
FROM yourtable
ORDER BY RAND()
LIMIT 2

Upvotes: 2

Related Questions