Optimize SQL Queries and/or complex workloads like dbt Projects on MotherDuck
I want to optimize SQL queries or a dbt project on MotherDuck. Help me adapt this recipe to my own data and use case, using it as a guide: https://motherduck.com/docs/cookbook/query-optimization
Harness to diagnose and optimize queries and/or complex workloads like dbt Projects with isolated experiments, profiles, correctness checks, and auditable measurements on MotherDuck.
How it works
For one slow read-only query, use lightweight diagnosis with the user's existing token: no new accounts, clones, or campaign harness. Use the full methodology for dbt, write-query, or broader optimization campaigns. Generate profiles/history, then consult DuckDB patterns for observed bottlenecks. No existing profiles or internal tooling required.
The helpers capture SQL profiles and paired timings, not resource provisioning or campaign orchestration. Adapt an isolated runner for dbt jobs.
Results dive
Campaigns log every experiment, run and decision as they go. The log goes to a MotherDuck results database, shared with the organization, and the Optimization results Dive shows it:
- the best configuration found;
- what each experiment changed and what it gained or cost against the original;
- which Duckling sizes were used;
- where pipeline time and spill go.
The Dive follows the MotherDuck light or dark theme.

Run setup once per organization to create the database, share and Dive. Agents then log with
record_results.py. See results/README.md for setup, the logging rules
and more screenshots.
Questions to answer
Discover what the project provides; clarify only missing inputs. Single-query diagnosis needs SQL/parameters, database access, the existing token, and execution conditions; management credentials and compute-slot limits are campaign-only.
- Goal: query, query group, or dbt project.
- Workload: SQL and parameters, or project and exact dbt invocation, selectors, exclusions, variables, and target. Confirm dbt focus: incremental runs, full refreshes, initial builds/backfills, or multiple modes. Never assume full refresh.
- Credentials: secret references with source-data access. Campaigns also need service-account/Duckling management capability; verify permissions and grants.
- Sources: databases/shares; comparisons need stable inputs. Campaigns pin a snapshot.
- Campaign compute envelope: maximum service accounts, per-size limits, allowed query/job Duckling sizes, and starting dbt threads. Size and threads remain tunable.
For campaigns, suggest smaller query-exploration slots and representative job-sized slots; increase within the envelope if memory pressure makes exploration unrepresentative.
Caveats
explain analyzeexecutes SQL. Lightweight diagnosis is read-only; writes and dbt require disposable targets and campaign credentials.- Helpers accept one
SELECT, optionally as CTAS; these do not measure a full dbt job or its actual incremental writes. - Profile for diagnosis; measure timing without profiling. Follow methodology for warm-up, comparable batches, validation, and opt-in repetitions.
--setupreruns per process; prepare persistent experiment inputs separately.
What you'll adjust
| Helper option | Meaning |
|---|---|
--database | Existing database for read-only diagnosis; experiment clone for campaigns. |
--sql / --baseline / --candidate | SQL files, including compiled model SELECTs. |
--mode | explain (default), profiling, or timing. |
--materialize | Include CTAS into a unique disposable main.__mdopt_* table. |
--keep-result / --keep-results | Retain CTAS outputs for validation; persistent databases only; track cleanup. |
--conditions | Adapt conditions.json; required for MotherDuck. |
--inputs-read-at | Verified full-input read timestamp; omit if unknown to trigger warm-up. |
--output | New artifact directory; existing runs are never overwritten. |
--token-env | Experiment token variable; default MOTHERDUCK_EXPERIMENT_TOKEN. |
Run it
Use uv to reuse/recreate the customer's Python, DuckDB, dbt, and adapter
environment; record versions. No recipe dependency pins or original dependency
edits/upgrades. Helpers require Python 3.10+; adapt them for older runtimes.
Commands assume the prepared environment and this recipe's working directory.
For a single-query diagnosis, use direct profiling
with the existing user token. Optional helpers accept --token-env MOTHERDUCK_TOKEN;
MotherDuck helper runs still require --conditions and perform warm-up as configured.
For campaigns, provision the isolated slot/clone, prepare conditions, and expose its token through the environment. Profile the customer's SQL, then measure one pair:
uv run python scripts/profile.py \
--database md:opt_baseline --sql optimization/experiment-001/baseline.sql \
--conditions optimization/conditions.json \
--output optimization/experiment-001/profile
uv run python scripts/benchmark.py \
--database md:opt_baseline \
--baseline optimization/experiment-001/baseline.sql \
--candidate optimization/experiment-001/candidate.sql \
--conditions optimization/conditions.json \
--output optimization/experiment-001/pair
Use --mode profiling for connection profiles; add --materialize to include
table-model writes. Never use it with a read scaling token.
Security
Campaigns separate provisioning, experiment, and observer credentials; lightweight diagnosis reuses the user's token without changing its permissions. Keep secrets out of SQL, artifacts, logs, and diffs. Clone only approved sources through restricted shares; clean only campaign-owned resources. Review SQL/profile artifacts for sensitive names and literals before sharing.
Learn more
- Experiment checkpoint and report.
- Results database, logging rules and Dive.
- Read-scaling benchmark for read-only load tests.