Interview Questions/SQL/Task Dependency - Parallel Execution Levels

Task Dependency - Parallel Execution Levels

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a Tasks table and a Dependencies table. A task can only start after all tasks it depends on have completed. Tasks with no dependencies can run immediately (level 1). Write a SQL query to assign an execution_level to each task: the earliest level at which it can run, given all its dependencies must be at a strictly lower level. Return (task_id, execution_level) ordered by execution_level, then task_id. Table: Tasks

Column NameTypeDescription
task_idINTPrimary key
task_nameVARCHARName of task

Table: Dependencies

Column NameTypeDescription
task_idINTTask that depends on another
depends_onINTTask that must complete first

Database Schema (Inferred)

Tasks

Column NameExample Value
task_id1
task_nameT1

Dependencies

Column NameExample Value
task_id3
depends_on1

Example

Tasks

task_idtask_name
1T1
2T2
3T3
4T4
5T5
6T6

Dependencies

task_iddepends_on
31
32
42
53
64
65

Output

task_idexecution_level
11
21
32
42
53
64

Explanation:

T1, T2 have no deps → level 1. T3 depends on T1(1) and T2(1) → level 2. T4 depends on T2(1) → level 2. T5 depends on T3(2) → level 3. T6 depends on T4(2) and T5(3) → level 4. Use recursive CTE propagating level from roots and take MAX per task.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Tasks

task_idtask_name
1T1
2T2
3T3
4T4
5T5
6T6

Dependencies

task_iddepends_on
31
32
42
53
64
65

Output

task_idexecution_level
11
21
32
42
53
64