SQL Indexing Best Practices
Before we show best practices, let’s look at how database indexes work. A database index is a type of data structure like an array or hash. Without any indexes our database has to scan every row in the table. What if this table had 20 million rows? Running a single query consume a lot of resources and if this table used by an application it could have thousand similar queries. The solution to this problem is to use indexes. We want to index the data is looked up most frequently.
SELECT *
FROM users
WHERE city = 'Berlin'
ORDER BY balance DESC;CREATE INDEX city_idx ON users(city);SQL index is basically a shorted list with the values from one or more rows of a table and a pointer value that tells the database where to find.
Indexes are automatically maintained by database engine. This means that whenever a DML operation is performed on the table, the same operation is done on each of the indexes.
For queries that are going to be run frequently we can make this even more efficient by multi-cloumn index.
CREATE INDEX idx_city_balance ON users (city, balance DESC);Don’t create more indexes than you need.
-- Less Frequent Query:
SELECT *
FROM users
WHERE created_at >= '2023-01-01';
-- Avoid Unnecessary Indexes: If the created_at query is less frequent and not resource-intensive, you might choose not to create an index for it.
CREATE INDEX idx_created_at ON users (created_at);Try to avoid large indexes.
-- Indexing the first 255 characters of a large column
CREATE INDEX idx_large_text ON users (large_text_column(255));When in doubt, use EXPLAIN
EXPLAIN SELECT *
FROM users
WHERE city = 'Berlin'
ORDER BY balance DESC; QUERY PLAN
---------------------------------------------------------------------------------
Sort (cost=12.50..12.51 rows=100 width=200)
Sort Key: balance DESC
-> Seq Scan on users (cost=0.00..10.00 rows=100 width=200)
Filter: (city = 'Berlin')Index hint is a directive, you can provide to the database query optimizer to force it to use spesific index for query. In Oracle we can define this way:
SELECT /*+ INDEX(users idx_city_balance) */
*
FROM users
WHERE city = 'Berlin'
ORDER BY balance DESC;
Yorumlar
Yorum Gönder