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
-->-->INPUT TABLESTable ASize: 1000Table BSize: 2000Table CSize: 500JOIN CONDITIONS:A ⟷ B: selectivity 0.1B ⟷ C: selectivity 0.2OPTIMIZATION STEPS1Single TablesCost = 0 each2Evaluate PairsA,B: 200k | A,C: 500k | B,C: 1M3Build TripleCompare all combinations4Select OptimalMinimum cost pathCOST COMPARISON:[A,B,C]: 210k[A,C,B]: 505k[B,C,A]: 1.2MWINNER: [A,B,C]OPTIMAL PLANExecution Order:[A, B, C]Total Cost: 210,000Step-by-step:1. Join A ⟷ B Cost: 200,0002. Join (A⟷B) ⟷ C Cost: 10,000Total: 210,000Key Insight:Dynamic programming builds optimal join plans by combining smaller optimal subplans,avoiding the exponential cost of trying every possible join order permutation.TutorialsPoint - Database Query Optimizer | Dynamic Programming Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
22.3K Views
Medium-High Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen