Sobes.tech
Junior — Middle

How can a combined index be implemented in a database?

sobes.tech AI

Answer from AI

A composite index is created on multiple columns of a database table and allows speeding up queries that filter or sort data by these columns simultaneously.

In Java, if you use JPA (e.g., with Hibernate), a composite index can be created using the @Table annotation with the indexes parameter.

Example:

import javax.persistence.*;

@Entity
@Table(name = "users", indexes = {
    @Index(name = "idx_name_email", columnList = "name, email")
})
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;

    // getters and setters
}

This creates an index idx_name_email on the name and email columns. Such an index is useful for queries that use both fields in WHERE or ORDER BY clauses.

If working directly with SQL, the creation of a composite index looks like:

CREATE INDEX idx_name_email ON users(name, email);

It is important to remember that the order of columns in the index affects its efficiency: the index is useful for queries starting with the first column of the index.

How can a combined index be implemented in a… - sobes.tech