A query optimizer is database software that automatically determines the most efficient way to execute SQL queries. It analyzes multiple potential execution paths and selects the one with the lowest estimated cost.
When you submit a SQL query, the query optimizer doesn't just execute it as written. Instead, it:
| Type | Description | Example Systems |
|---|---|---|
| Cost-based | Uses statistical data about tables to estimate costs | Oracle, SQL Server, PostgreSQL |
| Rule-based | Follows predefined heuristic rules | Older MySQL versions |
| Iterative changing | Refines plans during execution | Some NoSQL databases |
Query optimizers exist in virtually all relational database management systems (RDBMS), including:
They're also found in some NoSQL databases and big data processing frameworks.
Many people assume query optimizers simply make queries run faster by any means necessary. In reality, they work within strict constraints:
For example, a query optimizer won't add indexes that don't exist, even if they would improve performance.
Consider joining two large tables, orders and customers. A naive approach might scan both tables completely. A good query optimizer would:
This approach might reduce execution time.
While query optimizers work automatically, developers can improve their effectiveness by:
For complex queries, examining the execution plan can reveal optimization opportunities.