Junior — Middle
Is it possible to create a composite index on multiple columns in a database?
sobes.tech AI
Answer from AI
Yes, most database management systems can create a composite index on multiple columns. Such an index speeds up queries that filter or sort data based on a combination of these columns.
In Go, when working with a database, an SQL query is usually used to create an index. For example, for PostgreSQL:
CREATE INDEX idx_name ON table_name (column1, column2);
If you are using an ORM or a library for database interaction in Go, such as GORM, creating a composite index might look like this:
import (
"gorm.io/gorm"
)
type User struct {
ID uint
FirstName string `gorm:"index:idx_name,priority:1"`
LastName string `gorm:"index:idx_name,priority:2"`
}
// During migration, GORM will create a composite index idx_name on FirstName and LastName
Thus, a composite index helps optimize queries that use multiple columns in WHERE or ORDER BY conditions.