Java – How to select 10 random records in JPQL?

How to select 10 random records in JPQL?… here is a solution to the problem.

How to select 10 random records in JPQL?

I have to randomly select 10 records from the user table

Below is an SQL query that gives a random 10 records.


What are the alternatives to JPQL and do we have Random() support for JPQL? IS USING RANDOM() A GOOD HABIT?


I DON’T KNOW IF THERE IS RANDOM IN JPA. As an alternative solution, you can use this trick:

Query queryCount = em.createQuery("SELECT COUNT(u) FROM UserTable u");
Long size = (Long) queryCount.getSingleResult();

I use this way of Java8, you can use the way you see it better to generate random indexes
int[] index = new Random().ints(0, size, 10).toArray();

Query query = em.createQuery("SELECT u FROM UserTable u WHERE INDEX(u) IN :indexs");
query.setParameter("indexs", index);
List<UserTable> listUsersRandom = query.getResultList();

The big picture

This solution is based on INDEX

  • First query – Find out the size of the object
  • Generates an index list between 0 and the size of the list
  • Second query – Select the objects in this generated list

Related Problems and Solutions