Close

JPQL Subquery in WHERE AND HAVING Clauses

[Updated: May 16, 2018, Created: May 16, 2018]

JPA allows usage of subqueries in WHERE or HAVING clauses. Subqueries must be surrounded by parentheses.

Example

Entity

@Entity
public class Employee {
  @Id
  @GeneratedValue
  private long id;
  private String name;
  private String dept;
  private long salary;
  @ElementCollection
  private List<String> phoneNumbers;
    .............
}

Using Subqueries in WHERE And HAVING clauses

public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          persistEmployees();
          findEmployeeByPhoneCount();
          findDeptHavingAboveNetAverage();
          findEmployeeWithLessThanAverageSalary();
      } finally {
          entityManagerFactory.close();
      }
  }

  public static void persistEmployees() {
      Employee employee1 = Employee.create("Diana", "IT", 3000, "111-111-111", "222-111-111");
      Employee employee2 = Employee.create("Rose", "Admin", 2000, "333-111-111", "444-111-111");
      Employee employee3 = Employee.create("Denise", "Admin", 4000, "555-111-111");
      Employee employee4 = Employee.create("Mike", "IT", 3500, "777-111-111");
      Employee employee5 = Employee.create("Linda", "Sales", 2000);
      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(employee1);
      em.persist(employee2);
      em.persist(employee3);
      em.persist(employee4);
      em.persist(employee5);
      em.getTransaction().commit();

      System.out.println("-- Employees persisted --");
      Query query = em.createQuery(
              "SELECT e FROM Employee e");
      List<Employee> resultList = query.getResultList();
      resultList.forEach(System.out::println);
      em.close();
  }

  private static void findEmployeeByPhoneCount() {
      System.out.println("-- Employees who have more than 2 phones --");
      EntityManager em = entityManagerFactory.createEntityManager();
      Query query = em.createQuery(
              "SELECT e FROM Employee e where (SELECT COUNT(p) FROM e.phoneNumbers p) >= 2");
      List<Employee> resultList = query.getResultList();
      resultList.forEach(System.out::println);
      em.close();
  }

  private static void findDeptHavingAboveNetAverage() {
      EntityManager em = entityManagerFactory.createEntityManager();
      System.out.println("-- net average salary --");
      Object singleResult = em.createQuery("SELECT AVG(e.salary) FROM Employee e")
                              .getSingleResult();
      System.out.println(singleResult);

      System.out.println("-- Dept by average salaries --");
      List<Object[]> list = em.createQuery("SELECT e.dept, AVG(e.salary) FROM Employee e GROUP BY e.dept")
                              .getResultList();
      list.forEach(ar -> System.out.println(Arrays.toString(ar)));

      System.out.println("-- Dept having AVG salaries greater than net AVG salary --");
      Query query = em.createQuery(
              "SELECT e.dept, AVG(e.salary) FROM Employee e GROUP BY e.dept HAVING AVG(e.salary) > "
                      + "(SELECT AVG(e2.salary) FROM Employee e2)");
      List<Object[]> resultList = query.getResultList();
      resultList.forEach(r -> System.out.println(Arrays.toString(r)));
      em.close();
  }

  private static void findEmployeeWithLessThanAverageSalary() {
      System.out.println("-- Employees who have less than average salary --");
      EntityManager em = entityManagerFactory.createEntityManager();
      Query query = em.createQuery(
              "SELECT e FROM Employee e where  e.salary < (SELECT AVG(e2.salary) FROM Employee e2)");
      List<Employee> resultList = query.getResultList();
      resultList.forEach(System.out::println);
      em.close();
  }
}
-- Employees persisted --
Employee{id=1, name='Diana', dept='IT', salary=3000, phoneNumbers=[111-111-111, 222-111-111]}
Employee{id=2, name='Rose', dept='Admin', salary=2000, phoneNumbers=[333-111-111, 444-111-111]}
Employee{id=3, name='Denise', dept='Admin', salary=4000, phoneNumbers=[555-111-111]}
Employee{id=4, name='Mike', dept='IT', salary=3500, phoneNumbers=[777-111-111]}
Employee{id=5, name='Linda', dept='Sales', salary=2000, phoneNumbers=[]}
-- Employees who have more than 2 phones --
Employee{id=1, name='Diana', dept='IT', salary=3000, phoneNumbers=[111-111-111, 222-111-111]}
Employee{id=2, name='Rose', dept='Admin', salary=2000, phoneNumbers=[333-111-111, 444-111-111]}
-- net average salary --
2900.0
-- Dept by average salaries --
[IT, 3250.0]
[Sales, 2000.0]
[Admin, 3000.0]
-- Dept having AVG salaries greater than net AVG salary --
[IT, 3250.0]
[Admin, 3000.0]
-- Employees who have less than average salary --
Employee{id=2, name='Rose', dept='Admin', salary=2000, phoneNumbers=[333-111-111, 444-111-111]}
Employee{id=5, name='Linda', dept='Sales', salary=2000, phoneNumbers=[]}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.197: H2 Database Engine.
  • hibernate-core 5.2.13.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

JPQL Subquery in WHERE AND HAVING Clauses Select All Download
  • jpql-subqueries-in-where-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also