Search code examples
postgresqlrandomsql-order-bysql-likealphabetical-sort

Get random record using like query in postgres


I am having an table with email_address as a primary key and there is no id column in the table.

So whenever I hit the query like

select email_address from data  where email_address like '%@gmail.com' limit 10

it gives result alphabetically means all the email-id starting with a (if its present).

But I don't want like alphabetic order, I want result like

email_address
___________________
[email protected]
[email protected]
[email protected]
[email protected]

Pick randomly email address which ends with gmail.com, not by inserted order or not by alphabetic order.

NOTE : I have like 1000's of result starting with each alphabet when I pick just 100 then I want not only all the result starting with 'a'


Solution

  • If you order them randomly and then pick the first top 10 results I guess that could work. It would be something like this:

    SELECT email_address FROM data
    WHERE email_address LIKE '%@gmail.com'
    ORDER BY RANDOM()
    LIMIT 10