问题
Is it right to expect that, for the typical modern RDBMS, querying by one specific primary key is as fast as querying a hashtable by key?
Or is there "actual work" done to traverse the table and track down the primary key value? That seems unthinkably wasteful, even if there are automatic indexes for primary keys.
回答1:
Database operation involves access of secondary memory unit (Disk). And to achieve efficiency important is to reduce block access time(not operations). Complexity of Select query depends on what kind of optimization done.
Because you mentioned =
on key attribute, an equality comparison on key attribute on which the file is ordered(with a primary index), Binary Search is efficient.(which is more efficient then inner search) are used. A binary search usually access log2(Br) block, where Br is number of block a file. (this is wrought calculation you may need to access extra block for indexes also).
It also depends on type of index implementation. If its implemented through multilevel or B, B+ then access time may be further reduce depends on what is number of keys in a node (that further depends how many record can be accommodate in a block).
In heuristic type of optimization generally DBMS system keeps store MAX, MIN, AVG and other kind of information in table catalogs. So if information can be derived from catalog information query execution time may be constant O(1).
Read: Chapter 19 Algorithms for Query Processing and Optimization
回答2:
Let's take InnoDB storage engine. All InnoDB indexes are B-trees. The worst-case search complexity in a B-tree is O(log n). But if a table fits almost entirely in main memory, InnoDB can automatically build a hash index. Adaptive Hash Indexes
来源:https://stackoverflow.com/questions/15727818/is-select-where-primary-key-primary-key-value-o1