Database Query Optimizer - Problem
Build a simple database query optimizer that generates and compares execution plans for SELECT queries with JOINs.
Given a query structure with tables, join conditions, and table sizes, your optimizer should:
- Generate different join orders (execution plans)
- Calculate cost estimates for each plan using a simple cost model
- Return the plan with the lowest estimated cost
The cost model uses: Cost = (Table1_Size * Table2_Size) / Selectivity
Where selectivity is estimated as 0.1 for equality joins and 1.0 for cross joins.
Input & Output
Example 1 — Basic Three-Table Join
$
Input:
tables = [{"name":"A","size":1000}, {"name":"B","size":2000}, {"name":"C","size":500}], joins = [{"table1":"A","table2":"B","selectivity":0.1}, {"table1":"B","table2":"C","selectivity":0.2}]
›
Output:
["A","C","B"]
💡 Note:
Optimal order: join A with C first (cross join cost: 500k), then join result with B (selective join cost: much lower than A→B→C)
Example 2 — Chain of Joins
$
Input:
tables = [{"name":"X","size":100}, {"name":"Y","size":200}], joins = [{"table1":"X","table2":"Y","selectivity":0.5}]
›
Output:
["X","Y"]
💡 Note:
With only two tables, the order is straightforward: join X with Y using selectivity 0.5
Example 3 — Single Table
$
Input:
tables = [{"name":"T1","size":1000}], joins = []
›
Output:
[]
💡 Note:
Single table requires no joins, so return empty execution plan
Constraints
- 1 ≤ tables.length ≤ 10
- 1 ≤ table.size ≤ 106
- 0 ≤ joins.length ≤ 20
- 0.01 ≤ selectivity ≤ 1.0
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code