A database index is a separate, organized structure that helps a database locate qualifying rows without inspecting every row in a table. If you are asking what a database index is, how a SQL index works, whether a B-tree index makes queries faster, or why indexes slow down inserts, the central answer is that an index exchanges storage and maintenance work for more efficient searches. The database can use the index as a route to records rather than as a replacement for the records themselves.
In a relational database such as PostgreSQL, an index usually associates one or more column values with information that helps the engine find corresponding table rows. Its usefulness depends on what a query asks, how the data are distributed, and how much work the engine expects to save. A very selective lookup can benefit dramatically; a query that needs almost the entire table may not. There is no universal rule that every column should have an index.
This guide explains database indexing from first principles, including SQL WHERE clauses, B-tree organization, equality and range lookups, composite indexes, unique constraints, partial and expression indexes, query plans, and the costs of keeping indexes current. It includes a reproducible worked example and practical distinctions from hash tables, caches and full-text search. The goal is to help you reason about a real workload instead of memorising slogans about speed.
The problem an index solves
Imagine a school library with 80,000 accession records. Each record stores a book identifier, a title, a borrower, a due date and a return status. If the records arrive without any predictable order and you want the borrower of book 57261, the most direct algorithm is to read records until the matching identifier appears. In the worst case, you inspect all 80,000; with a uniformly random position, the average is about 40,000.5 inspections for a successful search. The calculation assumes a simple linear scan and is an illustration rather than a measured database benchmark.
You could instead maintain a sorted list of identifiers connected to record locations. That additional list is the basic idea behind an index: read a much smaller route map to identify the relevant record. There is a cost. You must create the list, store it, and adjust it whenever relevant identifiers or record locations change. Whether the trade is worthwhile depends on how frequently a question is asked and how often the underlying data change.
A first-principles model: locate, read, maintain
There are three jobs in database retrieval. First, interpret the condition: which rows satisfy the question? Second, locate candidates: which physical or logical data locations are worth examining? Third, return the requested values while enforcing transaction rules. An index mainly helps with the second job, although some index structures can supply enough values to avoid extra table reads under appropriate conditions. SQL specifies the desired result, not a mandatory procedure for obtaining it.
It is useful to treat the index as a promise with a maintenance bill. When an indexed column changes, the engine must preserve an association between the new key and the appropriate row. When a row is inserted or removed, index state generally changes as part of normal database maintenance, with implementation details governed by the storage engine and concurrency model. The promise is not free, but it can make repeated questions much cheaper.
Why sequential scans are not automatically bad
A sequential table scan reads the relation systematically and evaluates each row against the predicate. That sounds primitive, but ordered reading can be efficient, particularly when records are contiguous, the table is small, or a large proportion of rows will qualify. A database engine can exploit buffering, sequential I/O, parallel workers and vectorised or batch-oriented processing where supported. Reading many pages in order may be less expensive than fetching many scattered pages one by one.
Suppose a school has 50 students and asks for the names of all 50. An index on student ID adds little: the engine has to return everyone. Likewise, a table with a million entries queried for 900,000 may be better scanned. A good database designer does not regard a sequential scan as evidence of failure. The relevant question is whether an alternative path would reduce total elapsed work, including the cost of following index entries.
What an index stores and what it does not
An ordinary secondary index commonly stores key values together with pointers or row identifiers, but the exact representation varies across database engines and access methods. That distinction matters because the index is not necessarily a duplicate of the whole table. A book catalogue can contain titles and shelf locations without holding every page of every book; similarly, an index can direct retrieval without containing every non-indexed field of a record.
A primary-key constraint identifies rows according to a declared uniqueness rule. A database may implement it using an index, but a primary key is a logical integrity promise and an index is a physical access structure. Different products handle clustered placement, heap storage and automatically created indexes differently. When reading documentation, separate these logical rules from storage-specific implementation choices. The phrase ‘indexed table’ alone tells you little about how rows are physically arranged.
Why a B-tree is a useful structure
A B-tree family index maintains keys in a balanced, search-friendly arrangement. Its nodes hold multiple ordered keys and references to children or data entries, so each comparison can narrow the search to a smaller region. Balanced height prevents the pathological long chains that a poorly shaped binary search tree could develop. Database pages are relatively large, and the branching factor can be high, which keeps a search path short even when there are many records.
You need not know the precise page format to understand the mechanism. At each level, a comparison directs the search toward the subtree whose key range can contain the answer. Leaf entries connect matching values to rows or other database structures. Inserts may require local changes, splits or other maintenance, but the tree remains navigable. PostgreSQL’s documentation describes B-tree indexes as the default for many equality and ordered-comparison operations, including ranges.
Equality versus range searches
An equality predicate asks for keys matching a target, such as a pupil identifier equal to 312. A range predicate asks for keys between boundaries, such as due dates in the next seven days. An ordered B-tree can be useful for both because adjacent key values are arranged systematically. After navigating to the first qualifying position, the engine may visit neighbouring entries until the range ends.
A pure hash index organizes keys for equality-oriented access and generally does not provide the same ordered traversal. That is why ‘hashes are fast’ does not answer whether a database should use a hash index for a range query. The operation matters more than the fashion of the data structure. Even for equality, an index is valuable only if the optimizer predicts the path will be cheaper than alternatives.
A carefully worked example: lookup comparisons
Assume a fictional table has exactly 1,000,000 rows and a uniformly positioned unique identifier. A linear scan for an existing row requires between 1 and 1,000,000 row examinations; the expected count under the uniform-position assumption is (1 + 1,000,000) / 2 = 500,000.5. If each row check were equally costly, that would be the simple algorithmic baseline. It is not a claim that a real server takes 500,000 disk reads.
Now imagine, solely for arithmetic illustration, an ideally balanced search structure that reduces the candidate set by a factor of 100 at each navigational step. One million divided by 100 becomes 10,000; divided by 100 again becomes 100; divided a third time becomes 1. That makes three conceptual reductions before a final lookup, rather than inspecting a large fraction of the million rows. Real B-tree implementations perform page-level operations and may require fetching heap pages, so the precise speed ratio cannot be inferred from these counts. The lesson is about the shape of the search.
Why illustrative complexity is not a benchmark
Textbooks commonly describe a tree search as logarithmic rather than linear in the number of indexed entries. If the branching factor is b and the number of keys is N, the tree height is on the order of log base b of N. This relationship explains why indexed lookups scale favourably, but it omits important constants and real-world effects such as cache hits, disk latency, row visibility checks and concurrent transactions.
It would therefore be misleading to divide 500,000.5 by three and promise a comparable real-world acceleration. The sequential scan can process many rows efficiently, while index traversal can trigger additional random accesses. Planning, sorting and network transfer also take time. A reproducible benchmark has to report the actual query, row distribution, hardware, cache state and execution plan, not just an impressive theoretical comparison.
Reading a basic SQL query
Consider the query SELECT borrower FROM loans WHERE book_id = 57261. The SELECT clause names the requested output; FROM identifies the relation; WHERE defines the condition. The optimizer may consider an index on book_id because the condition is an equality against a specific key. If book_id is unique or highly selective, very few rows are expected to match, and the index path could be attractive.
Compare SELECT borrower FROM loans without a WHERE clause. Returning all borrowers generally entails reading information for the whole table. Adding an index on book_id does not make that information unnecessary. Also notice that book_id and borrower are different columns: if an index has only book_id, the engine may need to visit the table to retrieve borrower. These ordinary examples explain why the requested output columns and the filter must be evaluated together.
Selectivity and cardinality
Selectivity describes how narrow a condition is, while cardinality is used in database discussions for counts or numbers of distinct values, depending on context. A condition selecting one row from a million is much more selective than a condition selecting 700,000. A column with two common values, such as a nearly evenly split active flag, may be a poor stand-alone candidate for some workloads because each value retrieves so many rows.
But do not use cardinality as a magical rule. A low-cardinality column can still be valuable in a partial or composite index, and some query shapes can exploit bitmap combinations. The engine needs estimates of how values occur together, how many rows qualify and how expensive the underlying pages are to access. Ask what result set the query needs, not merely how many different labels a column contains.
Why the query planner matters
PostgreSQL, like other sophisticated databases, has a planner or optimizer that estimates alternative execution paths and selects one with an attractive expected cost. It can choose a sequential scan, index scan, bitmap index scan or other plan depending on the SQL and available structures. An index existing on disk does not force the planner to use it. Nor should developers normally treat the chosen path as a fixed promise.
Statistics influence those estimates. If a table has recently grown or its value distribution has changed, old estimates may point the planner toward a poor choice. PostgreSQL documentation recommends collecting statistics with ANALYZE before drawing conclusions about index usage. The correct diagnostic begins with evidence from real workloads, not with a command that turns off sequential scans to make an index appear essential.
What EXPLAIN tells you
EXPLAIN reveals the execution plan that PostgreSQL proposes. EXPLAIN ANALYZE actually runs a query and adds observed measurements, which is powerful but has consequences for queries that modify data. In a controlled environment, a reader can compare scans, estimated and actual row counts, elapsed time, loops and conditions. Look at where work accumulates, not at the mere presence of the word Index.
If estimated rows differ greatly from observed rows, the planner’s knowledge of the data may be inadequate. If the plan fetches many heap pages after an index lookup, random access may dominate. If execution returns thousands of large records over a network, transfer costs may eclipse lookup costs. Good diagnosis separates index-search efficiency from the larger end-to-end path that delivers a useful result.
Composite indexes and leftmost prefixes
A composite index uses multiple fields as an ordered key. For a fictional attendance table often searched by school_id and attendance_date, an index on (school_id, attendance_date) can be useful because queries first restrict to a school and then scan a date interval. The ordering of columns influences which predicates efficiently narrow the search. It is not enough to know that both names appear somewhere in the index.
Imagine a printed directory sorted first by school and, within each school, by date. Finding dates for one school is straightforward. Finding every entry for an isolated date across all schools requires visiting many school sections. Actual PostgreSQL planner capabilities include nuances and evolving access methods, so ‘the second column can never be used’ is too absolute. Yet the directory analogy gives a correct starting point: order indexes around real recurring questions.
Covering and index-only scans
Sometimes an index stores or exposes all columns needed to answer a query, reducing the need for a separate table lookup. In PostgreSQL, INCLUDE columns can make some indexes covering for particular queries. However, a supposed index-only scan is not guaranteed to avoid all heap access: the engine may need to check row visibility under its concurrency system. Physical page state and maintenance therefore influence the actual benefit.
This is a useful reminder that databases are transactional systems rather than static dictionaries. A result must be correct under concurrent updates and deletions. An index entry alone might reveal where a record exists, but returning the right version of that record can require extra verification. When measuring index-only performance, look at the actual heap fetches and workload, not just the attractive plan name.
Unique indexes and integrity
A unique index has a purpose beyond faster searching. It can enforce that no two permitted rows carry the same unique key under the applicable NULL semantics and database rules. Consider a membership table that must not contain two active accounts with the same normalized email address. A correctly designed constraint can reject a conflicting write before the duplicate becomes accepted data, even if two users submit simultaneously.
However, enforcing uniqueness and deciding what should be unique are different tasks. Names are not unique identifiers; phone numbers may be shared or reassigned; email normalization can be nuanced. Indexes cannot rescue a flawed model of identity. Use a real uniqueness rule, understand how the database treats NULL values and expressions, and decide whether the requirement covers all rows or only a subset.
Partial indexes and conditional populations
A partial index includes entries satisfying a condition. Imagine an order system where only five percent of orders are open and support staff mainly search open orders by deadline. A partial index on deadlines with a predicate equivalent to status = ‘open’ may be smaller and more focused than indexing deadlines for every historical order. It still has to be maintained whenever membership in the subset changes.
There is a crucial matching question: can the optimizer establish that a given query’s condition implies the index’s predicate? A logically relevant partial index may not be chosen when the query expression prevents the engine from proving applicability. Developers should inspect documentation and plans rather than assume all equivalent-sounding SQL clauses will behave the same. The index is a data structure governed by query predicates, not an intuitive keyword search.
Expression indexes and transformed values
A user might search for case-normalized names or a derived date rather than a field’s stored representation. An expression index can store an indexed result of a computation, such as a lowercased text value, so that an appropriate matching predicate need not recompute and scan every row. This is different from creating an ordinary index on the untouched source column. The expression and the query must cooperate.
For example, a query comparing lower(email) against a normalized address is not automatically optimized by any arbitrary index on email. Collations, locale behaviour and case-folding assumptions matter, especially for multilingual text. The correct approach is to articulate the equality semantics desired by the application, test the database-supported expression and verify a real plan. Search convenience should never silently change what equality means to users.
B-tree, hash, GIN, GiST and BRIN
PostgreSQL exposes several index methods because one organization cannot fit every data type and predicate. B-tree is the familiar general-purpose choice for orderable comparisons. Hash targets equality operators. GIN is often associated with structures such as arrays and suitable full-text search operations. GiST provides an extensible framework used by some geometric and similarity access patterns. BRIN summarizes ranges of physical blocks and may be attractive where values correlate with storage order.
This is not a ranking from best to worst. A GIN index suitable for text search can be inappropriate for sorting dates; a BRIN index can be compact but imprecise enough to require checking more rows. Operator classes determine exactly which operations a particular index supports. A reliable design asks what operations the application needs, then chooses an index structure whose documented operators and trade-offs match them.
Indexes versus full-text search
Ordinary equality search for a book identifier differs from retrieving paragraphs containing words in varying forms and combinations. Full-text search involves tokenization, lexemes, possibly stemming, stop-word handling and ranking mechanisms. PostgreSQL can index suitable document representations with methods such as GIN. A B-tree on raw paragraphs does not by itself provide a search engine for natural-language questions.
This matters for an educational article collection and its chatbox. Search may involve exact post titles, related words, synonyms and semantic meaning. A relational index can accelerate specific stored predicates but does not automatically resolve synonyms or infer concepts. Editors should maintain accurate titles, metadata and links, while search-system designers should choose retrieval methods that actually support the intended queries. The two jobs complement each other.
Indexes versus hash tables
A hash table is a general computing structure mapping keys to locations or values using a hash function and collision handling. A database hash index uses related concepts, but a complete database index must also fit durability, concurrency, storage, transaction visibility and recovery requirements. Conversely, a B-tree organizes keys by order, which makes range traversal possible. These are related designs with different operating constraints.
Readers who want the separate first-principles account can consult What is a Hash Table?. The important transfer is to avoid equating a theoretical constant-time average lookup in an in-memory structure with an end-to-end SQL response time on persistent data. Physical pages, locks, transaction snapshots, row sizes and query semantics remain part of the cost.
Indexes versus caches
An index tells a system how to find relevant data; a cache attempts to retain data that may be needed again, ideally in a faster location. An indexed query can still be slow on a cold cache. A non-indexed table scan can become relatively fast when relevant pages are already resident in memory. Both mechanisms can operate together, but they solve different problems and carry different resource costs.
The companion explanation What is a Cache? covers reuse and freshness. To diagnose an application, record whether measured performance is a cold-start observation, a warmed-up repeated query or a mixed production workload. A spectacular second run could reflect caching rather than the index change being tested. Responsible performance comparisons vary one factor at a time when possible.
Inserts, updates and deletes are part of the price
An index is not a read-only accessory. Inserting a new row may require changes to multiple indexes, while updates to indexed values can cause related entries to be adjusted. Deleting rows requires the storage engine to manage their index references under its transactional rules. More indexes can therefore mean more storage, write amplification, buffer pressure and maintenance activity, even when individual reads benefit.
Think of a filing office that maintains ten separate catalogues. Finding a record by any of ten attributes becomes easier, but every correction may require updating several catalogues accurately. The trade-off is particularly important for write-heavy systems, high-ingest logs and tables with frequent updates. The objective is not to maximize the number of indexes; it is to minimize the total cost of the workload while preserving correctness.
The hidden cost of extra storage
Indexes occupy bytes, often many pages, and they consume resources in backups, replication, maintenance and cache management. The storage-to-table ratio depends on key widths, included attributes, data distribution, fill levels and implementation. There is no honest universal percentage that applies to all SQL databases. Creating a wide composite index on long text fields can have different consequences from indexing a compact integer key.
A sensible assessment estimates the expected search benefit, measures the added size, and watches write performance. Sometimes a narrow index plus a table lookup is better than a large covering index. Sometimes a single well-chosen composite index can replace several redundant individual indexes. Measurements must include production-like data and the actual operations that matter to users, including ordinary periods of heavy writing.
Concurrency and transactions
Database queries rarely run in isolation on a busy site. Students may submit answers while teachers read progress, orders may arrive while finance reports run, and users may edit profiles while search requests continue. Index structures must remain correct when these actions overlap. Transactional databases coordinate changes so that a query sees data consistent with its isolation rules rather than half-applied index updates.
PostgreSQL uses multi-version concurrency control, which creates practical distinctions between an index reference and the visibility of the corresponding tuple to a transaction. This is one reason an index does not guarantee that every candidate can be returned without examining the table. When explaining index performance, include concurrent workload and data freshness instead of relying only on idealized single-user search diagrams.
Distribution, skew and hot values
Real data rarely distribute neatly. In a library, most loans may be due on a small set of school calendar dates. In an ecommerce site, one popular category can dominate traffic. In a support database, nearly every issue might initially have status ‘open’. A filter on an extremely common value can return so many rows that an index contributes little or even adds work.
Histograms and other statistics help the planner estimate these patterns. Yet relationships between columns can complicate estimates: school_id and campus may be strongly associated, for example. A query involving both is not equivalent to multiplying two independent probabilities. When a supposedly selective index behaves poorly, inspect the actual result count and joint distribution rather than assuming the hardware is underpowered.
Sorting, ORDER BY and LIMIT
An index can sometimes deliver rows in a useful key order, potentially reducing or avoiding a separate sort. Consider retrieving the ten most recent completed assignments for one class. An index whose leading fields match the class filter and whose later fields correspond to the desired ordering might permit efficient retrieval of the first few qualifying entries. The exact result depends on ordering direction, NULL rules and the query plan.
This is a different benefit from finding a single matching record. A sorted index can help answer ‘which ten first?’ without processing every matching row in the same way as an unsorted full retrieval. But an index may still be undesirable if the filter is broad and table access is expensive. Compare execution plans for the complete SELECT, WHERE, ORDER BY and LIMIT combination, never for one clause in isolation.
Joins and lookup paths
Many useful queries combine tables. A pupil’s timetable may be in one table, classroom details in another and attendance records in a third. Joining them requires identifying related rows, often through key relationships. An index on an appropriate join column can make repeated lookups efficient, especially when one side of a join produces a modest number of keys.
The planner can also choose hash joins, merge joins or other strategies that do not use a particular index path. A database index does not mean a hash join must be present, and a hash join is not the same thing as a hash index. These distinctions help readers decode execution plans without confusing the names of algorithms. Ask which data relation supplies keys, how many matching records exist and whether indexes alter the total work.
Index maintenance and fragmentation
As data change, index pages may become less densely packed or require reorganizing according to the engine’s rules. Pages split, obsolete entries are eventually reclaimed and statistical descriptions drift. Maintenance tools vary among products: PostgreSQL supports operations such as VACUUM, ANALYZE and REINDEX with distinct purposes. They are not interchangeable magic commands and some can place operational demands on a production service.
Routine decisions should be grounded in evidence: table growth, index size, bloat indicators, actual query latency and write rates. Rebuilding every index on a fixed schedule can waste resources or create avoidable disruption. Conversely, ignoring actual corruption or pathological bloat is not acceptable. Use version-specific official documentation and an operational plan suitable for your database, not copied maintenance recipes.
The reliability dimension
An index is part of a system that must remain correct after crashes and concurrent writes. Storage engines use logging, checksums, recovery procedures and integrity controls appropriate to their architecture. An index that quickly returns the wrong rows would be worse than a slow scan. Therefore the optimizer and storage layer preserve semantic correctness while choosing an access path.
If an application produces inconsistent results, do not immediately blame an index. Verify SQL predicates, transactions, permission filters, data types, collations and the current data. In rare cases where corruption is suspected, follow the vendor’s documented diagnostics and backup-preserving procedures rather than forcing arbitrary repairs. Performance work is an optimization of a correct process, never a substitute for correctness.
The difference between logical and physical design
The logical model asks what entities and relationships exist. The physical design asks how records and access structures should be stored for practical performance. A pupil table should represent a pupil correctly whether or not it has a particular secondary index. Likewise, a unique key or foreign-key relationship is a semantic requirement that may cause or motivate index creation, but is not identical to any one chosen access route.
This distinction prevents schema design from degenerating into a collection of speed tricks. Name columns according to real concepts, define constraints, and understand workload boundaries first. Then use indexes to support recurring operations. When requirements change, the physical design can evolve while preserving the logical meaning of the data. That separation is a powerful principle transferable to many engineering decisions.
Measuring the right outcome
There are several measures of index success: median query latency, tail latency under load, throughput, write amplification, storage cost, CPU time and the time a user waits for an answer. A reduction in one narrow query’s milliseconds may be outweighed by worse inserts or higher operational complexity. A test that runs an individual statement once is weak evidence for a long-lived production decision.
Create a baseline with representative row counts, query parameters and realistic concurrency. Record the plan and actual measurements, change the index design, then repeat under comparable conditions. Inspect regressions across the workload instead of reporting only the winning query. The database’s goal is to support correct useful applications, not to achieve an index-scan badge on every EXPLAIN screen.
A school attendance case study
A school’s attendance dashboard often asks for one class on one day, while a monthly report asks for every class over a date interval. Those are different access patterns. The former may benefit from an index beginning with class_id and then attendance_date. The latter may benefit from a different route or from scanning data in date order. Adding both indexes has a maintenance cost that needs justification by frequency and response requirements.
The same application might update attendance status many times during morning registration. A broadly indexed status column could add work while providing little read value if almost all rows share one state. The correct design starts by listing actual questions: ‘Who is absent today?’, ‘Which records are missing?’, ‘How many lessons were attended this term?’ Then test candidate indexes for those specific questions and their usage volumes.
A product catalogue case study
An online catalogue might support product lookups by exact stock-keeping unit, price range, category and phrase search. These are not one generic search problem. An exact identifier can use a unique constraint and associated index. A price range may exploit an ordered index. Category and price combinations might justify a composite design. Full-text descriptions require suitable linguistic indexing or an external search architecture.
Suppose 95 percent of browsing traffic asks for items in stock, while archival product data are rarely touched. A partial index may be useful, but only if queries consistently express the relevant predicate and writes remain manageable. This scenario shows why the storage of old rows, the shape of user questions and the maintenance burden all affect choices. No single ‘index everything’ answer fits the catalogue.
A monitoring-log case study
A high-volume log table receives time-stamped events continuously. Newest-event and time-window searches are common, but old rows are rarely modified. When timestamp values correlate closely with physical insertion order, a block-range summarizing structure such as BRIN can sometimes be attractive because it stores compact summaries rather than a separate entry for every row. Whether it wins depends on the storage pattern and query granularity.
The same database may need exact lookups by request_id, which have different selectivity and access needs. A B-tree on request_id might coexist with a BRIN on time. This is an example of complementary rather than competing techniques. A log query that filters both user and time must still be benchmarked. Never assume the existence of a specialist index removes the importance of realistic query plans.
A practical decision procedure
Write down the five most important SQL queries and their frequency. For each, note whether it filters by equality, range, membership, text relevance or spatial relationship; how many rows it returns; and what order it needs. Then inspect existing constraints and indexes. Creating another index without checking for overlap may cost storage and writes while contributing little new coverage.
Next, use EXPLAIN and representative timing to locate the expensive step. Consider a narrow index that directly addresses the bottleneck, or a revised query that expresses the intended condition more clearly. Re-test reads and writes. Record why an index exists so future maintainers do not remove a useful one or preserve a redundant one indefinitely. Repeat when the workload or data distribution meaningfully changes.
Common mistakes: diagnosis, not blame
Mistake one is believing every index speeds every query. Correct diagnosis: identify the predicate and estimated number of qualifying rows. Mistake two is assuming a B-tree on one column automatically handles arbitrary transformations of that column. Diagnosis: compare the expression in SQL with the indexed key. Mistake three is treating a primary key, clustered storage and a secondary index as synonyms. Diagnosis: inspect the particular database’s documentation.
Mistake four is benchmarking with a tiny artificial table. Diagnosis: use realistic cardinality, selectivity and distribution. Mistake five is celebrating an index scan without measuring elapsed work. Diagnosis: look for heap fetches, rows removed by filters and total timing. Mistake six is forgetting write costs. Diagnosis: measure inserts and updates as well as SELECT. These checks convert vague performance claims into testable engineering questions.
How to transfer the idea beyond databases
An index is a general form of precomputed organization. Dictionaries have alphabetic entry points; museum catalogues have accession numbers; maps have coordinate systems; search services maintain inverted term lists; warehouses use location labels. Each organizes information in advance because expected future queries justify the work. The right arrangement depends on the question being asked.
The transfer principle is that lookup speed usually comes from constraints on search space, purchased with structure and upkeep. A perfectly organized alphabetical catalogue is not ideal when visitors search by publication year or topic. Likewise, one SQL index cannot answer every question. To teach this to a student, ask them to design two different filing systems for the same collection and explain which questions each makes easier.
FAQs: Is an index a copy of the table?
Usually not. It is a separate access structure storing keys and enough information to lead toward rows, with implementation-specific variations. Some indexes also contain additional columns to support covering or index-only plans. A primary or clustered index in one database product may interact with physical row storage differently from a PostgreSQL secondary index. The correct answer depends on the engine and index type, not just the word ‘index’.
FAQs: Does creating an index guarantee a faster query?
No. The planner may reject it because the filter returns too many rows, the table is small, the predicate cannot use the available operator class, or index traversal costs more than a scan. Sometimes it speeds a particular SELECT but slows INSERT and UPDATE enough to reduce overall system throughput. Compare measured workload costs before and after creation rather than assuming improvement from the index’s existence.
FAQs: Can an index make an application slower?
Yes. Additional indexes consume storage, cache resources and maintenance work whenever indexed entries need updating. An index can also enable a query plan that turns out poorly under stale estimates, though the planner tries to choose efficient alternatives. The effect depends on read-to-write ratio, key size, data distribution and query patterns. Index design is resource allocation, not a free acceleration switch.
FAQs: What index should a beginner learn first?
Learn the ordered B-tree and an equality query with a unique identifier. Then learn a date range, a two-column composite index and a query plan. These examples explain the majority of foundational concepts: narrowing candidate rows, key order, selectivity and maintenance costs. Next, study full-text or spatial indexing only when an actual query needs those functions. Starting from real questions leads to more durable understanding.
FAQs: What does a database index have to do with SEO?
Both use the word ‘index’, but the operations are different. A database index is a data structure for efficient lookups inside a database. Search-engine indexing involves discovering, processing and representing content so a search system can retrieve results, with ranking systems then deciding relevance. Adding an SQL B-tree does not cause a webpage to be indexed by Google. Accurate article titles and accessible pages address a different layer of retrieval.
FAQs: Should every foreign-key column be indexed?
Not as an unqualified universal claim. The value depends on database product, query workload, referential actions and how many related rows must be found. A referenced unique or primary key often already has an associated index, while a referencing column may benefit from a separate index for joins and parent-row updates or deletes. Check the engine’s specific constraint behaviour and benchmark the operations your application actually performs.
FAQs: Why might the optimizer ignore a new index?
It may estimate that few pages would be saved, that too many rows qualify, or that the index does not support the operator used in the query. Stale statistics, data correlation or expression mismatch can also contribute. Run ANALYZE where appropriate, inspect EXPLAIN and compare estimates with actual counts. Do not treat forcing the planner to use the index as proof that the resulting plan is best.
FAQs: Can the same table have multiple indexes?
Yes, and frequently does. Different indexes can serve different queries, including exact identifier lookup, ordered date retrieval and specialized full-text search. Each additional structure costs disk space and ongoing maintenance, so overlapping indexes should be justified. A good design has a manageable set of access paths corresponding to demonstrated workloads rather than every imaginable combination of fields.
FAQs: Can an index replace a cache?
No. An index structures where and how to locate data; a cache holds data or results for reuse. A workload can benefit from both. The effectiveness of a database index is influenced by caching because index and table pages may be resident in memory. To compare performance, state the cache conditions. Treat caching, indexing and query design as different levers in the same application.
FAQs: What should students remember?
An index answers a practical question: ‘How can we narrow the search before reading all records?’ The useful mental model is a maintained route map, not an enchanted speed button. Remember the three costs—finding rows, reading them, and updating the route map—and learn to reason from a specific query. Once that model is clear, B-trees, hash methods and query plans become meaningful rather than mysterious.
Sources and further reading
The current PostgreSQL documentation on indexes is the authoritative primary reference for supported index families, covering methods, multicolumn indexes, uniqueness and index-only retrieval. Its index introduction explains access and write overhead. The index usage guidance documents statistics and plan inspection. These links identify the database product being discussed rather than claiming that every vendor implements identical internals. The worked counts and school examples above are explanatory constructions, not measured PostgreSQL benchmarks.
