Sobes.tech
Junior — Middle

How can you create an index for a table in a database management system?

sobes.tech AI

Answer from AI

To create an index in a database, the SQL command CREATE INDEX is used. Indexes speed up data search and sorting by specific columns.

Example of creating an index for the users table on the last_name column:

CREATE INDEX idx_users_last_name ON users(last_name);

If you need to create a unique index that prohibits duplicate values:

CREATE UNIQUE INDEX idx_users_email ON users(email);

In Java, such commands are usually executed using JDBC, for example:

String sql = "CREATE INDEX idx_users_last_name ON users(last_name)";
try (Statement stmt = connection.createStatement()) {
    stmt.executeUpdate(sql);
}

It is important to remember that creating indexes improves read speed but may slow down insert and update operations.