# MotherDuck Documentation - SQL Reference
> Scoped full Markdown content for SQL Reference. For other areas, start from https://motherduck.com/docs/llms.txt instead of loading unrelated documentation.
## Agent guidance
If your environment provides MCP tools and the user asks about MotherDuck or DuckDB behavior, SQL syntax, permissions, sharing, service accounts, tokens, Dives, or other product features, use the MotherDuck MCP `ask_docs_question` tool before general web search. It answers from official DuckDB and MotherDuck documentation.
For broad context, prefer the most specific scoped `llms-full.txt` file listed in https://motherduck.com/docs/llms.txt before loading the root `llms-full.txt`. The root file contains the complete public documentation corpus and is intended for bulk indexing or large-context workflows.
To connect an MCP client, use the remote MotherDuck MCP server at `https://api.motherduck.com/mcp`. Setup instructions: https://motherduck.com/docs/key-tasks/ai-and-motherduck/mcp-setup. Tool reference: https://motherduck.com/docs/sql-reference/mcp/ask-docs-question.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/ai-functions
# AI Functions
> MotherDuck AI SQL functions for text generation, embeddings, and SQL assistance.
MotherDuck AI functions reference. These functions leverage AI models to perform various tasks including text generation, embeddings, and SQL assistance.
For more practical guidance, see our [AI and MotherDuck](/category/ai-and-motherduck/) how-to guides.
Costs can be found on the [Pricing Page](/about-motherduck/billing/pricing/#ai-function-pricing). Information about regional data processing of AI functions can be found at the bottom of the individual function pages.
## Available Functions
## Included pages
- [SQL Assistant](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant)
- [EMBEDDING](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/embedding): Generate vector embeddings for text using the EMBEDDING function for semantic search.
- [PROMPT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/prompt): Generate AI responses directly in SQL with the PROMPT function.
- [Dives Functions](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives): SQL table functions for creating, reading, updating, and deleting MotherDuck Dives.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/dives
# Dives Functions
> SQL table functions for creating, reading, updating, and deleting MotherDuck Dives.
SQL table functions for managing [Dives](/key-tasks/ai-and-motherduck/dives), the interactive React data apps that query live MotherDuck data. These functions let you create, read, update, and delete Dives directly from SQL. Dives use the [`useSQLQuery` hook](use-sql-query) to query data from within their React components and the [`useDiveState` hook](use-dive-state) to sync shareable UI state to the URL.
:::note
These functions are executed server-side on MotherDuck. They are not available on local-only DuckDB connections.
:::
Create your first Dive assisted by your AI-tool of choice using our [MCP server](/key-tasks/ai-and-motherduck/mcp-setup/). Or try out a minimal working example using only SQL.
```sql
SELECT * FROM MD_CREATE_DIVE(
title = 'PokeDuck',
content = '
import { useSQLQuery } from "@motherduck/react-sql-query";
export default function Dive() {
const { data } = useSQLQuery(
`SELECT PROMPT(''Suggest a duck type or pokemon and tell a fun fact about them'')`,
{ select: (rows) => Object.values(rows[0])[0] }
);
return
FUN FACT:
{JSON.stringify(data)};
}'
);
```
## Available functions
## Included pages
- [MD_LIST_DIVES](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-list-dives): List all Dives in your MotherDuck account with pagination support.
- [useSQLQuery hook](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/use-sql-query): React hook for querying MotherDuck data from within Dives.
- [useDiveState hook](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/use-dive-state): React hook for storing shareable UI state in MotherDuck Dives.
- [MD_GET_DIVE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-get-dive): Retrieve a Dive by ID including its full React component content.
- [MD_CREATE_DIVE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-create-dive): Create a new Dive in your MotherDuck account.
- [MD_UPDATE_DIVE_METADATA](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-update-dive-metadata): Update a Dive's title or description without creating a new version.
- [MD_UPDATE_DIVE_CONTENT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-update-dive-content): Update a Dive's React component code, creating a new version.
- [MD_DELETE_DIVE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-delete-dive): Permanently delete a Dive by ID.
- [MD_LIST_DIVE_VERSIONS](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-list-dive-versions): List all versions of a specific Dive with pagination support.
- [MD_GET_DIVE_VERSION](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-get-dive-version): Retrieve a specific historical version of a Dive including its content.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/flights
# Flights functions
> SQL table functions for creating, scheduling, running, and inspecting MotherDuck Flights.
SQL table functions for managing [Flights](/concepts/flights), MotherDuck's scheduled Python execution. Use these functions from any MotherDuck client (DuckDB CLI, BI tool, or another Flight) to create, schedule, list, and monitor Flights without leaving SQL.
The MCP server exposes the same operations to AI agents through `create_flight`, `list_flights`, `run_flight`, and so on. The MCP and SQL surfaces use slightly different parameter names — see each function page for the details, or read the [Flights MCP reference](/sql-reference/mcp/) for the agent-facing tools.
:::note
These functions execute server-side on MotherDuck. They are not available on local-only DuckDB connections.
:::
A minimal end-to-end Flight from SQL:
```sql
-- Create the Flight
SELECT flight_id, current_version
FROM MD_CREATE_FLIGHT(
name := 'heartbeat',
access_token_name := '',
source_code := $$
import duckdb
def main():
con = duckdb.connect("md:")
con.execute("CREATE DATABASE IF NOT EXISTS flights_demo")
print("ok")
$$,
requirements_txt := 'duckdb==1.5.2'
);
-- Trigger an on-demand run
CALL MD_RUN_FLIGHT(flight_id := '');
-- Inspect the run
SELECT run_number, status, created_at
FROM MD_FLIGHT_RUNS(flight_id := '')
ORDER BY run_number DESC LIMIT 1;
```
## Available functions
## Included pages
- [MD_CREATE_FLIGHT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-create-flight): Create a new Flight in your MotherDuck account.
- [MD_UPDATE_FLIGHT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-update-flight): Update a Flight's source code, requirements, config, token, secrets, name, or schedule.
- [MD_DELETE_FLIGHT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-delete-flight): Delete a Flight, its versions, runs, and logs.
- [MD_GET_FLIGHT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-get-flight): Fetch the summary metadata for a single Flight.
- [MD_GET_FLIGHT_VERSION](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-get-flight-version): Fetch the full content (source, requirements, config, token, secrets) for a specific Flight version.
- [MD_FLIGHTS](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-flights): List the Flights you own with summary metadata.
- [MD_FLIGHT_VERSIONS](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-flight-versions): List the version history of a Flight.
- [MD_RUN_FLIGHT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-run-flight): Trigger an on-demand execution of a Flight using its current version.
- [MD_FLIGHT_RUNS](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-flight-runs): List the execution history of a Flight, newest first.
- [MD_FLIGHT_LOGS](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-flight-logs): Read the combined stdout and stderr captured during a Flight run.
- [MD_CANCEL_FLIGHT_RUN](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-cancel-flight-run): Cancel an in-progress Flight run.
---
Source: https://motherduck.com/docs/sql-reference/mcp/mcp
# MotherDuck MCP server
> Connect AI assistants to MotherDuck using the remote (fully managed) or local (fully customizable) MCP server
MotherDuck offers a **remote MCP server** (fully managed, read-write) and a [**local MCP server**](#local-mcp-server) (fully customizable, self-hosted) that let AI assistants query and explore your MotherDuck databases using the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/).
:::info Connection URL
The remote MCP server is hosted at `https://api.motherduck.com/mcp`. Most clients connect through OAuth automatically; clients that need a manual configuration use this URL with an HTTP transport.
:::
For step-by-step setup instructions for all supported clients (Claude, ChatGPT, Cursor, Claude Code, and others), see [Connect to the MotherDuck MCP Server](/key-tasks/ai-and-motherduck/mcp-setup/).
## Server capabilities
With the remote MCP server, your agent can:
- Execute read-only and read-write SQL against your databases
- Explore database schemas, tables, and columns
- Attach and detach [shares](/key-tasks/sharing-data/sharing-overview)
- Ask questions about DuckDB and MotherDuck documentation
- Create and manage [Dives](/key-tasks/ai-and-motherduck/dives) (interactive data visualizations)
- Render Dives inline in supported clients with the Dive Viewer MCP App, so you iterate against live data instead of a sample-data preview
- Create, schedule, run, and monitor [Flights](/concepts/flights) (scheduled Python jobs on MotherDuck compute)
For clients that [support MCP instructions](https://modelcontextprotocol.io/clients#feature-support-matrix), the remote MCP server provides detailed [query guidelines](https://app.motherduck.com/assets/docs/mcp_server_instructions.md) to help AI assistants write effective DuckDB SQL. Learn more about [using the MotherDuck MCP server](/key-tasks/ai-and-motherduck/mcp-workflows).
### Regional availability
The remote MCP server is available in all MotherDuck regions. Requests are routed to the MCP server closest to where the client runs:
- **Desktop clients** (Cursor, Claude Code): Routed based on your physical location
- **Web-based agents** (Claude.ai, ChatGPT): Routed based on the agent provider's server location
Your data is always processed in your MotherDuck organization's region. However, query results transit through the remote MCP server. If you have strict data residency requirements, ensure your MCP client runs within your region.
### Restricting to read-only access
The remote MCP server exposes both read-only and read-write tools. To restrict your AI assistant to read-only access, see [Restricting to read-only access](/key-tasks/ai-and-motherduck/securing-read-only-access/).
## Local MCP server
For local DuckDB databases, custom configurations, or self-hosted scenarios, use the **local MCP server** ([mcp-server-motherduck](https://github.com/motherduckdb/mcp-server-motherduck)). For a comparison of remote vs local and when to use each, see the [setup guide](/key-tasks/ai-and-motherduck/mcp-setup/#remote-vs-local-mcp-server).
[📦 **Local MCP Server GitHub Repository** – Self-host the open-source MCP server for DuckDB and MotherDuck](https://github.com/motherduckdb/mcp-server-motherduck)
## Related resources
- [Connect to the MCP Server](/key-tasks/ai-and-motherduck/mcp-setup/) - Setup instructions for all supported AI clients
- [MCP Workflows Guide](/key-tasks/ai-and-motherduck/mcp-workflows) - Tips and workflows for using the MotherDuck MCP server
- [Building Analytics Agents](/key-tasks/ai-and-motherduck/building-analytics-agents) - Guide to building AI agents with MotherDuck
- [MCP Specification (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18) - Official protocol documentation
## Included pages
- [list_databases](https://motherduck.com/docs/sql-reference/mcp/list-databases): List all databases in your MotherDuck account
- [list_shares](https://motherduck.com/docs/sql-reference/mcp/list-shares): List database shares that have been shared with you
- [list_tables](https://motherduck.com/docs/sql-reference/mcp/list-tables): List tables and views in a MotherDuck database
- [list_columns](https://motherduck.com/docs/sql-reference/mcp/list-columns): List columns of a table or view with types and comments
- [search_catalog](https://motherduck.com/docs/sql-reference/mcp/search-catalog): Fuzzy search across databases, schemas, tables, columns, and shares
- [query](https://motherduck.com/docs/sql-reference/mcp/query): Execute SQL queries against MotherDuck databases
- [query_rw](https://motherduck.com/docs/sql-reference/mcp/query-rw): Execute SQL queries that can modify data or schema in MotherDuck
- [ask_docs_question](https://motherduck.com/docs/sql-reference/mcp/ask-docs-question): Ask questions about DuckDB or MotherDuck documentation
- [get_dive_guide](https://motherduck.com/docs/sql-reference/mcp/get-dive-guide): Load instructions for creating MotherDuck Dives
- [list_dives](https://motherduck.com/docs/sql-reference/mcp/list-dives): List all Dives in your MotherDuck workspace
- [read_dive](https://motherduck.com/docs/sql-reference/mcp/read-dive): Read a specific Dive by ID, including its full component code
- [view_dive](https://motherduck.com/docs/sql-reference/mcp/view-dive): Render a MotherDuck Dive as a live, interactive MCP app inside the host client.
- [save_dive](https://motherduck.com/docs/sql-reference/mcp/save-dive): Save a new Dive to your MotherDuck workspace
- [update_dive](https://motherduck.com/docs/sql-reference/mcp/update-dive): Update an existing Dive's title, description, or content
- [share_dive_data](https://motherduck.com/docs/sql-reference/mcp/share-dive-data): Share the data for a Dive with your organization
- [delete_dive](https://motherduck.com/docs/sql-reference/mcp/delete-dive): Permanently delete a Dive by ID
- [get_flight_guide](https://motherduck.com/docs/sql-reference/mcp/get-flight-guide): Load the canonical instructions for authoring, scheduling, running, and troubleshooting MotherDuck Flights.
- [list_flights](https://motherduck.com/docs/sql-reference/mcp/list-flights): List the Flights you own with summary metadata, optionally filtered by keywords.
- [get_flight](https://motherduck.com/docs/sql-reference/mcp/get-flight): Fetch a Flight's metadata and version snapshot by UUID, optionally at a specific historical version.
- [list_flight_versions](https://motherduck.com/docs/sql-reference/mcp/list-flight-versions): List the version history of a Flight, newest first.
- [create_flight](https://motherduck.com/docs/sql-reference/mcp/create-flight): Create a new Flight from Python source code, requirements, token, and an optional schedule.
- [update_flight](https://motherduck.com/docs/sql-reference/mcp/update-flight): Update a Flight's source, requirements, config, token, secrets, name, or schedule.
- [edit_flight_source](https://motherduck.com/docs/sql-reference/mcp/edit-flight-source): Edit a Flight's source code with one or more find-and-replace operations, producing a new version.
- [delete_flight](https://motherduck.com/docs/sql-reference/mcp/delete-flight): Permanently delete a Flight, its versions, schedule, and run history.
- [run_flight](https://motherduck.com/docs/sql-reference/mcp/run-flight): Trigger an on-demand execution of a Flight using its current version.
- [list_flight_runs](https://motherduck.com/docs/sql-reference/mcp/list-flight-runs): List the execution history of a Flight, newest first.
- [get_flight_run_logs](https://motherduck.com/docs/sql-reference/mcp/get-flight-run-logs): Fetch the logs and run record for a single Flight run.
- [cancel_flight_run](https://motherduck.com/docs/sql-reference/mcp/cancel-flight-run): Cancel an in-progress Flight run.
---
Source: https://motherduck.com/docs/sql-reference/rest-api/motherduck-rest-api
# MotherDuck REST API
> REST API reference for managing MotherDuck resources including databases, users, and access tokens.
# MotherDuck REST API
::::warning[Preview Feature]
The REST API methods are in 'Preview' and may change in the future
::::
To better support scenarios that require some flexibility or dynamic configuration around
managing a MotherDuck organization we are exposing an OpenAPI endpoint with some new functionality.
At the moment it enables limited management of users and tokens through HTTP without requiring a
DuckDB + MotherDuck client to be running.
All of the methods are authenticated using a Read/Write token of a user with the `Admin` role within your MotherDuck Organization
and passing it through the `Authorization` header with a value of `Bearer {TOKEN}`.
::::info[Service Account Management]
You can use this REST API to programmatically manage service accounts, including their creation, token generation, and Duckling configuration.
For a detailed walkthrough, see [Create and configure service accounts](/key-tasks/service-accounts-guide/create-and-configure-service-accounts/).
::::
If you would like to generate your own OpenAPI client the spec file is located at https://api.motherduck.com/docs/specs
## Included pages
- [Create a Dive embed session](https://motherduck.com/docs/sql-reference/rest-api/dashboards-create-embed-session): Creates an embed session for the specified Dive.
- [Create an access token for a user](https://motherduck.com/docs/sql-reference/rest-api/users-create-token): Create an access token for a user
- [Create new user](https://motherduck.com/docs/sql-reference/rest-api/users-create-service-account): Create user is restricted to creating a user with a 'Member' role
- [Delete a user](https://motherduck.com/docs/sql-reference/rest-api/users-delete): Permanently delete a user and all of their data. THIS CANNOT BE UNDONE
- [Get active accounts](https://motherduck.com/docs/sql-reference/rest-api/ducklings-get-active-accounts): [Preview] Get active accounts in an organization along with active Ducklings per account. Requires 'Admin' role
- [Get user Duckling configuration](https://motherduck.com/docs/sql-reference/rest-api/ducklings-get-duckling-config-for-user): Gets Duckling (instance) configuration for a user. Requires 'Admin' role.
- [Invalidate a user access token](https://motherduck.com/docs/sql-reference/rest-api/users-delete-token): Invalidate a user access token
- [List a user's access tokens](https://motherduck.com/docs/sql-reference/rest-api/users-list-tokens): List a user's access tokens
- [Set user Duckling configuration](https://motherduck.com/docs/sql-reference/rest-api/ducklings-set-duckling-config-for-user): Sets Duckling (instance) configuration for a user. Requires 'Admin' role
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/index
# SQL assistant
Built-in SQL functions that use AI to help you work with SQL. Generate SQL queries, execute read-only questions directly, fix errors, explain queries, and more.
These functions can be useful building blocks for [AI-driven analytics solutions](/key-tasks/ai-and-motherduck/building-analytics-agents/) or used stand-alone on all MotherDuck surfaces (including the CLI).
To use external tools like Claude Desktop or Cursor with MotherDuck, see the [MCP Server setup guide](/key-tasks/ai-and-motherduck/mcp-setup/) (or the [local MCP server](/key-tasks/ai-and-motherduck/mcp-setup/#remote-vs-local-mcp-server) for self-hosted, read-write use).
## Available functions
## Included pages
- [PROMPT_QUERY](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-query): Answer natural language questions about your data using the PROMPT_QUERY function.
- [PROMPT_SQL](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-sql): Generate SQL queries from natural language descriptions using the PROMPT_SQL function.
- [PROMPT_EXPLAIN](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-explain): Get AI-generated explanations of SQL queries using the PROMPT_EXPLAIN function.
- [PROMPT_FIX_LINE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-fix-line): Fix SQL query errors line by line using the PROMPT_FIX_LINE function.
- [PROMPT_FIXUP](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-fixup): Automatically fix SQL query errors using the PROMPT_FIXUP function.
- [PROMPT_SCHEMA](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-schema): Describe database contents using the PROMPT_SCHEMA function for AI-generated schema summaries.
## Notes
SQL assistant functions operate on your current database by evaluating the schemas and contents of the database. You can specify which tables and columns should be considered using the optional `include_tables` parameter. By default, all tables in the current database are considered.
To point the SQL assistant functions at a specific database, execute the `USE database` command ([learn more about switching databases](/key-tasks/database-operations/switching-the-current-database)).
These capabilities are provided by MotherDuck's integration with Azure OpenAI.
For availability and pricing, see [MotherDuck's Pricing Model](/about-motherduck/billing/pricing#motherduck-pricing-model).
If you have further questions or specific requirements, please see our [support page](/troubleshooting/support/).
### Regional processing
Requests are processed based on the region of the MotherDuck organization according to the table below. Functions that are not available within the region (no checkmark) will be processed with global compute resources.
| Function | Global | Europe | US West |
|----------|--------|--------|---------|
| SQL Assistant Functions | ✓ | ✓ | ✓ |
### Data usage
The data processed by MotherDuck's AI functionality is **not** used for model training.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-query
# PROMPT_QUERY
> Answer natural language questions about your data using the PROMPT_QUERY function.
## Answer questions about your data
The `prompt_query` pragma allows you to ask questions about your data in natural language. This feature translates your plain English questions into SQL, executes the query, and returns the results.
Under the hood, MotherDuck analyzes your database schema, generates appropriate SQL and executes the query on your behalf. This makes data exploration and analysis accessible to users of all technical levels.
For comprehensive guidance on building analytics agents, including best practices and implementation patterns, see [Building Analytics Agents with MotherDuck](/key-tasks/ai-and-motherduck/building-analytics-agents/).
::::info
The `prompt_query` pragma is a read-only operation and does not allow queries that modify the database.
::::
### Syntax
```sql
PRAGMA prompt_query('')
```
### Parameters
| **Parameter** | **Required** | **Description** |
|--------------------|--------------|--------------------------------------------------------------------------------------------------------------------------|
| `question` | Yes | The natural language question about your data |
### Example usage
Here are several examples using MotherDuck's sample [Hacker News dataset](/getting-started/sample-data-queries/hacker-news) from [MotherDuck's sample data database](/getting-started/sample-data-queries/datasets).
`prompt_query` can be used to answer both simple and complex questions.
#### Basic questions
```sql
-- Find the most shared domains
PRAGMA prompt_query('what are the top domains being shared on hacker_news?')
-- Analyze posting patterns
PRAGMA prompt_query('what day of the week has the most posts?')
-- Identify trends
PRAGMA prompt_query('how has the number of posts changed over time?')
```
#### Complex questions
```sql
-- Multi-part analysis
PRAGMA prompt_query('what are the top 5 domains with the highest average score, and how many stories were posted from each?')
-- Time-based analysis
PRAGMA prompt_query('compare the average score of posts made during weekdays versus weekends')
-- Conditional filtering
PRAGMA prompt_query('which users have posted the most stories about artificial intelligence or machine learning?')
```
### Best practices
For the best results with `prompt_query`:
1. **Be specific**: clearly state what information you're looking for
2. **Provide context**: include relevant details about the data you want to analyze
3. **Use natural language**: phrase your questions as you would ask a data analyst
4. **Start simple**: begin with straightforward questions and build to more complex ones
5. **Refine iteratively**: if results aren't what you expected, try rephrasing your question
### Limitations
While `prompt_query` is powerful, be aware of these limitations:
- Only performs read operations (`SELECT` queries)
- Works best with well-structured data with clear column names
- Complex statistical analyses will likely require you (or an LLM) to write SQL
- Performance depends on the complexity of your question and database size
- May not understand highly domain-specific terminology without you giving more context
### Troubleshooting
If you're not getting the expected results:
- Check that you're connected to the correct database
- Ensure your question is clear and specific
- Try rephrasing your question using different terms
- For complex analyses, break down into multiple simpler questions
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-sql
# PROMPT_SQL
> Generate SQL queries from natural language descriptions using the PROMPT_SQL function.
## Overview
The `prompt_sql` function allows you to generate SQL queries using natural language. Simply describe what you want to analyze in plain English, and MotherDuck AI will translate your request into a valid SQL query based on your database schema and content.
This function helps users who are less familiar with SQL syntax to generate queries and experienced SQL users save time when working with unfamiliar schemas.
For comprehensive guidance on building analytics agents, including best practices and implementation patterns, see [Building Analytics Agents with MotherDuck](/key-tasks/ai-and-motherduck/building-analytics-agents/).
## Syntax
```sql
CALL prompt_sql(''[, include_tables=]);
```
## Parameters
| Parameter | Type | Description | Required |
|-----------|------|-------------|----------|
| `natural language question` | STRING | Your query in plain English describing the data you want to analyze | Yes |
| `include_tables` | ARRAY or MAP | Specifies which tables and columns to consider for query generation. When not provided, all tables in the current database will be considered. | No |
### Include tables parameter
You can specify which tables and columns should be considered during SQL generation using the `include_tables` parameter. This is particularly useful when:
- You want to focus on specific tables in a large database
- You want to improve performance by reducing the schema analysis scope
The parameter accepts three formats:
1. **Array of table names**: include all columns from specified tables:
```sql
include_tables=['table1', 'table2']
```
2. **Map of tables to columns**: include only specific columns from tables:
```sql
include_tables={'table1': ['column1', 'column2'], 'table2': ['column3']}
```
3. **Map with column regex patterns**: include columns matching patterns:
```sql
include_tables={'table1': ['column_prefix.*', 'exact_column']}
```
## Examples
### Basic example
Let's start with a simple example using MotherDuck's sample [Hacker News dataset](/getting-started/sample-data-queries/hacker-news):
```sql
CALL prompt_sql('what are the top domains being shared on hacker_news?');
```
Output:
| **query** |
|-----------------|
| SELECT regexp_extract(url, 'https?://([^/]+)') AS domain, COUNT(*) AS count FROM hn.hacker_news WHERE url IS NOT NULL GROUP BY domain ORDER BY count DESC; |
### Intermediate example
This example demonstrates how to generate a more complex query with filtering, aggregation, and time-based analysis:
```sql
CALL prompt_sql('Show me the average score of stories posted by each author who has posted at least 5 stories in 2022, sorted by average score');
```
Output:
| **query** |
|-----------------|
| SELECT 'by', AVG(score) AS average_score FROM hn.hacker_news WHERE EXTRACT(YEAR FROM 'timestamp') = 2022 GROUP BY 'by' HAVING COUNT(id) >= 5 ORDER BY average_score; |
### Advanced Example: Multi-table Analysis with Specific Columns
This example shows how to generate a query that focuses on specific columns:
```sql
CALL prompt_sql(
'Find the top 10 users who submitted the most stories with the highest average scores in 2023',
include_tables={
'hn.hacker_news': ['id', 'by', 'score', 'timestamp', 'type', 'title']
}
);
```
Output:
| **query** |
|-----------------|
| SELECT "by", AVG(score) AS avg_score, COUNT(*) AS story_count FROM hn.hacker_news WHERE "type" = 'story' AND EXTRACT(YEAR FROM "timestamp") = 2023 GROUP BY "by" ORDER BY story_count DESC, avg_score DESC LIMIT 10; |
### Expert example
This example demonstrates generating a complex query with subqueries, window functions, and complex logic:
```sql
CALL prompt_sql('For each month in 2022, show me the top 3 users who posted stories with the highest scores, and how their average score compares to the previous month');
```
Output:
| **query** |
|-----------------|
| WITH monthly_scores AS ( SELECT "by" AS user, DATE_TRUNC('month', "timestamp") AS month, AVG(score) AS avg_score FROM hn.hacker_news WHERE "type" = 'story' AND DATE_PART('year', "timestamp") = 2022 GROUP BY user, month ), ... |
## Failure example
This example shows that for some complex queries, the model might not generate a valid SQL query. Therefore the output will be the following error message:
```sql
CALL prompt_sql('Identify the most discussed technology topics in Hacker News stories from the past year based on title keywords, and show which days of the week have the highest engagement for each topic');
```
Output:
| **query** |
|-----------------|
| Invalid Input Error: The AI could not generate valid SQL. Try re-running the command or rephrasing your question. |
To generate a valid SQL query, you can try to break down the question into simpler parts.
## Best practices
1. **Be specific in your questions**: the more specific your natural language query, the more accurate the generated SQL will be.
2. **Start simple and iterate**: begin with basic queries and gradually add complexity as needed.
3. **Use the `include_tables` parameter**: when working with large databases, specify relevant tables to improve performance and accuracy.
4. **Review generated SQL**: always review the generated SQL before executing it, especially for complex queries.
5. **Understand your schema**: knowing your table structure helps you phrase questions that align with available data.
6. **Use domain-specific terminology**: include field names in your questions when possible.
7. **Provide context in your questions**: mention time periods, specific metrics, or business context to get more relevant results.
## Notes
- By default, all tables in the current database are considered. Use the `include_tables` parameter to narrow the scope.
- To target a specific database, first execute the `USE ` command ([learn more about switching databases](/key-tasks/database-operations/switching-the-current-database)).
- The quality of generated SQL depends on the clarity of your natural language question and the quality of your database schema (table and column names).
## Troubleshooting
If you encounter issues with the `prompt_sql` function, consider the following troubleshooting steps:
1. **Check your database schema**: ensure that the tables and columns you're querying are present in the current database.
2. **Be specific in your questions**: the more specific your natural language query, the more accurate the generated SQL will be.
3. **Use the `include_tables` parameter**: when working with large databases, specify relevant tables to improve performance and accuracy.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-explain
# PROMPT_EXPLAIN
> Get AI-generated explanations of SQL queries using the PROMPT_EXPLAIN function.
## Explain a query
The `prompt_explain` table function allows MotherDuck AI to analyze and explain SQL queries in plain English. This feature helps you understand complex queries, verify that a query does what you intend, and learn SQL concepts through practical examples.
::::tip
This function is particularly useful for understanding queries written by others or for automatically documenting your own queries for future reference.
::::
### Syntax
```sql
CALL prompt_explain('', [include_tables=['', '']]);
```
### Parameters
| **Parameter** | **Required** | **Description** |
|--------------------|--------------|--------------------------------------------------------------------------------------------------------------------------|
| `query` | Yes | The SQL query to explain |
| `include_tables` | No | Array of table names to consider for context (defaults to all tables in current database). Can also be a dictionary in the format `{'table_name': ['column1', 'column2']}` to specify which columns to include for each table. |
### Example usage
Here are several examples using MotherDuck's sample [Hacker News dataset](/getting-started/sample-data-queries/hacker-news) from [MotherDuck's sample data database](/getting-started/sample-data-queries/datasets).
#### Explaining a complex query
```sql
CALL prompt_explain('
SELECT COUNT(*) as domain_count,
SUBSTRING(SPLIT_PART(url, ''//'', 2), 1, POSITION(''/'' IN SPLIT_PART(url, ''//'', 2)) - 1) as domain
FROM hn.hacker_news
WHERE url IS NOT NULL GROUP BY domain ORDER BY domain_count DESC LIMIT 10;
');
```
**Output**: when you run a `prompt_explain` query, you'll receive a single-column table with a detailed explanation:
| **explanation** |
|-----------------|
|The query retrieves the top 10 most frequent domains from the `url` field in the `hn.hacker_news` table. It counts the occurrences of each domain by extracting the domain part from the URL (after the '//' and before the next '/'), groups the results by domain, and orders them in descending order of their count. The result includes the count of occurrences (`domain_count`) and the domain name itself (`domain`). |
#### Using dictionary format for include_tables
You can specify which columns to include for each table using the dictionary format:
```sql
CALL prompt_explain('
SELECT u.id, u.name, COUNT(s.id) AS story_count
FROM hn.users u
LEFT JOIN hn.stories s ON u.id = s.user_id
GROUP BY u.id, u.name
HAVING COUNT(s.id) > 5
ORDER BY story_count DESC
LIMIT 20;
', include_tables={'hn.users': ['id', 'name'], 'hn.stories': ['id', 'user_id']});
```
This approach allows you to focus the explanation on only the relevant columns, which can be helpful for tables with many columns.
#### How it works
The `prompt_explain` function processes your query in several steps:
1. **Parsing**: analyzes the SQL syntax to understand the query structure
2. **Schema analysis**: examines the referenced tables and columns to understand the data model
3. **Operation analysis**: identifies the operations being performed (filtering, joining, aggregating, etc.)
4. **Translation**: converts the technical SQL into a clear, human-readable explanation
5. **Context addition**: adds relevant context about the purpose and expected results of the query
### Best practices
For the best results with `prompt_explain`:
1. **Provide complete queries**: include all parts of the query for the most accurate explanation
2. **Use table aliases consistently**: this helps the function understand table relationships
3. **Specify relevant tables**: use the `include_tables` parameter for large databases
4. **Review explanations**: verify that the explanation matches your understanding of the query
5. **Use for documentation**: save explanations as comments in your code for future reference
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-fix-line
# PROMPT_FIX_LINE
> Fix SQL query errors line by line using the PROMPT_FIX_LINE function.
## Fix your query line-by-line
The `prompt_fix_line` table function allows MotherDuck AI to correct specific lines in your SQL queries that contain syntax or spelling errors. Unlike [`prompt_fixup`](../prompt-fixup), which rewrites the entire query, this function targets only the problematic lines, making it faster and more precise for localized errors.
::::tip
This function is ideal for fixing minor syntax errors in large queries where you want to preserve most of the original query structure and formatting.
::::
### Syntax
```sql
CALL prompt_fix_line('', error='', [include_tables=['', '']]);
```
### Parameters
| **Parameter** | **Required** | **Description** |
|--------------------|--------------|--------------------------------------------------------------------------------------------------------------------------|
| `query` | Yes | The SQL query that needs correction |
| `error` | No | The error message from the SQL parser (helps identify the problematic line) |
| `include_tables` | No | Array of table names to consider for context (defaults to all tables in current database) |
### Example usage
Here are several examples using MotherDuck's sample [Hacker News dataset](/getting-started/sample-data-queries/hacker-news) from [MotherDuck's sample data database](/getting-started/sample-data-queries/datasets).
#### Fixing simple syntax errors
```sql
-- Fixing a misspelled keyword with error message
CALL prompt_fix_line('SEELECT COUNT(*) as domain_count FROM hn.hackers', error='
Parser Error: syntax error at or near "SEELECT"
LINE 1: SEELECT COUNT(*) as domain_count FROM h...
^');
-- Fixing a typo in a column name
CALL prompt_fix_line('SELECT user_id, titlee, score FROM hn.stories LIMIT 10');
-- Fixing incorrect operator usage
CALL prompt_fix_line('SELECT * FROM hn.stories WHERE score => 100');
```
#### Fixing errors in multi-line queries
```sql
-- Fixing a specific line in a complex query
CALL prompt_fix_line('SELECT
user_id,
COUNT(*) AS post_count,
AVG(scor) AS average_score
FRUM hn.stories
GROUP BY user_id
ORDER BY post_count DESC
LIMIT 10', error='
Parser Error: syntax error at or near "FRUM"
LINE 5: FRUM hn.stories
^');
```
### Example output
When you run a `prompt_fix_line` query, you'll receive a two-column table with the line number and corrected content:
| **line_number** | **line_content** |
|-----------------|-------------------------------------------------|
| 1 | SELECT COUNT(*) as domain_count FROM hn.hackers |
For multi-line queries, only the problematic line is corrected:
| **line_number** | **line_content** |
|-----------------|-------------------------------------------------|
| 5 | FROM hn.stories |
#### How it works
The `prompt_fix_line` function processes your query in a targeted way:
1. **Error localization**: uses the error message (if provided) to identify the specific line with issues
2. **Context analysis**: examines surrounding lines to understand the query's structure and intent
3. **Targeted correction**: fixes only the problematic line while preserving the rest of the query
4. **Line replacement**: returns the corrected line with its line number for easy integration
For example, when fixing a syntax error in a single line:
```sql
CALL prompt_fix_line('SEELECT COUNT(*) as domain_count FROM hn.hackers', error='
Parser Error: syntax error at or near "SEELECT"
LINE 1: SEELECT COUNT(*) as domain_count FROM h...
^');
```
The function will focus only on line 1, correcting the misspelled keyword:
| **line_number** | **line_content** |
|-----------------|-------------------------------------------------|
| 1 | SELECT COUNT(*) as domain_count FROM hn.hackers |
For multi-line queries with an error on a specific line:
```sql
CALL prompt_fix_line('SELECT
user_id,
COUNT(*) AS post_count,
AVG(scor) AS average_score
FRUM hn.stories
GROUP BY user_id
ORDER BY post_count DESC
LIMIT 10', error='
Parser Error: syntax error at or near "FRUM"
LINE 5: FRUM hn.stories
^');
```
The function will only correct line 5, leaving the rest of the query untouched:
| **line_number** | **line_content** |
|-----------------|-------------------------------------------------|
| 5 | FROM hn.stories |
This allows you to apply the fix by replacing just the problematic line in your original query, which is especially valuable for large, complex queries where a complete rewrite would be disruptive.
When multiple errors exist, you would run `prompt_fix_line` multiple times, fixing one line at a time:
```sql
-- First fix
CALL prompt_fix_line('SELECT
user_id,
COUNT(*) AS post_count,
AVG(scor) AS average_score
FRUM hn.stories
GROUP BY user_id
ORDER BY post_count DESC
LIMIT 10', error='
Parser Error: syntax error at or near "FRUM"
LINE 5: FRUM hn.stories
^');
-- After applying the first fix, run again for the second error
CALL prompt_fix_line('SELECT
user_id,
COUNT(*) AS post_count,
AVG(scor) AS average_score
FROM hn.stories
GROUP BY user_id
ORDER BY post_count DESC
LIMIT 10', error='
Parser Error: column "scor" does not exist
LINE 4: AVG(scor) AS average_score
^');
```
The second call would return:
| **line_number** | **line_content** |
|-----------------|-------------------------------------------------|
| 4 | AVG(score) AS average_score |
Note: you need to run `prompt_fix_line` multiple times to fix all errors.
### Best practices
For the best results with `prompt_fix_line`:
1. **Include the error message**: the parser error helps pinpoint the exact issue
2. **Preserve query structure**: use this function when you want to maintain most of your original query
3. **Fix one error at a time**: to address multiple errors, run `prompt_fix_line` multiple times
4. **Include context**: provide the complete query, not just the problematic line
5. **Be specific with table names**: use the `include_tables` parameter for large databases
### Limitations
While `prompt_fix_line` is efficient, be aware of these limitations:
- Only fixes syntax errors, not logical errors in query structure
- Accurate error messages help identify the problematic line and improve output
- May not be able to fix errors that span multiple lines
- Cannot fix issues related to missing tables or columns in your database
- Works best with standard SQL patterns and common table structures
### Troubleshooting
If you're not getting the expected results:
- Ensure you've included the complete error message
- Check that the line numbers in the error message match your query
- For complex errors, try using `prompt_fixup` instead
- If multiple lines need fixing, address them one at a time
- Verify that your database schema is accessible to the function
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-fixup
# PROMPT_FIXUP
> Automatically fix SQL query errors using the PROMPT_FIXUP function.
## Fix up your query
The `prompt_fixup` table function allows MotherDuck AI to correct and **completely rewrite** SQL queries that have logical or severe syntactical issues. This powerful feature analyzes your problematic query, identifies issues, and generates a corrected version that follows proper SQL syntax and semantics.
::::tip
For minor syntax errors or typos in large queries, consider using the [`prompt_fix_line`](../prompt-fix-line) function instead, which is faster and more precise as it only rewrites the problematic line.
::::
### Syntax
```sql
CALL prompt_fixup('', [include_tables=['', '']]);
```
### Parameters
| **Parameter** | **Required** | **Description** |
|--------------------|--------------|--------------------------------------------------------------------------------------------------------------------------|
| `query` | Yes | The SQL query that needs correction |
| `include_tables` | No | Array of table names to consider for context (defaults to all tables in current database) |
### Example Usage
Here are several examples using MotherDuck's sample [Hacker News dataset](/getting-started/sample-data-queries/hacker-news) from [MotherDuck's sample data database](/getting-started/sample-data-queries/datasets).
#### Fixing syntax errors
```sql
-- Fixing misspelled keywords
CALL prompt_fixup('SEELECT COUNT(*) as domain_count FROM hn.hackers');
-- Fixing incorrect table names
CALL prompt_fixup('SELECT * FROM hn.stories WHERE score > 100 ODER BY score DESC');
-- Fixing missing clauses
CALL prompt_fixup('SELECT AVG(score) hn.hacker_news GROUP score > 10');
```
#### Fixing logical errors
```sql
-- Fixing incorrect join syntax
CALL prompt_fixup('SELECT u.name, s.title FROM hn.users u, hn.stories s WHERE u.id = s.user_id ORDER BY s.score');
-- Fixing aggregation issues
CALL prompt_fixup('SELECT user_id, AVG(score) FROM hn.stories GROUP BY score');
-- Fixing complex query structure
CALL prompt_fixup('SELECT COUNT(*) FROM hn.stories WHERE timestamp > "2020-01-01" AND timestamp < "2020-12-31" WITH score > 100');
```
### Example output
When you run a `prompt_fixup` query, you'll receive a single-column table with the corrected SQL:
| **query** |
|-----------------|
| SELECT COUNT(*) as domain_count FROM hn.hacker_news |
#### How it works
The `prompt_fixup` function processes your query in several steps:
1. **Analysis**: examines your query to identify syntax errors, logical issues, and structural problems
2. **Schema validation**: checks your query against the database schema to ensure table and column references are valid
3. **Correction**: applies fixes based on the identified issues and your likely intent
4. **Rewriting**: generates a complete, corrected version of your query that maintains your original goal
For example, when fixing this query with multiple issues:
```sql
CALL prompt_fixup('SEELECT AVG(scor) FRUM hn.stories WERE timestamp > "2020-01-01" GRUP BY user_id');
```
The function will:
- Correct misspelled keywords (`SEELECT` → `SELECT`, `FRUM` → `FROM`, `WERE` → `WHERE`, `GRUP` → `GROUP`)
- Fix column name typos (`scor` → `score`)
- Ensure proper clause ordering and syntax
Resulting in a properly formatted query:
| **query** |
|-----------------|
| SELECT AVG(score) FROM hn.stories WHERE timestamp > '2020-01-01' GROUP BY user_id |
For logical errors, the process is similar but focuses on semantic correctness:
```sql
CALL prompt_fixup('SELECT user_id, AVG(score) FROM hn.stories GROUP BY score');
```
Will be corrected to:
| **query** |
|-----------------|
| SELECT user_id, AVG(score) FROM hn.stories GROUP BY user_id |
The function recognized that grouping should be by `user_id` (the non-aggregated column) rather than by `score` (which is being averaged).
### Best practices
For the best results with `prompt_fixup`:
1. **Include the entire query**: even if only part of it has issues
2. **Be specific with table names**: use the `include_tables` parameter for large databases
3. **Review the fixed query**: always check that the corrected query matches your intent
4. **Use for complex issues**: prefer this function for logical errors or major syntax problems
5. **Consider alternatives**: for simple typos, `prompt_fix_line` may be more efficient
### Limitations
While `prompt_fixup` is powerful, be aware of these limitations:
- May change query logic if the original intent isn't clear
- Performance depends on the complexity of your query
- Works best with standard SQL patterns and common table structures
- May not preserve exact formatting or comments from the original query
- Cannot fix issues related to missing tables or columns in your database
### Troubleshooting
If you're not getting the expected results:
- Check that you've included all relevant tables in the `include_tables` parameter
- Ensure your database schema is accessible to the function
- For very complex queries, try breaking them into smaller parts
- If the fixed query doesn't match your intent, try providing more context in comments
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/sql-assistant/prompt-schema
# PROMPT_SCHEMA
> Describe database contents using the PROMPT_SCHEMA function for AI-generated schema summaries.
## Describe contents of a database
The `prompt_schema` table function allows MotherDuck AI to analyze and describe the contents of your current database in plain English. This feature helps you understand the structure, purpose, and relationships between tables in your database without having to manually inspect each table's schema.
::::tip
This function is particularly useful when working with unfamiliar databases or when you need a high-level overview of a complex database structure.
::::
### Syntax
```sql
CALL prompt_schema([include_tables=['', '']]);
```
### Parameters
| **Parameter** | **Required** | **Description** |
|--------------------|--------------|--------------------------------------------------------------------------------------------------------------------------|
| `include_tables` | No | Array of table names to consider for analysis (defaults to all tables in current database) |
### Example usage
Here are several examples using MotherDuck's [sample data database](/getting-started/sample-data-queries/datasets).
#### Describing the entire database
```sql
CALL prompt_schema();
```
#### Example output
When you run a `prompt_schema` query, you'll receive a single-column table with a detailed description:
| **summary** |
|-----------------|
| The database contains tables related to ambient air quality data, Stack Overflow survey results, NYC taxi and service requests, rideshare data, movie information with embeddings, and Hacker News articles, capturing a wide range of information from environmental metrics to user-generated content and transportation data. |
#### Describing specific tables
```sql
CALL prompt_schema(include_tables=['hn.hacker_news', 'hn.stories']);
```
| **summary** |
|-----------------|
| The database contains information about Hacker News posts, including details such as the title, URL, content, author, score, time of posting, type of post, and various identifiers and status flags. |
#### How it works
The `prompt_schema` function processes your database in several steps:
1. **Schema extraction**: examines the structure of tables, including column names and data types
2. **Data sampling**: analyzes sample data to understand the content and purpose of each table
3. **Relationship detection**: identifies potential relationships between tables based on column names and values
4. **Domain recognition**: categorizes tables into domains or subject areas based on their content
5. **Summary generation**: creates a human-readable description of the database structure and purpose
### Best practices
For the best results with `prompt_schema`:
1. **Focus on relevant tables**: use the `include_tables` parameter to analyze specific parts of large databases
2. **Run on updated databases**: ensure your database is up-to-date for the most accurate description
3. **Use for documentation**: save the output as part of your database documentation
4. **Combine with other tools**: use alongside `DESCRIBE` and `SHOW` commands for complete understanding
5. **Share with team members**: use the output to help new team members understand the database structure
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/alter-database
# ALTER DATABASE
> Update storage-related settings on a MotherDuck database.
The `ALTER DATABASE` statement updates storage-related settings for an existing MotherDuck database.
## Syntax
```sql
ALTER DATABASE SET = ;
```
## Options
### Native storage databases
These options apply to standard and transient databases backed by MotherDuck native storage.
| Name | Data type | Description |
|------|-----------|-------------|
| `SNAPSHOT_RETENTION_DAYS` | INTEGER | Number of days to retain automatic and unnamed snapshots. Must be a non-negative integer within your [plan limits](#plan-limits-for-native-storage). `0` disables historical snapshots. Named snapshots are retained until unnamed. |
### DuckLake databases
These options apply to [DuckLake](/concepts/ducklake) databases (fully managed and BYOB).
| Name | Data type | Description |
|------|-----------|-------------|
| `AUTO_MAINTENANCE` | BOOLEAN | Enables or disables [auto maintenance](/concepts/ducklake#auto-maintenance) (file optimization and snapshot lifecycle management). Fully managed DuckLake databases have this enabled by default; BYOB databases have it disabled by default. |
| `SNAPSHOT_RETENTION_DAYS` | INTEGER or NULL | Number of days to retain DuckLake snapshots. Defaults to `NULL` (infinite retention). Set a positive integer to enable automatic snapshot expiration. Requires `AUTO_MAINTENANCE` to be enabled. |
## Notes
Use [`ALTER DATABASE SET SNAPSHOT`](/sql-reference/motherduck-sql-reference/alter-database-snapshot) to restore a native storage database to a snapshot.
Refer to the [snapshots guide](/concepts/snapshots) for snapshot behavior and to [Storage lifecycle](/concepts/storage-lifecycle#standard-databases) for plan limits on retention.
## Plan limits for native storage
For standard and transient databases, `SNAPSHOT_RETENTION_DAYS` is limited by plan:
- Business: 0-90 days
- Lite (paid): 1 day (min/max)
- Lite (free): 0 days (min/max)
## Examples
### Native storage
```sql
ALTER DATABASE my_db SET SNAPSHOT_RETENTION_DAYS = 7;
```
### DuckLake
Enable auto maintenance for a BYOB DuckLake database:
```sql
ALTER DATABASE my_ducklake SET AUTO_MAINTENANCE = TRUE;
```
Set a snapshot retention period for a DuckLake database:
```sql
ALTER DATABASE my_ducklake SET SNAPSHOT_RETENTION_DAYS = 7;
```
Revert to infinite snapshot retention:
```sql
ALTER DATABASE my_ducklake SET SNAPSHOT_RETENTION_DAYS = NULL;
```
Disable auto maintenance:
```sql
ALTER DATABASE my_ducklake SET AUTO_MAINTENANCE = FALSE;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/alter-database-snapshot
# ALTER DATABASE SET SNAPSHOT
> Restore a database from a snapshot using ALTER DATABASE SET SNAPSHOT TO.
## Overview
`ALTER DATABASE ... SET SNAPSHOT TO` overwrites a target database with the contents of a selected snapshot. You can restore from a snapshot created by the same database or from another database you own. For background on snapshots and retention, see the [snapshots guide](/concepts/snapshots).
:::caution
This replaces the current contents of the target database. If you want to inspect a snapshot before overwriting, use `CREATE DATABASE ... FROM ...` to clone it first.
:::
## Syntax
```sql
ALTER DATABASE SET SNAPSHOT TO (
SNAPSHOT_ID '' [, DATABASE_NAME '']
| SNAPSHOT_TIME '' [, DATABASE_NAME '']
| SNAPSHOT_NAME ''
);
```
## Options
| Option | Type | Description |
|--------|------|-------------|
| SNAPSHOT_ID | UUID | Restores to the snapshot with this ID. The source database is inferred unless `DATABASE_NAME` is provided. |
| SNAPSHOT_TIME | TIMESTAMP | Restores to the newest snapshot created at or before this timestamp. Uses the target database unless `DATABASE_NAME` is provided. |
| SNAPSHOT_NAME | STRING | Restores to a named snapshot. Only valid for snapshots created with `CREATE SNAPSHOT ...`. |
| DATABASE_NAME | STRING | Source database for `SNAPSHOT_ID` or `SNAPSHOT_TIME`. Not allowed with `SNAPSHOT_NAME`. |
## Notes
- Only one snapshot selector can be used per statement.
- `DATABASE_NAME` is only valid with `SNAPSHOT_ID` or `SNAPSHOT_TIME`. It is not allowed with `SNAPSHOT_NAME`.
- `SNAPSHOT_TIME` picks the newest snapshot created at or before the timestamp. Use UTC; the recommended format is `YYYY-MM-DD HH:MM:SS[.ffffff]`.
- Automatic and unnamed snapshots are only available if `snapshot_retention_days` is greater than 0. Named snapshots are retained until they are unnamed. See [`ALTER DATABASE`](/sql-reference/motherduck-sql-reference/alter-database).
- To list snapshots and their IDs, query [`MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS`](/sql-reference/motherduck-sql-reference/md_information_schema/database_snapshots).
- This statement applies to MotherDuck native storage databases. DuckLake databases do not support snapshot restore.
## Examples
Restore to a snapshot ID (source database inferred):
```sql
ALTER DATABASE my_db SET SNAPSHOT TO (SNAPSHOT_ID 'c204ce3b-f3fd-4677-8a05-e8680648cf27');
```
Restore to a snapshot ID from a specific source database (extra safety):
```sql
ALTER DATABASE my_db SET SNAPSHOT TO (
DATABASE_NAME 'prod_db',
SNAPSHOT_ID 'c204ce3b-f3fd-4677-8a05-e8680648cf27'
);
```
Restore to a snapshot by time from the same database:
```sql
ALTER DATABASE my_db SET SNAPSHOT TO (SNAPSHOT_TIME '2025-07-29 14:30:25');
```
Restore to a snapshot by time from another database:
```sql
ALTER DATABASE my_db SET SNAPSHOT TO (
DATABASE_NAME 'prod_db',
SNAPSHOT_TIME '2025-07-29 14:30:25'
);
```
Restore to a named snapshot:
```sql
ALTER DATABASE my_db SET SNAPSHOT TO (SNAPSHOT_NAME 'prod_backup');
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/alter-snapshot
# ALTER SNAPSHOT
> Rename or remove names from database snapshots using ALTER SNAPSHOT.
`ALTER SNAPSHOT` renames a snapshot or removes its name. The only supported option is `snapshot_name`.
## Syntax
```sql
ALTER SNAPSHOT SET snapshot_name = '';
```
### Snapshot selector
Snapshot selectors resolve within a database. If you don't qualify the database, the current database (set with `USE`) is used.
```text
:=
.
|
| ''
```
- `.` targets a snapshot by name on a specific database. Use this when you want to rename a snapshot without switching databases.
- `` targets a snapshot by name on the current database (set with `USE`). Unquoted names must be valid SQL identifiers (letters, digits, and underscores). Use double quotes for names with spaces or punctuation (single quotes are reserved for the UUID-or-name form).
- `''` targets a snapshot UUID or a snapshot name on the current database. MotherDuck first tries to resolve the value as a snapshot UUID. If no snapshot is found, it falls back to resolving it as a snapshot name. This form does not accept a database qualifier, so use `USE` first if needed. If a snapshot name looks like a UUID, use the identifier form (unquoted or double-quoted) to avoid UUID resolution.
### Options
| Option | Type | Description |
| --- | --- | --- |
| `snapshot_name` | STRING | New name for the snapshot (string literal). Use `''` to remove the name. When set, names must be 1-255 characters and unique per user across all databases. |
## Considerations
- Named snapshots are available on the Business plan only. `ALTER SNAPSHOT` will error on plans that do not support
named snapshots.
- This command applies only to MotherDuck databases (not DuckLake databases or shares).
- To list snapshots, query `md_information_schema.database_snapshots` (for example, filter by `user_name`).
- Removing a snapshot name makes it subject to `snapshot_retention_days`. See the [snapshots guide](/concepts/snapshots).
- `snapshot_name` only accepts a string literal. Expressions and `NULL` are not supported.
## Example usage
```sql
-- Rename a snapshot in the current database
USE my_db;
ALTER SNAPSHOT nightly_backup SET snapshot_name = 'nightly_backup_2025_02_01';
-- Rename a snapshot using a database-qualified name
ALTER SNAPSHOT analytics.month_end SET snapshot_name = 'fy2025_q4_close';
-- Rename a snapshot by UUID
USE my_db;
ALTER SNAPSHOT '3f2504e0-4f89-11d3-9a0c-0305e82c3301' SET snapshot_name = 'pre_migration';
-- Rename a snapshot that has spaces or special characters in its name
USE my_db;
ALTER SNAPSHOT 'month end (final)' SET snapshot_name = 'month_end_final';
-- Remove a snapshot name (unset)
USE my_db;
ALTER SNAPSHOT '3f2504e0-4f89-11d3-9a0c-0305e82c3301' SET snapshot_name = '';
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/attach
# ATTACH
> Attach local databases, MotherDuck databases, or public shares to your session
The `ATTACH` command in MotherDuck can be used to:
- Attach a local database to access local data
- Re-attach a previously detached MotherDuck database or [share](/key-tasks/sharing-data/sharing-overview/)
- Attach a public [share](/key-tasks/sharing-data/) created by any MotherDuck user in the same cloud region as your Organization, including users outside your Organization
## Attaching databases
### Syntax for databases
```sql
ATTACH 'md:'
```
Parameters:
* `database_name`: The name of the MotherDuck database to attach. Pass an empty string (`md:`) to attach all databases in your workspace -- see the attach-mode behavior below.
### Attach mode set by `ATTACH`
If your session has not connected to MotherDuck yet, the form of the `ATTACH` string determines which [attach mode](/key-tasks/authenticating-and-connecting-to-motherduck/attach-modes/) the session enters:
* `ATTACH 'md:'` -- enters **workspace mode**. Attaches every database in your saved workspace. Subsequent attach/detach changes are persisted and stay in sync with parallel connections.
* `ATTACH 'md:'` -- enters **single mode**. Attaches only the named database without using your saved workspace. Attachment changes are session-scoped and not persisted. You can still `ATTACH` additional databases mid-session, including shares (for example, `ATTACH 'md:_share//'`).
The mode is set by the first command that connects to MotherDuck and can't be switched mid-session. That first command isn't always an `ATTACH`: client connection strings like `duckdb.connect('md:')` in Python or `duckdb 'md:'` from the CLI also establish the mode. If the session is already connected in workspace mode, `ATTACH 'md:'` just adds that database to the workspace rather than switching to single mode.
### Important notes for database attachment
#### Local database `ATTACH` operations:
* Are temporary and last only for the current session
* Data stays local and isn't uploaded to MotherDuck
* Use file paths instead of share URLs
#### MotherDuck database `ATTACH` operations:
* Are persistent, as they attach the database/share to your MotherDuck account.
* Requires read/write permissions for the database.
* The database must have been created by the active user and must have already been detached.
* If the remote database was not detached prior to running the `ATTACH` command, using the `md:` prefix will produce an error rather than creating a local database and attaching it.
* For a remote MotherDuck database, the database name is used to indicate what to attach and no alias is permitted.
::::info Aliasing Databases
Aliasing behavior in MotherDuck considers your relationship to the database itself. For databases owned by your user, aliases are not allowed. You will see an error that says `Database aliases are not yet supported by MotherDuck in workspace mode` when attempting to do this.
::::
## Attaching shares
Sharing in MotherDuck is done through shares. Recipients of a share must `ATTACH` the share, which creates a read-only database. This is a zero-copy, zero-cost, metadata-only operation. [Learn more about sharing in MotherDuck](/key-tasks/sharing-data/sharing-overview.md).
:::note
Shares are region-scoped based on your Organization's cloud region. MotherDuck Organizations are scoped to a single cloud region that must be chosen when creating the organization on sign up.
:::
:::info Important
If a shared database contains views or other objects that reference tables using the fully qualified name, for example, `my_db.main.my_table`, you must alias the share to match the original database name. Otherwise, those references can't be resolved and queries against those views fail. For example `ATTACH md:_share/ducks/e9ads7-dfr32-41b4-a230-bsadgfdg32tfa as birds;` means a view that does `SELECT * FROM ducks` will no longer be able to resolve the correct table. See [Views and fully-qualified table references](/key-tasks/sharing-data/sharing-overview/#views-and-fully-qualified-table-references) for details.
:::
### Syntax for shares
```sql
ATTACH [AS ];
```
### Shorthand convention for shares
You may choose to name the new database by using `AS `. If you omit this clause, the new database will be given the same name as the source database that's being shared. For shares, database aliases are _optional_, the default name is the string following `_share`, i.e. `ATTACH md:_share/ducks/e9ads7-dfr32-41b4-a230-bsadgfdg32tfa;` will have the alias `ducks`. When attaching a share, the alias name remains in effect for as long as the database is attached. If the database is detached for any reason, the associated alias name is automatically cleared as well.
## Examples
### Attaching databases
```sql
-- Attach a specific MotherDuck database. If this is the first MotherDuck
-- connection in the session, the session enters single mode; if the session
-- is already in workspace mode, the database is added to the workspace.
ATTACH 'md:';
-- Attach all MotherDuck databases in the workspace (enters workspace mode
-- if no MotherDuck connection has been made yet).
ATTACH 'md:';
-- Attach a local database
ATTACH '/path/to/my_database.duckdb';
ATTACH 'a_new_local_duckdb';
```
### Listing shares
```sql
-- your shares
FROM MD_INFORMATION_SCHEMA.OWNED_SHARES;
-- list all shares from service accounts
FROM MD_INFORMATION_SCHEMA.SHARED_WITH_ME WHERE owner LIKE 'sa-%';
```
### Attaching shares
```sql
ATTACH 'md:_share/ducks/0a9a026ec5a55946a9de39851087ed81' AS birds; # attaches the share as database `birds`
ATTACH 'md:_share/ducks/0a9a026ec5a55946a9de39851087ed81'; # attaches the share as database `ducks`
```
## Troubleshooting
### Finding share URL
The Share URL is provided when you [create a share](/key-tasks/sharing-data/sharing-overview/#creating-a-share).
You can also see shares available for attachment by querying the [`MD_INFORMATION_SCHEMA.SHARED_WITH_ME`](/sql-reference/motherduck-sql-reference/md_information_schema/shared_with_me/) view.
### Share alias conflicts
When you attach a share, its alias defaults to the source database name (the string after `_share/` in the URL). If you already have a database with that name, the attach fails with:
```text
Can't open share: Share alias cannot be the same as an existing database name.
is already taken and used as a database name.
```
To resolve this, either:
1. **Use a different alias** when attaching the share:
```sql
ATTACH 'md:_share/analytics/abc123' AS analytics_shared;
```
2. **Detach or rename the conflicting database** so the share can use the default alias.
This commonly happens when a service account used for [embedding Dives](/key-tasks/ai-and-motherduck/dives/embedding-dives/) owns a database with the same name as one of the Dive's shared databases. In that case, detach the database from the service account or use a dedicated service account that does not own conflicting databases.
### Handling name conflicts between local and remote databases
In case of name conflict between a local database and a remote database, there are two possible paths:
1. Attach the local database with a different name using an alias with `AS`. For instance : `ATTACH 'my_db.db' AS my_new_name`
2. Create a share out of your remote database and attach it with an alias. Shares are read-only.
### Using `SHARES` with [read scaling replicas](/key-tasks/authenticating-and-connecting-to-motherduck/read-scaling/)
A database cannot be attached with a [read_scaling](/key-tasks/authenticating-and-connecting-to-motherduck/read-scaling/#understanding-read-scaling-tokens) token. Databases should first be attached by an account + token with read_write permission, then accessed through read_scaling tokens.
For more information, see the [Attach & Detach](/key-tasks/database-operations/detach-and-reattach-motherduck-database) guide.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/copy-database
# COPY FROM DATABASE
> Copy a database from one location to another in MotherDuck
The `COPY FROM DATABASE` statement creates a new database from an existing one by copying its structure and data. This command can be used to:
[Interact with MotherDuck Databases](#copy-a-motherduck-database-to-a-motherduck-database)
- Copy MotherDuck databases to MotherDuck databases
[Interact with Local Databases](#interacting-with-local-databases)
- Copy local databases to MotherDuck databases
- Copy MotherDuck databases to local databases
- Copy local databases to local databases
The `COPY FROM DATABASE` command is a multiple statement macro. Multiple statement macros are not supported in Wasm and as a result, this command will not work in the MotherDuck Web UI when copying both schema and data. However, the command works in the MotherDuck Web UI if either the `(DATA)` option is specified or the `(SCHEMA)` option is specified. All other drivers support this command, including the DuckDB CLI.
:::caution No zero-copy clone
`COPY FROM DATABASE` creates a *physical* copy of both the schema and the data. It **does not** use MotherDuck's zero-copy cloning, so the operation may take longer to run and will consume additional storage proportional to the size of the source database. If you want to zero-copy clone a database, use the [`COPY FROM DATABASE (OVERWRITE)`](/sql-reference/motherduck-sql-reference/copy-database-overwrite.md) or the [`CREATE DATABASE ... FROM` statement](/sql-reference/motherduck-sql-reference/create-database.md).
:::
## Syntax
```sql
COPY FROM DATABASE TO [ (SCHEMA) | (DATA) ]
```
### Parameters
- ``: The name or path of the source database to copy from
- ``: The name or path of the target database to create
- `(SCHEMA)`: Optional parameter to copy only the database schema without data
- `(DATA)`: Optional parameter to copy only the database data without schema
## Example Usage
### Copy a MotherDuck database to a MotherDuck database
This is the same as [creating a new database from an existing one](/sql-reference/motherduck-sql-reference/create-database.md).
```sql
COPY FROM DATABASE my_db TO my_db_copy;
```
### Interacting with Local Databases
These operations can be done with access to the local filesystem, i.e. inside the DuckDB CLI.
#### Copy a local database to a MotherDuck database
```sql
ATTACH 'md:';
ATTACH 'local_database.db';
CREATE DATABASE md_database;
COPY FROM DATABASE local_database TO md_database;
```
#### Copy a MotherDuck database to a local database
To copy a MotherDuck database to a local database requires some extra steps.
```sql
ATTACH 'md:';
ATTACH 'local_database.db' as local_db;
COPY FROM DATABASE my_db TO local_db;
```
#### Copy a local database to a local database
To copy a local database to a local database, please see the [DuckDB documentation](https://duckdb.org/docs/stable/sql/statements/copy.html#copy-from-database--to).
### Copying the Database Schema
```sql
COPY FROM DATABASE my_db TO my_db_copy (SCHEMA);
```
This will copy the schema of the database, but not the data.
### Copying the Database Data
```sql
COPY FROM DATABASE my_db TO my_db_copy (DATA);
```
This will copy the data of the database, but not the schema.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/copy-database-overwrite
# COPY FROM DATABASE (OVERWRITE)
> Overwrite a database with a zero-copy clone from another database.
The `COPY FROM DATABASE ... (OVERWRITE [, OPTIONS])` statement will make the target database contain exactly the same data as the source database via zero-copy cloning, effectively overwriting it.
This command will wait on any ongoing write transactions on the target database to complete, and prevent new ones from starting while it is in progress.
# Source Database Options
These additional options can be applied, in addition to OVERWRITE, to specify a specific snapshot of the source database to clone.
| Name | Data Type | Value |
|-------------|-----------|-----------------------------------|
| SNAPSHOT_TIME | TIMESTAMP | Selects the newest snapshot created before or at this timestamp |
| SNAPSHOT_ID | UUID | ID of snapshot to clone |
| SNAPSHOT_NAME | STRING | Name of snapshot to clone |
:::note
This syntax operates at the metadata level and is therefore unique to MotherDuck.
:::
:::tip Zero-copy clone
This command operates purely at the MotherDuck metadata layer, so it is a **zero-copy clone**. The operation is almost instantaneous and does not duplicate any underlying data.
:::
## Syntax
```sql
COPY FROM DATABASE (OVERWRITE) [ TO ]
```
### Parameters
- ``: The name or path of the source database to copy from, can be either a MotherDuck database or a share.
- ``: The name or path of the target database to create, must be a MotherDuck database that the user owns.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/create-database
# CREATE DATABASE
> Create a database, zero-copy clone from an existing database, or import a local DuckDB file into MotherDuck.
The `CREATE DATABASE` statement creates a new database in MotherDuck.
It can be used for the following operations:
- Create a MotherDuck database from a local DuckDB database.
- Create a MotherDuck database from another MotherDuck database or [share](/key-tasks/sharing-data/sharing-overview/) using zero-copy clone (without physically copying data).
:::note Copy to local database
To copy a MotherDuck database to a local database, use the [`COPY FROM DATABASE`](/sql-reference/motherduck-sql-reference/copy-database.md) statement.
:::
::::tip Zero-copy clone
When the source is another MotherDuck database or a share, `CREATE DATABASE ... FROM` performs a **zero-copy clone**. The command completes almost instantly because no data is physically duplicated. When the source is a local file or `CURRENT_DATABASE()`, data is physically copied to MotherDuck.
::::
## Syntax
```sql
CREATE [ OR REPLACE ] DATABASE [ IF NOT EXISTS ]
[
FROM |
FROM | |
FROM '' |
FROM 'md:_share/...' |
FROM CURRENT_DATABASE() -- Important: this command does not work with attached shares
]
[(DATABASE OPTIONS)];
```
You can also pass the name of an attached share or a share URL as the database name, for example `CREATE DATABASE FROM my_share` or `CREATE DATABASE FROM 'md:_share/...'`.
If the database name already exists, the statement returns an error unless you specify `IF NOT EXISTS`.
Similar to DuckDB table name conventions, database names that start with a number or contain special characters must be double-quoted when used. Example: `CREATE DATABASE "123db"`
Creating a database does not change the active database. Run `USE DATABASE ` to switch.
## Database options
Databases on MotherDuck are either native storage databases or DuckLake databases. Each type has certain options which can be configured upon creation.
All native storage databases have a transient status and a historical retention period.
MotherDuck supports configuring historical retention periods upon creation, as well as after creation with [`ALTER DATABASE`](/sql-reference/motherduck-sql-reference/alter-database).
You can set the transient status upon creation. This can't be changed after database creation. Transient databases have a different failsafe period than non-transient databases.
| Name | Database type | Description |
|------------|----------------|----------------------------------------------------------------------------------------------------------------------------------------------|
| STANDARD | Native storage | Leave blank; any database created in MotherDuck defaults to a standard, native storage database. |
| TRANSIENT | Native storage | Specify `TRANSIENT` at database creation to enable transient storage. Refer to the [Storage lifecycle management overview](/concepts/storage-lifecycle#transient-databases) for more details. |
| SNAPSHOT_RETENTION_DAYS | Native storage | Provide an integer to specify the number of days to retain automatic and unnamed snapshots as `historical_bytes`. Named snapshots are retained until unnamed. Refer to the [Storage lifecycle management overview](/concepts/storage-lifecycle#storage-management) for more details. |
| DUCKLAKE | DuckLake | Specify `TYPE DUCKLAKE` at database creation to create a fully managed DuckLake. Refer to the [DuckLake overview](/integrations/file-formats/ducklake/) for more details. |
| DATA_PATH | DuckLake | Optional data path for DuckLake storage (for example, `DATA_PATH 's3://bucket/prefix'`). Buckets must be in the same AWS region as your MotherDuck org (`us-east-1` or `us-west-2` for US, `eu-central-1` for EU). |
| ENCRYPTED | DuckLake | Enables encryption for DuckLake storage. To enable it, specify `ENCRYPTED` at database creation. Refer to [Encryption](https://ducklake.select/docs/stable/duckdb/advanced_features/encryption) for more details. |
| DATA_INLINING_ROW_LIMIT | DuckLake | Row-size threshold (bytes) for inline data storage. Provide an integer value. |
| AUTO_MAINTENANCE | DuckLake | Enables or disables [auto maintenance](/concepts/ducklake#auto-maintenance). Fully managed DuckLake databases have this enabled by default; BYOB databases have it disabled by default. |
| SNAPSHOT_RETENTION_DAYS | DuckLake | Number of days to retain DuckLake snapshots. Defaults to `NULL` (infinite retention). Requires `AUTO_MAINTENANCE` to be enabled. |
## Source database options
These options are only available for native MotherDuck databases. They apply to the source database that is being cloned.
Snapshot selectors are only supported when cloning a native MotherDuck database. They are not supported for DuckLake databases.
| Name | Data Type | Value |
|-------------|-----------|-----------------------------------|
| SNAPSHOT_TIME | TIMESTAMP | Selects the newest snapshot created before or at this timestamp |
| SNAPSHOT_ID | UUID | ID of the snapshot to clone |
| SNAPSHOT_NAME | STRING | Name of the snapshot to clone |
Once these properties are set, they cannot be changed. However, MotherDuck supports cloning databases and copying data content between transient and standard databases. Note that the following syntax `CREATE DATABASE empty_duck FROM non_empty_duck (TRANSIENT);` is not supported. Please refer to the examples below for supported methods.
## Example usage
To create an empty database:
```sql
CREATE DATABASE empty_ducks;
```
If the database name already exists, the statement fails unless you use `OR REPLACE` or `IF NOT EXISTS`.
```sql
CREATE DATABASE ducks;
-- Succeeds if 'ducks' does not exist
CREATE DATABASE ducks;
-- Error: Failed to create database: database with name 'ducks' already exists
CREATE OR REPLACE DATABASE ducks; -- Replaces existing 'ducks' with an empty database
CREATE DATABASE IF NOT EXISTS ducks; -- No-op if 'ducks' already exists
```
To *copy* an entire database from your local DuckDB instance into MotherDuck:
```sql
USE ducks_db;
CREATE DATABASE ducks FROM CURRENT_DATABASE();
-- Or alternatively, use the following command - if ducks_db exists, even if populated, it will be replaced with an empty one:
CREATE OR REPLACE DATABASE ducks FROM ducks_db;
-- In the following, if ducks_db exists, the operation will be skipped, but it will not error:
CREATE DATABASE IF NOT EXISTS ducks_db;
```
To configure database options in MotherDuck:
```sql
-- Create a transient database:
CREATE DATABASE cloud_db (TRANSIENT);
-- Create a database with seven days retention:
CREATE DATABASE cloud_db (SNAPSHOT_RETENTION_DAYS 7)
-- Create a DuckLake:
CREATE DATABASE cloud_ducklake (TYPE DUCKLAKE);
-- Create a DuckLake with a storage path and encryption:
CREATE DATABASE cloud_ducklake
(
TYPE DUCKLAKE,
DATA_PATH 's3://my-bucket/ducklake',
ENCRYPTED true
);
-- Create a DuckLake with auto maintenance and snapshot retention:
CREATE DATABASE my_ducklake
(
TYPE DUCKLAKE,
AUTO_MAINTENANCE TRUE,
SNAPSHOT_RETENTION_DAYS 7
);
```
To copy content between standard and transient databases:
```sql
-- Option 1: Clone with inherited properties
-- The new database inherits the transient/standard property from the source
CREATE OR REPLACE DATABASE dest_db FROM source_db;
-- Option 2: Copy content while preserving destination properties
-- Replaces the contents of dest_db without changing its configuration
CREATE DATABASE dest_db (TRANSIENT);
COPY FROM DATABASE source_db (OVERWRITE) TO dest_db;
```
:::note Limitations
You cannot copy data from a transient database into a standard database using `COPY FROM DATABASE (OVERWRITE)`, as this would violate the standard database's 7-day failsafe guarantee. To copy transient data into a standard database, use Option 1.
:::
To zero-copy clone a database that is already attached in MotherDuck:
```sql
CREATE DATABASE cloud_db FROM another_cloud_db;
```
To zero-copy clone a past snapshot of a database in MotherDuck
```sql
CREATE DATABASE cloud_db FROM another_cloud_db (SNAPSHOT_NAME 'prod_backup');
CREATE DATABASE cloud_db FROM another_cloud_db (SNAPSHOT_ID '3f2504e0-4f89-11d3-9a0c-0305e82c3301');
CREATE DATABASE cloud_db FROM another_cloud_db (SNAPSHOT_TIME '2025-07-29 14:30:25.123456');
```
To upload a local DuckDB database file:
```sql
CREATE DATABASE flying_ducks FROM './databases/local_ducks.db';
```
To upload an attached local DuckDB database:
```sql
ATTACH './databases/local_ducks.db';
CREATE DATABASE flying_ducks FROM local_ducks;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/create-secret
# CREATE SECRET
> Create a secret in MotherDuck
MotherDuck lets you store your cloud storage credentials for convenience, using the familiar DuckDB `CREATE SECRET` syntax. See [DuckDB CREATE SECRET documentation](https://duckdb.org/docs/sql/statements/create_secret.html).
Ensure you add the `PERSISTENT` or `IN MOTHERDUCK` keyword to create MotherDuck secrets. Secrets stored in MotherDuck are fully encrypted and scoped to the user who created them. They are not shared with other users in your organization.
:::note
You can use the `PERSISTENT` keyword to create a local file persistent secret in local DuckDB as well. It gets stored unencrypted in the `~/.duckdb/stored_secrets` directory.
When you've loaded the MotherDuck extension, `PERSISTENT` secrets are stored encrypted in MotherDuck. Locally persisted secrets are not impacted.
You can still create locally persisted secrets when using MotherDuck by specifying the secret storage backend: `CREATE SECRET IN LOCAL_FILE`.
:::
When using MotherDuck, the statement below creates a cloud-persistent secret stored in MotherDuck.
## Syntax
```sql
CREATE [OR REPLACE] (PERSISTENT SECRET [secret_name] | SECRET [secret_name] IN MOTHERDUCK)
(
TYPE ,
);
```
## Secret parameters
Supported parameters for S3, GCS, and R2 secrets:
| Name | Description | Secret | Type | Default |
|------|-------------|--------|------|---------|
| ENDPOINT | Specify a custom S3 endpoint | S3, GCS, R2 | STRING | s3.amazonaws.com for S3 |
| KEY_ID | The ID of the key to use | S3, GCS, R2 | STRING | - |
| REGION | The region used for authentication. For S3, this should match the region of the bucket. For R2, use `auto` since R2 buckets are regionless. | S3, GCS, R2 | STRING | Orgs will default to the region that was chosen at signup: us-east-1, us-west-2, or eu-central-1. For R2, defaults to `auto`. |
| SECRET | The secret of the key to use | S3, GCS, R2 | STRING | - |
| SESSION_TOKEN | Optionally, a session token can be passed to use temporary credentials | S3, GCS, R2 | STRING | - |
| URL_COMPATIBILITY_MODE | Can help when URLs contain problematic characters | S3, GCS, R2 | BOOLEAN | true |
| URL_STYLE | Either vhost or path | S3, GCS, R2 | STRING | vhost for S3, path for R2 and GCS |
| USE_SSL | Whether to use HTTPS or HTTP | S3, GCS, R2 | BOOLEAN | true |
| ACCOUNT_ID | The R2 account ID to use for generating the endpoint URL | R2 | STRING | - |
| KMS_KEY_ID | AWS KMS (Key Management Service) key for Server Side Encryption S3 | S3 | STRING | - |
| SCOPE | Scope of secret resolution; In the case of multiple matching secrets, the longest prefix is chosen | S3, GCS, R2 | STRING | - |
::::info
Because of SSL certificate verification requirements, S3 bucket names that contain dots (.) cannot be accessed using vhost style URLs. This is due to AWS's SSL wildcard certificate (*.s3.amazonaws.com) which only validates single-level subdomains. To resolve this SSL issue, use `URL_STYLE path` in your secret.
::::
## Examples
### Manually defined S3 secret
To manually create an S3 secret in MotherDuck:
```sql
CREATE SECRET IN MOTHERDUCK (
TYPE S3,
KEY_ID 's3_access_key',
SECRET 's3_secret_key',
REGION 'us-east-1',
SCOPE 'my-bucket-path'
);
```
This creates a new secret with a default name (for S3, `__default_s3`) and a default scope (i.e., `[s3://, s3n://, s3a://]`) used for path matching explained below.
::::info
DuckDB uses the `SCOPE` parameter to determine which secret to use. When using persistent secrets or public buckets, scoping the secrets is important so that the database uses the correct secret. Imprecise scoping will lead to authentication errors.
Learn more in the [DuckDB documentation](https://duckdb.org/docs/stable/configuration/secrets_manager.html#creating-multiple-secrets-for-the-same-service-type).
::::
### Secret providers
MotherDuck supports the same [secret providers](https://duckdb.org/docs/configuration/secrets_manager.html#secret-providers) as DuckDB.
To create a secret by automatically fetching credentials using mechanisms provided by the AWS SDK, see [AWS CREDENTIAL_CHAIN provider](https://duckdb.org/docs/extensions/httpfs/s3api#credential_chain-provider).
To create a secret by automatically fetching credentials using mechanisms provided by the Azure SDK, see [Azure CREDENTIAL_CHAIN provider](https://duckdb.org/docs/extensions/azure#credential_chain-provider).
To create a secret by automatically fetching credentials using mechanisms provided by the Hugging Face CLI, see [Hugging Face CREDENTIAL_CHAIN provider](https://duckdb.org/docs/extensions/httpfs/hugging_face#authentication).
To store a secret from a given secret provider in MotherDuck, specify the `PERSISTENT` or `IN MOTHERDUCK` keyword in addition.
### Provider examples
If you are logged in to a provider on your local machine you can use those credentials to connect to the bucket. Creating the secret does not work in the MotherDuck UI since your credential provider is not available there, but you can use the secret once it's stored.
To store a secret configured through `aws configure`:
```sql
CREATE PERSISTENT SECRET aws_secret (
TYPE S3,
PROVIDER CREDENTIAL_CHAIN
);
```
To store a secret using AWS SSO credentials:
```sql
-- if you use AWS SSO, run `aws sso login --profile ` first
CREATE SECRET aws_secret IN MOTHERDUCK (
TYPE S3,
PROVIDER CREDENTIAL_CHAIN,
CHAIN 'sso',
PROFILE ''
);
```
:::note Secret validation
Starting with DuckDB v1.4.0, credentials are validated at secret creation time. If your credentials are not resolvable locally (for example, expired SSO tokens or missing `~/.aws/credentials`), `CREATE SECRET` will fail with a `Secret Validation Failure` error. The recommended fix is to use the correct `CHAIN` and `PROFILE` for your credential type (see the SSO example above) and confirm your SSO session is active. If you need to bypass local validation, you can add `VALIDATION 'none'`, but keep in mind that this skips the local check that confirms your credentials are valid before storing them in MotherDuck.
:::
To store a secret configured through `az configure`:
```sql
CREATE SECRET azure_secret IN MOTHERDUCK (
TYPE AZURE,
PROVIDER CREDENTIAL_CHAIN,
ACCOUNT_NAME 'some-account'
);
```
## Querying with secrets
[Secret scope](https://duckdb.org/docs/configuration/secrets_manager.html#creating-multiple-secrets-for-the-same-service-type) is supported in the same way as in DuckDB to allow multiple secrets of the same type to be stored in MotherDuck.
When there are multiple local (i.e. in memory and store in local file) and remote (i.e. MotherDuck) secrets of the same type, scope matching (secret scope against the file path) happens to determine which secret to use to open a file. Both local and remote secrets are considered in scope matching.
In the case of multiple matching secrets, the secret with the longest matching scope prefix is chosen.
In the case of multiple secrets stored in different secret storages sharing the same scope (e.g. the default scope if not specified), matching secret is chosen based on the following order: local temp secret > local_file secret > MotherDuck secret.
:::info Local secrets and cloud execution
When you query cloud storage (S3, GCS, Azure, R2) while connected to MotherDuck, the query is routed to MotherDuck's [cloud execution engine](/concepts/architecture-and-capabilities#dual-execution), not your local machine. MotherDuck can use **any** matching secret to authenticate with your storage provider, including temporary, in-memory secrets from your local DuckDB session. Your local DuckDB client does not connect to cloud storage directly.
:::
To see which secret (either local or remote) is being used by MotherDuck, the DuckDB `which_secret` table function can be used, which takes a path and the secret type.
### Example usage
To see which secret is used to open a file:
```sql
FROM which_secret('s3://my-bucket/my_dataset.parquet', 's3');
┌───────────────────────┬────────────┬────────────┐
│ name │ persistent │ storage │
│ varchar │ varchar │ varchar │
├───────────────────────┼────────────┼────────────┤
│ __default_s3 │ PERSISTENT │ motherduck │
└───────────────────────┴────────────┴────────────┘
```
## Discovering buckets and files
If you want to inspect cloud storage from SQL before querying files directly:
- Use [`MD_LIST_BUCKETS_FOR_SECRET()`](/sql-reference/motherduck-sql-reference/md-list-buckets-for-secret) to list buckets visible to an S3/AWS secret.
- Use [`MD_LIST_FILES()`](/sql-reference/motherduck-sql-reference/md-list-files) to list files in `s3://`, `azure://`, or `az://` paths.
:::note
`MD_LIST_FILES()` supports S3 and Azure paths only. It does not accept `r2://`, `gcs://`, or `gs://` paths.
:::
## Troubleshooting
If you encounter issues creating or using secrets, check out our troubleshooting guides:
- **[AWS S3 Secrets Troubleshooting](/documentation/troubleshooting/aws-s3-secrets.md)** - Common issues with AWS S3 authentication and credentials
- **[Error Messages](/documentation/troubleshooting/error_messages.md)** - Understanding MotherDuck error messages
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/create-share
# CREATE SHARE
> Create a share from a database to share data with other users
The `CREATE SHARE` statement creates a new share from a database. This command is used to share databases with other users. [Learn more about sharing in MotherDuck](/key-tasks/sharing-data/sharing-overview.md).
:::note
All shares are **read-only**. Only the creator of a database has write permissions.
:::
## Syntax
```sql
CREATE [ OR REPLACE ] SHARE [ IF NOT EXISTS ] [] [FROM ] (
[ACCESS ORGANIZATION | UNRESTRICTED | RESTRICTED],
[VISIBILITY DISCOVERABLE | HIDDEN],
[UPDATE MANUAL | AUTOMATIC]
);
```
If you attempt to create a share, yet a share with that name already exists, no new share will be created and the query will return an error.
The error will be silenced when you specify `IF NOT EXISTS`.
This statement returns a share URL of the form `md:_share//`.
- If the share is **Hidden**, you must pass this URL to the **data consumer**, who will need to [`ATTACH`](attach.md) the share.
- If the share is **Discoverable**, passing the URL to the **data consumer** is optional.
### _OR REPLACE_ clause
When you use the `OR REPLACE` clause to create or replace a share named `foo`, the share's **URL changes**. This means that
any clients connected to the old share URL will be **disconnected within a few minutes**.
To continue using the share named `foo`, clients must **re-attach** to it using the **new URL** provided by the `CREATE SHARE`
command. The old share URL will no longer be valid.
### _ACCESS_ clause
You can configure scope of access of the share:
- `ACCESS ORGANIZATION` (default) - only members of your Organization can access the share.
- `ACCESS UNRESTRICTED` - all MotherDuck users in the same cloud region as the share creator can access the share.
- `ACCESS RESTRICTED` - the share owner will be the only user with access to the share initially. Access for other users the share can be updated using the [`GRANT`](grant-access.md) and [`REVOKE`](revoke-access.md) commands.
If omitted, defaults to `ACCESS ORGANIZATION`.
:::note
Shares are **region-scoped** based on your Organization's cloud region. Each MotherDuck Organization is scoped to a single cloud region that must be chosen at Org creation when signing up.
MotherDuck is available on AWS in three regions:
- **US East (N. Virginia):** `us-east-1`
- **US West (Oregon):** `us-west-2`
- **Europe (Frankfurt):** `eu-central-1`
:::
### _VISIBILITY_ clause
For Organization scoped shares **only**, you may choose to make them Discoverable:
- `VISIBILITY DISCOVERABLE` (default) - all members of your Organization will be able to list/find the share in the UI or SQL.
- `VISIBILITY HIDDEN` - the share can only be accessed directly by the share URL, and is not listed to other users. A Share can be hidden only if it has its `ACCESS` set to `RESTRICTED`.
If omitted, Organization-scoped and Restricted shares default to `VISIBILITY DISCOVERABLE`. Unrestricted shares can only be **Hidden**.
### _UPDATE_ clause
Shares can be automatically or manually updated by the share creator.
- `UPDATE MANUAL` (default) - shares are only updated using the [`UPDATE SHARE`](update-share.md) command.
- `UPDATE AUTOMATIC` - the share is automatically updated when the underlying database changes. Typically, changes on the underlying database will automatically be published to the share within at most 5 minutes, after writes have completed. Ongoing overlapping writes may prolong share updating.
If omitted, defaults to `UPDATE MANUAL`.
### Shorthand convention
- If the database name is omitted, a share will be created from the current/active database.
- If the share name is omitted, the share will be named after the source database.
- If both database and share names are omitted, the share will be named and created after the current/active database.
## Example usage
```sql
-- If ducks_share exists, it will be replaced with a new share.
--A new share URL is returned.
CREATE OR REPLACE SHARE ducks_share;
-- If ducks_share exists, nothing is done. Its existing share URL is returned.
--Otherwise, a new share is created and its share URL is returned.
CREATE SHARE IF NOT EXISTS ducks_share;
```
```sql
USE mydb;
-- Using shorthand: Create a share named ''mydb'' from the current database ''mydb''.
-- Defaults: ACCESS ORGANIZATION, VISIBILITY DISCOVERABLE, UPDATE MANUAL
CREATE SHARE;
-- Using shorthand: Create a share named ''db2'' from the specified database ''db2''.
-- Defaults: ACCESS ORGANIZATION, VISIBILITY DISCOVERABLE, UPDATE MANUAL
CREATE SHARE FROM db2;
-- Explicitly create a share named ''birds_share'' from database ''birds''.
-- Set specific access, visibility, and update behavior.
CREATE SHARE birds_share FROM birds (
ACCESS RESTRICTED, -- Only the share owner has initial access
VISIBILITY HIDDEN, -- Not listed; requires direct URL access
UPDATE AUTOMATIC -- Automatically updates with source DB changes
);
```
:::note
All shares created prior to June 6, 2024 are Unrestricted and Hidden. To make these legacy shares Organization-scoped and Discoverable, you can alter them in the UI or delete and create new shares.
:::
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/create-snapshot
# CREATE SNAPSHOT
> Create a snapshot of a MotherDuck database for recovery or read scaling.
The `CREATE SNAPSHOT` statement creates a snapshot of a single MotherDuck native storage database. You can create an unnamed snapshot or provide a name to create a **named snapshot**.
:::note
This statement applies to native storage databases. DuckLake databases manage snapshots through [auto maintenance](/concepts/ducklake#auto-maintenance).
:::
Named snapshots can be looked up and restored later. Their names can be updated (or removed) using [`ALTER SNAPSHOT`](/sql-reference/motherduck-sql-reference/alter-snapshot). For retention and recovery behavior, see the [data recovery guide](/concepts/data-recovery).
## Syntax
```sql
CREATE SNAPSHOT [] OF ;
```
## Notes
- Only one database can be snapshotted per statement.
- If you omit a name, the snapshot is eligible for restore only while it remains within the database's `SNAPSHOT_RETENTION_DAYS` window. Use [`ALTER DATABASE`](/sql-reference/motherduck-sql-reference/alter-database) to configure retention.
- If you provide a name, the snapshot becomes a named snapshot and is retained until it is unnamed.
- `CREATE SNAPSHOT` waits for active write queries to finish and blocks new writes until the snapshot is created.
- MotherDuck also takes automatic snapshots in the background every minute when no write queries are running.
## Read scaling
Creating a snapshot will make the latest data available to read-scaling connections.
Each read-scaling instance picks up the latest available snapshot every minute. To minimize delays and ensure access to the latest data, use `CREATE SNAPSHOT` on the writer connection, followed by a `REFRESH DATABASE ` on the read scaling connection.
Learn more about [`REFRESH DATABASES`](/sql-reference/motherduck-sql-reference/refresh-database).
## Examples
Create a named snapshot:
```sql
CREATE SNAPSHOT prod_backup OF my_db;
```
Create an unnamed snapshot:
```sql
CREATE SNAPSHOT OF my_db;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/database_snapshots
# DATABASE_SNAPSHOTS view
> Query the DATABASE_SNAPSHOTS view for snapshot history and data recovery options.
The `MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS` view provides information about database snapshots for databases visible to the current user. This can be used for data recovery or to inspect snapshot history.
## Schema
When you query the `MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS` view, the results contain at least one row per database visible to the user. MotherDuck treats the most recent snapshot for each database as the "active" snapshot.
In addition, if you have historical snapshots or named snapshots associated with any of your databases, they will show up here too.
The `MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS` view has the following schema:
| Column Name | Data Type | Value |
|-------------|-----------|-----------------------------------|
| DATABASE_NAME | VARCHAR | The name of the database |
| DATABASE_ID | UUID | Unique ID for the database |
| SNAPSHOT_ID | UUID | Unique ID for the snapshot |
| SNAPSHOT_NAME | VARCHAR | Optional name for the snapshot (NULL for automatic snapshots) |
| CREATED_TS | TIMESTAMP | Time when the snapshot was created |
| ACTIVE_BYTES | UBIGINT | The logical size of the database at this snapshot |
| BYTES_WRITTEN | UBIGINT | The number of bytes written since the previous snapshot |
| BYTES_DELETED | UBIGINT | The number of bytes deleted since the previous snapshot |
| USER_NAME | VARCHAR | The user who owns the database corresponding to the snapshot (user or service account) |
| USER_ID | UUID | Unique ID of the database owner |
## Example usage
```sql
FROM MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS
LIMIT 10;
```
Get the active (most recent) snapshot for each database:
```sql
SELECT *
FROM MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS
QUALIFY ROW_NUMBER() OVER (
PARTITION BY database_id
ORDER BY created_ts DESC
) = 1
ORDER BY database_name;
```
List named snapshots for a specific database:
```sql
SELECT *
FROM MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS
WHERE database_name = 'example_db'
AND snapshot_name IS NOT NULL
ORDER BY created_ts DESC;
```
### View snapshots with retention settings
Combine `DATABASE_SNAPSHOTS` with [`DATABASES`](/sql-reference/motherduck-sql-reference/md_information_schema/databases) to see all snapshots for a database along with its retention period:
```sql
SELECT
s.database_name,
d.historical_snapshot_retention,
s.snapshot_id,
s.snapshot_name,
s.created_ts,
s.active_bytes
FROM MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS s
JOIN MD_INFORMATION_SCHEMA.DATABASES d
ON s.database_id = d.uuid
WHERE s.database_name = 'example_db'
ORDER BY s.created_ts DESC;
```
This query helps you understand which snapshots are available for [point-in-time restore](/concepts/data-recovery) and how long automatic snapshots will be retained before garbage collection.
### Admin: View all named snapshots in your organization
Admins can use [`STORAGE_INFO`](/sql-reference/motherduck-sql-reference/md_information_schema/storage_info) combined with `DATABASE_SNAPSHOTS` to see all named snapshots across the organization:
```sql
SELECT
s.user_name,
s.database_name,
s.snapshot_name,
s.snapshot_id,
s.created_ts,
s.active_bytes
FROM MD_INFORMATION_SCHEMA.DATABASE_SNAPSHOTS s
WHERE s.snapshot_name IS NOT NULL
ORDER BY s.user_name, s.database_name, s.created_ts DESC;
```
::::note Snapshot naming conflicts
Snapshot names must be unique per user, but different users can have snapshots with the same name. When restoring or referencing snapshots programmatically, use `user_id` or `user_name` along with `snapshot_name` to avoid ambiguity.
::::
## Understanding timestamps
Use `DATABASE_SNAPSHOTS.created_ts` for **snapshot creation times** — this is what you need for [point-in-time restore](/concepts/data-recovery) operations with [`ALTER DATABASE SET SNAPSHOT`](/sql-reference/motherduck-sql-reference/alter-database-snapshot).
Use [`STORAGE_INFO`](/sql-reference/motherduck-sql-reference/md_information_schema/storage_info)`.created_ts` for **database creation times** — this is useful for billing and lifecycle management.
| View | `created_ts` meaning | Use case |
|------|---------------------|----------|
| `DATABASE_SNAPSHOTS` | When the snapshot was created | Point-in-time restore, finding snapshots to recover |
| `STORAGE_INFO` | When the database was created | Storage billing, database lifecycle management |
## Troubleshooting
### Why do I only see one snapshot for my database?
If your database's retention is set to zero days, you will only be able to see the "active" snapshot associated with your database. To modify your database's retention see [`ALTER DATABASE`](/sql-reference/motherduck-sql-reference/alter-database).
### Why can't I find a snapshot from a specific time?
Automatic snapshots are only retained for the duration specified by `snapshot_retention_days` and when data is actively modified. Once a snapshot falls outside this window, it is garbage-collected and cannot be recovered. To check your database's retention setting:
```sql
SELECT name, historical_snapshot_retention
FROM MD_INFORMATION_SCHEMA.DATABASES
WHERE name = 'example_db';
```
If you want to keep snapshots when only querying a database, you can either use a named snapshot or actively create a snapshot with:
```sql
CREATE SNAPSHOT OF example_db;
```
### How can I see the current retention period for my database
You can find the historical retention period in the information schema:
```sql
select name, historical_snapshot_retention from md_information_schema.databases
```
## See also
- [`DATABASES` view](/sql-reference/motherduck-sql-reference/md_information_schema/databases) — Database metadata including retention settings
- [`STORAGE_INFO` views](/sql-reference/motherduck-sql-reference/md_information_schema/storage_info) — Storage billing and lifecycle information
- [Data Recovery](/concepts/data-recovery) — Step-by-step guide to restoring databases from snapshots
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/databases
# DATABASES view
> Query the DATABASES view to list all databases you have created in MotherDuck.
The `MD_INFORMATION_SCHEMA.DATABASES` view provides information about the current databases that the user created.
## Schema
When you query the `MD_INFORMATION_SCHEMA.DATABASES` view, the query results contain one row for each database that the current user created.
The `MD_INFORMATION_SCHEMA.DATABASES` view has the following schema:
| Column Name | Data Type | Value |
|-------------|-----------|-----------------------------------|
| NAME | STRING | The name or alias of the database |
| UUID | STRING | The UUID of the database |
| CREATED_TS | TIMESTAMP | The database’s creation time |
| TRANSIENT | BOOLEAN | Whether the database is transient |
| HISTORICAL_SNAPSHOT_RETENTION | INTERVAL | Period of time the database's snapshots are retained after becoming inactive |
| TYPE | STRING | Database type (ducklake or default) |
## Example usage
```sql
from MD_INFORMATION_SCHEMA.DATABASES;
```
| name | uuid | created_ts | transient | historical_snapshot_retention | type |
|----------------------|--------------------------------------|------------------------|-----------|-------------------------------|----------|
| tpch_sf1000_template | 2c80b37d-d307-44d8-aff6-33ea2294bd35 | 2024-10-21 14:26:30-04 | false | 00:00:00 | default |
| db1 | 445864c7-5758-42a2-9a5c-2f16620ebc9f | 2024-09-15 09:32:05-04 | false | 1 day | default |
| foo | 4d829a9e-e0da-408c-aafa-0fc50186a588 | 2024-09-03 13:32:10-04 | false | 1 day | default |
| tpch_sf1000 | fc4bf9f4-80d1-4fd9-b6fe-d6d71f40ef42 | 2024-10-21 14:26:30-04 | false | 1 day | default |
| my_ducklake | a1b2c3d4-e5f6-7890-abcd-ef1234567890 | 2025-03-10 11:15:42-04 | false | NULL | ducklake |
| lake_with_retention | b2c3d4e5-f6a7-8901-bcde-f12345678901 | 2025-04-01 09:20:18-04 | false | 7 days | ducklake |
For DuckLake databases, `historical_snapshot_retention` shows `NULL` when snapshot retention is set to infinite (the default), or the configured `SNAPSHOT_RETENTION_DAYS` value.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/describe-share
# DESCRIBE SHARE
> Get details about a specific share by name or URL.
The `DESCRIBE SHARE` statement is used to get details about a specific share.
:::info
The **creator** of the share object can execute this statement by passing the **share name**. The **receiver** of the share object can execute this statement by passing the **share link**.
:::
# Syntax
```sql
DESCRIBE SHARE [ | ];
```
# Example
Let's use the `sample_data` database which is auto attached to MotherDuck users to illustrate the command
```sql
DESCRIBE SHARE 'md:_share/sample_data/23b0d623-1361-421d-ae77-62d701d471e6';
```
It returns a table with the following columns:
| column_name | column_type | description |
|---------------| ----------- |-----------------------------|
| name | VARCHAR | Name of the share |
| url | VARCHAR | URL of the share |
| source_db_name | VARCHAR | Name of the database shared |
| source_db_uuid | UUID | uid of the database shared |
| access | VARCHAR | Whether anyone (referred to as UNRESTRICTED) within the same cloud region or only organization members (referred to as ORGANIZATION) can attach to the share by its share_url |
| visibility | VARCHAR | Whether the share is DISCOVERABLE or HIDDEN |
| update | VARCHAR | The share’s update mode (MANUAL vs. AUTOMATIC) |
| created_ts | TIMESTAMP WITH TIME ZONE | The share’s creation time |
You can be specific about what which columns you want to return by using the table function :
```sql
SELECT name, url, source_db_name FROM md_describe_database_share('md:_share/sample_data/23b0d623-1361-421d-ae77-62d701d471e6');
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/detach
# DETACH
> Detach local, remote, or shared databases from your session
The `DETACH` command in MotherDuck can be used to:
- Detach a local DuckDB database
- Detach a remote MotherDuck database
- Detach a shared database
:::info
Database aliases are not persisted when [Shares](/key-tasks/sharing-data/) are detached.
:::
## Detaching Databases
After a database has been created, it can be detached. This will prevent queries from accessing or modifying that database while it is detached. This command may be used on both local DuckDB databases and remote MotherDuck databases.
For a local database, specify the name of the database to detach and not the full path.
In the case of a remote MotherDuck database, the [`ATTACH`](attach.md) command can be used to re-attach at any point, so this is designed to be a convenience feature, not a security feature. `DETACH` can be used to isolate work on specific databases, while preserving the contents of the detached databases.
To see all databases, both attached and detached, use the [`SHOW ALL DATABASES` command](show-databases.md).
### Syntax for Databases
```sql
DETACH ;
```
### Examples of Database Detachment
```sql
-- Prior command:
-- ATTACH '/path/to/local_database.duckdb';
DETACH local_database;
-- Prior command:
-- CREATE DATABASE my_md_database;
DETACH my_md_database;
```
## Detaching Shares
Attached shares are sticky, and will continue to appear in your catalog unless you explicitly detach them.
### Syntax for Shares
```sql
DETACH ;
```
### Examples of Share Detachment
```sql
DETACH ducks;
```
For more information, see the [Attach & Detach](/key-tasks/database-operations/detach-and-reattach-motherduck-database) guide.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/drop-database
# DROP DATABASE
> Remove a database from MotherDuck.
The `DROP` statement removes a database entry added previously with the `CREATE` command.
By default (or if the `RESTRICT` clause is provided), the entry will not be dropped if there are any existing database shares that were created from it. If the `CASCADE` clause is provided then all the shares that are dependent on the database will be dropped as well.
# Syntax
```sql
DROP DATABASE [IF EXISTS] [CASCADE | RESTRICT];
```
# Example usage
```sql
DROP DATABASE ducks; -- drops database named `ducks`
DROP DATABASE ducks CASCADE; -- drops database named `ducks` and all the shares created from `ducks`
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/delete-secret
# DROP SECRET
> Delete a secret from MotherDuck or local storage.
The DuckDB `DROP SECRET` statement (see DuckDB [DROP SECRET documentation](https://duckdb.org/docs/sql/statements/create_secret#syntax-for-drop-secret)) works in MotherDuck to delete the secret previously created with `CREATE SECRET` statement.
# Syntax
```sql
DROP SECRET ;
```
When there are multiple secrets with the same name stored in different secret storages (e.g. in memory vs. in MotherDuck), either the persistent type or the secret storage type needs to be specified to remove ambiguity when dropping the secret.
# Example Usage
Disambiguate by specifying the storage type when dropping a secret:
```sql
DROP SECRET __default_s3 FROM motherduck;
```
Disambiguate by specifying the persistence type when dropping a secret:
```sql
DROP PERSISTENT SECRET __default_s3;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/drop-share
# DROP SHARE
> Delete a share and revoke access for all attached users.
`DROP SHARE` is used to delete a share by the share creator. Users who have attached the share will lose access.
This will throw an error if the share does not exist.
`DROP SHARE IF EXISTS` is used to delete a share by the share creator and will not throw an error if the share does not exist.
Shares can be attached with an alias name.
To **drop a share** with `DROP SHARE`, you must reference its **original name**, which you can find by running `LIST SHARES`.
If you want to remove a share from your workspace without deleting it completely, use [`DETACH`](/sql-reference/motherduck-sql-reference/detach.md) instead.
# Syntax
```sql
DROP SHARE "";
DROP SHARE IF EXISTS "";
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/embedding
# EMBEDDING
> Generate vector embeddings for text using the EMBEDDING function for semantic search.
::::warning[Preview Feature]
This is a preview feature. Preview features may be operationally incomplete and may offer limited backward compatibility.
::::
## Embedding function
The `embedding` function lets you generate vector representations (embeddings) of text directly from SQL. These embeddings capture semantic meaning, enabling powerful [semantic search](/key-tasks/ai-and-motherduck/text-search-in-motherduck/#embedding-based-search) and other natural language processing tasks.
The function uses OpenAI's models: `text-embedding-3-small` (default) with 512 dimensions or `text-embedding-3-large` with 1024 dimensions. Both models support single- and multi-row inputs, enabling batch processing.
The maximum input size is limited to 2048 characters - larger inputs will be truncated.
Consumption is measured in [AI Units](/about-motherduck/billing/pricing#ai-function-pricing). One AI Unit equates to approximately:
- 60,000 embedding rows with `text-embedding-3-small`
- 12,000 embedding rows with `text-embedding-3-large`
These estimates assume an input size of 1,000 characters.
### Syntax
```sql
SELECT embedding(my_text_column) FROM my_table; -- returns FLOAT[512] column
```
### Parameters
The `embedding` function accepts parameters using named parameter syntax with the `:=` operator.
| **Parameter** | **Required** | **Description** |
|--------------------|--------------|--------------------------------------------------------------------------------------------------------------------------|
| `text_input` | Yes | The text to be converted into an embedding vector |
| `model` | No | Model type, either `'text-embedding-3-small'` (default) or `'text-embedding-3-large'` |
### Return types
The `embedding` function returns different array sizes depending on the model used:
- With `text-embedding-3-small`: Returns `FLOAT[512]`
- With `text-embedding-3-large`: Returns `FLOAT[1024]`
### Examples
#### Basic embedding generation
```sql
-- Generate embeddings using the default model (text-embedding-3-small)
SELECT embedding('This is a sample text') AS text_embedding;
-- Generate embeddings using the larger model for higher dimensionality
SELECT embedding('This is a sample text', model:='text-embedding-3-large') AS text_embedding;
```
#### Batch processing
```sql
-- Generate embeddings for multiple rows at once
SELECT
title,
embedding(overview) AS overview_embeddings
FROM kaggle.movies
LIMIT 10;
```
### Use cases
#### Creating an embedding database
This example uses the sample movies dataset from [MotherDuck's sample data database](/getting-started/sample-data-queries/datasets).
```sql
--- Create a new table with embeddings for the first 100 overview entries
CREATE TABLE my_db.movies AS
SELECT title,
overview,
embedding(overview) AS overview_embeddings
FROM kaggle.movies
LIMIT 100;
```
If write access to the source table is available, the embedding column can also be added in place:
```sql
--- Update the existing table to add new column for embeddings
ALTER TABLE my_db.movies ADD COLUMN overview_embeddings FLOAT[512];
--- Populate the column with embeddings
UPDATE my_db.movies
SET overview_embeddings = embedding(overview);
```
The movies table now contains a new column `overview_embeddings` with vector representations of each movie description:
```sql
SELECT * FROM my_db.movies;
```
| **title** | **overview** | **overview_embeddings** |
| ----------------- | ----------------- |----------------------------------------------------|
| 'Toy Story 3' | 'Led by Woody, Andy's toys live happily in [...]' | [0.023089351132512093, -0.012809964828193188, ...] |
| 'Jumanji' | 'When siblings Judy and Peter discover an [...]' | [-0.005538413766771555, 0.0799209326505661, ...] |
| ... | ... | ... |
#### Semantic similarity search
The `array_cosine_similarity` function can be used to compute similarities between embeddings.
This enables semantic search to retrieve entries that are conceptually / semantically similar to a query, even if they don't share the same keywords.
```sql
-- Find movies similar to "Toy Story" based on semantic similarity
SELECT
title,
overview,
array_cosine_similarity(
embedding('Led by Woody, Andy''s toys live happily [...]'),
overview_embeddings
) AS similarity
FROM kaggle.movies
WHERE title != 'Toy Story'
ORDER BY similarity DESC
LIMIT 5;
```
| **title** | **overview** | **similarity** |
|-----------------|-----------------|-----------------|
|'Toy Story 3'|'Woody, Buzz, and the rest of Andy's toys haven't [...]'|0.7372807860374451|
|'Toy Story 2'|'Andy heads off to Cowboy Camp, leaving his toys [...]'|0.7222828269004822|
|... |... |... |
For advanced similarity search techniques including document chunking, hybrid search, and performance optimization, see the [Embedding-Based Search](/key-tasks/ai-and-motherduck/text-search-in-motherduck/#embedding-based-search) section in the Text Search guide.
#### Building a recommendation system
Embeddings can be used to build content-based recommendation systems:
```sql
-- Create a macro to recommend similar movies
CREATE OR REPLACE MACRO recommend_similar_movies(movie_title) AS TABLE (
WITH target_embedding AS (
SELECT embedding(overview) AS emb
FROM sample_data.kaggle.movies
WHERE title = movie_title
LIMIT 1
)
SELECT
m.title AS recommended_title,
m.overview,
array_cosine_similarity(t.emb, m.overview_embeddings) AS similarity
FROM
sample_data.kaggle.movies m,
target_embedding t
WHERE
m.title != movie_title
ORDER BY
similarity DESC
LIMIT 5
);
-- Use the macro to get recommendations
SELECT * FROM recommend_similar_movies('The Matrix');
```
#### Retrieval-augmented generation (RAG)
Embeddings are a key component in building [RAG](https://motherduck.com/blog/search-using-duckdb-part-2/) systems,
which can be combined with the [[`prompt` function]](/sql-reference/motherduck-sql-reference/ai-functions/prompt/#retrieval-augmented-generation-rag) for powerful question-answering capabilities:
```sql
-- Create a reusable macro for question answering
CREATE OR REPLACE TEMP MACRO ask_question(question_text) AS TABLE (
SELECT question_text AS question, prompt(
'User asks the following question:\n' || question_text || '\n\n' ||
'Here is some additional information:\n' ||
STRING_AGG('Title: ' || title || '; Description: ' || overview, '\n') || '\n' ||
'Please answer the question based only on the additional information provided.',
model := 'gpt-4o'
) AS response
FROM (
SELECT title, overview
FROM sample_data.kaggle.movies
ORDER BY array_cosine_similarity(overview_embeddings, embedding(question_text)) DESC
LIMIT 3
)
);
-- Use the macro to answer questions
SELECT question, response
FROM ask_question('Can you recommend some good sci-fi movies about AI?');
```
### Security considerations
When passing free-text arguments from external sources to the embedding function (e.g., user questions in a RAG application), always use prepared statements to prevent SQL injection.
```python
# Using prepared statements in Python
user_query = "Led by Woody, Andy's toys live happily [...]"
con.execute("""
SELECT title, overview, array_cosine_similarity(embedding(?), overview_embeddings) as similarity
FROM kaggle.movies
ORDER BY similarity DESC
LIMIT 5""", [user_query])
```
### Error handling
When usage limits have been reached or an unexpected error occurs while computing embeddings,
the function will not fail the entire query but will return `NULL` values for the affected rows.
To check if all embeddings were computed successfully:
```sql
-- Check for NULL values in embedding column
SELECT count(*)
FROM my_db.movies
WHERE overview_embeddings IS NULL AND overview IS NOT NULL;
```
Missing values can be filled in with a separate query:
```sql
-- Fill in missing embedding values
UPDATE my_db.movies
SET overview_embeddings = embedding(overview)
WHERE overview_embeddings IS NULL AND overview IS NOT NULL;
```
### Performance considerations
- **Batch Processing**: when processing multiple rows, consider using `LIMIT` to control the number of API calls.
- **Model Selection**: use `text-embedding-3-small` for faster, less expensive embeddings when the highest precision isn't critical.
- **Caching**: results are not cached between queries, so consider storing embeddings in tables for repeated use.
- **Dimensionality**: higher dimensions (using `text-embedding-3-large`) provide more precise semantic representation but require more storage and computation time.
### Notes
These capabilities are provided by MotherDuck's integration with Azure OpenAI and inputs to the embedding function will be processed by Azure OpenAI.
For availability and usage limits, see [MotherDuck's Pricing Model](/about-motherduck/billing/pricing#motherduck-pricing-model).
Usage limits are in place to safeguard your spend, not because of throughput limitations. MotherDuck has the capacity to handle high-volume embedding workloads and is always open to working alongside customers to support any type of workload and model requirements.
If you need higher usage limits or have specific requirements, please see our [support page](/troubleshooting/support/).
#### Regional processing
Requests are processed based on the region of the MotherDuck organization according to the table below. Functions that are not available within the region (no checkmark) will be processed with global compute resources.
| Function | Global | Europe | US West |
|----------|--------|--------|---------|
| `EMBEDDING` (`text-embedding-3-small`) | ✓ | ✓ | ✓ |
| `EMBEDDING` (`text-embedding-3-large`) | ✓ | ✓ | ✓ |
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/explain
# EXPLAIN
> Display the physical query plan without executing the query.
The `EXPLAIN` statement shows the physical query plan that will be executed. It displays a tree of operators that will run in sequence to produce the query results. The query optimizer transforms this plan to improve performance.
On MotherDuck queries, `(L)` indicates queries that are executed **locally** and `(R)` indicates the queries are executed **remotely**.
For more detailed query analysis, review the documentation on [`EXPLAIN ANALYZE`](/sql-reference/motherduck-sql-reference/explain-analyze/).
:::note
The [query profiling guide on DuckDB](https://duckdb.org/docs/stable/dev/profiling.html) is a great place to start with this topic.
:::
## Syntax
This SQL query shows the physical query plan for an example query.
```sql
EXPLAIN
```
## Example Usage
```sql
EXPLAIN
SELECT 1 AS col
UNION ALL
SELECT 2
```
This will return the physical plan, which executes entirely locally.
```text
Physical Plan
┌───────────────────────────┐
│ UNION (L) ├──────────────┐
└─────────────┬─────────────┘ │
┌─────────────┴─────────────┐┌─────────────┴─────────────┐
│ PROJECTION (L) ││ PROJECTION (L) │
│ ──────────────────── ││ ──────────────────── │
│ col ││ 2 │
│ ││ │
│ ~1 Rows ││ ~1 Rows │
└─────────────┬─────────────┘└─────────────┬─────────────┘
┌─────────────┴─────────────┐┌─────────────┴─────────────┐
│ DUMMY_SCAN (L) ││ DUMMY_SCAN (L) │
└───────────────────────────┘└───────────────────────────┘
```
### `EXPLAIN` in MotherDuck compared to DuckDB
The MotherDuck `EXPLAIN` plan is similar to the DuckDB `EXPLAIN` plan, with two main differences:
* Operations that run locally are marked as (L), and operations running remotely on the MotherDuck service are marked as (R).
* The MotherDuck DuckDB extension adds four new type of custom operators, to exchange data between your local DuckDB and the MotherDuck service:
* The **`UploadSink`** operator runs locally and sends data from your local DuckDB to the remote MotherDuck service.
* The **`UploadSource`** operator runs remotely in the DuckDB on the MotherDuck side and consumes the uploaded data.
* The **`DownloadSink`** operator runs remotely on the MotherDuck side and prepares the data to be downloaded by the local DuckDB.
* The **`DownloadSource`** operator runs in your local DuckDB, fetching the data from the MotherDuck service made available via the remote DownloadSink.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/explain-analyze
# EXPLAIN ANALYZE
> Execute a query and display performance metrics for each operator.
`EXPLAIN ANALYZE` displays and executes the query plan, showing performance metrics and cardinality information for each operator.
:::note
The [query profiling guide on DuckDB](https://duckdb.org/docs/stable/dev/profiling.html) is a great place to start with this topic.
:::
## Syntax
This SQL query shows the physical query plan for an example query.
```sql
EXPLAIN ANALYZE
```
## Example Usage
```sql
EXPLAIN ANALYZE
SELECT 1 AS col
UNION ALL
FROM (SELECT vendorId
FROM sample_data.nyc.taxi LIMIT 1);
```
This will return the analyzed plan, which shows which elements of the query are running locally and some are running remotely on MotherDuck.
```text
┌─────────────────────────────────────┐
│┌───────────────────────────────────┐│
││ Query Profiling Information ││
│└───────────────────────────────────┘│
└─────────────────────────────────────┘
EXPLAIN ANALYZE SELECT 1 AS col UNION ALL FROM (SELECT vendorId FROM sample_data.nyc.taxi LIMIT 1)
-- MD_SQL_METADATA: {"source":"hatchling","purpose":"runCellStatement","containsUserSQL":true}
┌────────────────────────────────────────────────┐
│┌──────────────────────────────────────────────┐│
││ Total Time: 0.0955s ││
│└──────────────────────────────────────────────┘│
└────────────────────────────────────────────────┘
┌───────────────────────────┐
│ QUERY │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ EXTENSION │
│ ──────────────────── │
│ md_type: │
│ HYBRID_STATS_COLLECTOR │
│ │
│ 0 Rows │
│ (0.00s) │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ EXPLAIN_ANALYZE │
│ ──────────────────── │
│ 0 Rows │
│ (0.00s) │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ EXTENSION │
│ ──────────────────── │
│ md_type: │
│ HYBRID_RUNNER │
│ │
│ 0 Rows │
│ (0.00s) │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ EXTENSION │
│ ──────────────────── │
│ md_type: │
│ DOWNLOAD_SOURCE │
│ │
│ bridge_id: 1 │
│ │
│ 2 Rows │
│ (0.00s) │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ EXTENSION │
│ ──────────────────── │
│ md_type: │
│ DOWNLOAD_SINK │
│ │
│ bridge_id: 1 │
│ parallel: false │
│ │
│ 0 Rows │
│ (0.00s) │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ UNION │
│ ──────────────────── │
│ 2 Rows ├──────────────┐
│ (0.00s) │ │
└─────────────┬─────────────┘ │
┌─────────────┴─────────────┐┌─────────────┴─────────────┐
│ PROJECTION ││ STREAMING_LIMIT │
│ ──────────────────── ││ ──────────────────── │
│ col ││ │
│ ││ │
│ 1 Rows ││ 1 Rows │
│ (0.00s) ││ (0.00s) │
└─────────────┬─────────────┘└─────────────┬─────────────┘
┌─────────────┴─────────────┐┌─────────────┴─────────────┐
│ DUMMY_SCAN ││ TABLE_SCAN │
│ ──────────────────── ││ ──────────────────── │
│ ││ Table: taxi │
│ ││ Type: Sequential Scan │
│ ││ Projections: VendorID │
│ ││ │
│ 1 Rows ││ 4096 Rows │
│ (0.00s) ││ (0.00s) │
└───────────────────────────┘└───────────────────────────┘
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/grant-access
# GRANT READ ON SHARE
> Give users access to a restricted share.
For restricted shares, use the `GRANT` command to explicitly give users access to the share. After a user has been `GRANT`-ed access they will still need to run an `ATTACH` command to be able to run queries against the shared database. Only the owner of the share can use the `GRANT` command to give access to others.
## Syntax
```sql
GRANT READ ON SHARE TO [, , ];
```
## Example usage
```sql
-- Owner: gives the user with username 'duck' access to the share 'birds'
GRANT READ ON SHARE birds TO duck;
-- Owner: gives the users with usernames 'usr1' and 'usr2' access to the share 'taxis'
GRANT READ ON SHARE taxis TO user_1, user_2;
```
If a username contains special characters, such as '@', it must be enclosed in double quotes (`"`).
## Complete workflow example
Below is a complete workflow showing how to share a database with a restricted audience and how recipients can access it. We will first create a share and grant access to specific users. Then, we will show how recipients can attach and query the shared database. For more information on each step, refer to the [CREATE SHARE](create-share.md), [LIST SHARES](list-shares.md), and [ATTACH](attach.md) documentation.
### 1. Owner creates a share and grants access
```sql
-- Owner: create a restricted share of database 'analytics'
-- Using CREATE OR REPLACE allows updating the share if it already exists.
-- ACCESS RESTRICTED is required to use GRANT/REVOKE.
CREATE OR REPLACE SHARE analytics_share FROM analytics (ACCESS RESTRICTED);
-- Owner: Grant access to specific users.
-- If a username contains special characters like '@', enclose it in double quotes.
GRANT READ ON SHARE analytics_share TO user_1, "user_2@example-com";
-- Owner retrieves the share URL to provide to recipients.
-- The URL uniquely identifies the share.
LIST SHARES;
-- Example output contains URL like: md:_share/analytics/0a9a026ec5a55946a9de39851087ed81
-- Owner shares the full URL (e.g., 'md:_share/analytics/0a9a026ec5a55946a9de39851087ed81') with the granted users.
```
### 2. Recipient attaches and queries the shared database
```sql
-- Recipient: attach the shared database using the full URL provided by the owner.
-- Using the full URL prevents naming conflicts.
ATTACH 'md:_share/analytics/0a9a026ec5a55946a9de39851087ed81' AS analytics_data;
-- Recipient: switch to the attached database
USE analytics_data;
-- Recipient: query the shared database
SELECT * FROM customer_metrics LIMIT 10;
```
When the share is attached, it creates a read-only reference to the shared database that doesn't consume additional storage for the recipient. Recipients can query the data but cannot modify it.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/list-secrets
# LIST SECRETS
> List all secrets stored in memory and MotherDuck.
Secrets can be listed in the same way as in DuckDB by using the table function `duckdb_secrets()`.
# Syntax
```sql
FROM duckdb_secrets();
```
| name | type | provider | persistent | storage | scope | secret_string |
|-----------------|-------|------------------|------------|------------|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| __default_azure | azure | credential_chain | false | memory | [azure://, az://] | name=__default_azure;type=azure;provider=credential_chain;serializable=true;scope=azure://,az://;account_name=some-account |
| __default_s3 | s3 | credential_chain | false | memory | [s3://, s3n://, s3a://] | name=__default_s3;type=s3;provider=credential_chain;serializable=true;scope=s3://,s3n://,s3a://;endpoint=s3.amazonaws.com;key_id=my_key;region=us-east-1;secret=redacted;session_token=redacted |
| __default_r2 | r2 | config | true | motherduck | [r2://] | name=__default_r2;type=r2;provider=config;serializable=true;scope=r2://;endpoint=my_account.r2.cloudflarestorage.com;key_id=my_key;region=us-east-1;s3_url_compatibility_mode=0;secret=redacted;session_token=redacted;url_style=path;use_ssl=1 |
| __default_gcs | gcs | config | true | motherduck | [gcs://, gs://] | name=__default_gcs;type=gcs;provider=config;serializable=true;scope=gcs://,gs://;endpoint=storage.googleapis.com;key_id=my_key;region=us-east-1;s3_url_compatibility_mode=0;secret=redacted;session_token=redacted;url_style=path;use_ssl=1 |
:::note
DuckDB allows you to specify `redact` when listing secrets (it's set to `true` by default). However, MotherDuck secrets are always redacted for security reasons despite the flag.
:::
# Example Usage
To inspect specific field(s) in `secret_string`:
```sql
select
name, storage,
list_filter(split(secret_string,';'), x -> starts_with(x, 'region'))[1]
from duckdb_secrets(redact=false) where name='__default_s3';
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/list-shares
# LIST SHARES
> List all shares created by the current user.
The `LIST SHARES` statement lists all shares created by the current user.
It provides the same information as querying the [`MD_INFORMATION_SCHEMA.OWNED_SHARES`](/sql-reference/motherduck-sql-reference/md_information_schema/owned_shares/) view. You can also use the table function `md_list_database_shares()` for a subset of this information.
:::tip
To see shares that have been shared *with* you (by others), query the [`MD_INFORMATION_SCHEMA.SHARED_WITH_ME`](/sql-reference/motherduck-sql-reference/md_information_schema/shared_with_me/) view instead.
:::
## Syntax
```sql
-- Using DDL (lists all owned shares with details)
LIST SHARES;
-- Equivalent to querying the information schema view
SELECT * FROM MD_INFORMATION_SCHEMA.OWNED_SHARES;
-- Using table function (returns a subset of columns)
SELECT name, url, source_db_name FROM md_list_database_shares();
```
## Output
The `LIST SHARES` statement and `SELECT * FROM MD_INFORMATION_SCHEMA.OWNED_SHARES` return a table with the following columns:
| Column Name | Data Type | Value |
| ---------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| NAME | STRING | The name of the share |
| URL | STRING | The `share_url` which can be used to attach the share |
| SOURCE_DB_NAME | STRING | The name of the database where this share was created from |
| SOURCE_DB_UUID | UUID | UUID of the database where this share was created from |
| ACCESS | STRING | Whether anyone (`UNRESTRICTED`) within the same cloud region or only organization members (`ORGANIZATION`) can attach to the share by its `share_url`. RESTRICTED shares are hidden from the list. |
| VISIBILITY | STRING | Whether the share is `DISCOVERABLE` or `HIDDEN` |
| UPDATE | STRING | The share's update mode (`MANUAL` vs. `AUTOMATIC`) |
| CREATED_TS | TIMESTAMP | The share's creation time |
:::note
Shares are **region-scoped** based on your Organization's cloud region. Each MotherDuck Organization is scoped to a single cloud region that must be chosen at Org creation when signing up.
MotherDuck is available on AWS in three regions:
- **US East (N. Virginia):** `us-east-1`
- **US West (Oregon):** `us-west-2`
- **Europe (Frankfurt):** `eu-central-1`
:::
---
Source: https://motherduck.com/docs/sql-reference/mcp/list-databases
# list_databases
> List all databases in your MotherDuck account
List all databases in your MotherDuck account with their names and types.
## Description
The `list_databases` tool returns all databases accessible to your MotherDuck account, including both owned databases and attached shared databases. This is useful for discovering what data is available before running queries.
## Input Parameters
This tool takes no input parameters.
## Output Schema
```json
{
"success": boolean,
"databases": [ // List of databases (on success)
{
"alias": string, // Database name/alias
"is_attached": boolean, // Whether the database is currently attached
"type": string // Database type (e.g., "motherduck", "memory")
}
],
"error": string // Error message (on failure)
}
```
## Example Usage
**List available databases:**
```text
What databases do I have access to?
```
The AI assistant will call the tool with no parameters.
## Success Response Example
```json
{
"success": true,
"databases": [
{
"alias": "my_db",
"is_attached": true,
"type": "motherduck"
},
{
"alias": "analytics",
"is_attached": true,
"type": "motherduck"
},
{
"alias": "shared_sales_data",
"is_attached": true,
"type": "motherduck"
}
]
}
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/connection-management/monitor-connections
# MD_ACTIVE_SERVER_CONNECTIONS
> View active connections and running queries in MotherDuck using md_active_connections.
:::info
This is a preview feature. Preview features may be operationally incomplete and may offer limited backward compatibility.
:::
# MD_ACTIVE_SERVER_CONNECTIONS
:::tip
You can also monitor running queries in the MotherDuck UI under **Settings** → **Running Queries**. See [Running Queries](/getting-started/interfaces/motherduck-quick-tour/#running-queries) for details.
For an org-wide view of running and completed queries, see the [`RECENT_QUERIES`](/sql-reference/motherduck-sql-reference/md_information_schema/recent_queries/) view (for admins on the Business plan).
:::
The `md_active_server_connections` table function can be used to list all server-side connections that have active transactions.
## Syntax
```sql
FROM md_active_server_connections();
```
This returns a list of active server connections, with the following information:
| **column_name** | **column_type** | **description** |
|-------------------------------------|-----------------|----------------------------------------------------------------------------------|
| client_duckdb_id | UUID | Unique identifier for the client DuckDB instance that initiated the connection |
| client_user_agent | VARCHAR | User agent for the client |
| client_duckdb_version | USMALLINT[3] | DuckDB version from the client |
| client_connection_id | UUID | Unique identifier for the client DuckDB connection that initiated the connection |
| client_transaction_id | UBIGINT | Identifier for the transaction within the current connection |
| server_transaction_stage | VARCHAR | Stage the server-side transaction is in |
| server_transaction_elapsed_time | INTERVAL | How long the server-side transaction has been in the current stage |
| client_query_id | UBIGINT | Identifier for the query within the current transaction |
| client_query | VARCHAR | Query string (possibly truncated) |
| server_query_elapsed_time | INTERVAL | How long the query has been running on the server-side |
| server_query_execution_elapsed_time | INTERVAL | How long the connection has been interrupted |
| server_query_progress | DOUBLE | Progress information (value between 0.0 and 1.0) |
| server_interrupt_elapsed_time | INTERVAL | How long the connection has been interrupted |
| server_interrupt_reason | VARCHAR | Why the connection was interrupted |
| query_total_upload_size | UBIGINT | Data uploaded in Bytes |
| query_total_download_size | UBIGINT | Data downloaded in Bytes |
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-create-flight
# MD_CREATE_FLIGHT
> Create a new Flight in your MotherDuck account.
Creates a new [Flight](/concepts/flights) and returns its summary. The initial version is captured from `source_code`, `requirements_txt`, `config`, `access_token_name`, and `flight_secret_names`.
## Syntax
```sql
SELECT * FROM MD_CREATE_FLIGHT(
name := 'my_flight',
access_token_name := '',
source_code := '',
schedule_cron := '0 * * * *',
requirements_txt := 'duckdb==1.5.2',
config := MAP {'KEY': 'value'},
flight_secret_names := ['secret_name']
);
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `name` | `VARCHAR` | Yes | Human-readable Flight name. Must be non-empty. |
| `access_token_name` | `VARCHAR` | Yes | Label of a MotherDuck access token. The token value is injected into the Flight as `MOTHERDUCK_TOKEN`. List labels with `SELECT * FROM md_access_tokens();`. |
| `source_code` | `VARCHAR` | Yes | Python source for the Flight. A single-file program with a top-level `def main(): ...`. |
| `schedule_cron` | `VARCHAR` | No | 5-field cron expression in UTC. Omit for an on-demand-only Flight. |
| `requirements_txt` | `VARCHAR` | No | Contents of a `requirements.txt`, one pinned package per line. |
| `config` | `MAP(VARCHAR, VARCHAR)` | No | Non-secret key/value pairs surfaced to the Flight as environment variables. |
| `flight_secret_names` | `LIST(VARCHAR)` | No | List of MotherDuck-stored secret names. End-to-end secret delivery is still in development. |
## Return columns
| Column | Type | Description |
|---|---|---|
| `flight_id` | `UUID` | Unique identifier of the created Flight. |
| `flight_name` | `VARCHAR` | The Flight name. |
| `schedule_cron` | `VARCHAR` | The cron expression, or `NULL` for on-demand. |
| `status` | `VARCHAR` | Schedule status (for example, `JOB_STATUS_ACTIVE`). |
| `current_version` | `INTEGER` | Always `1` for a newly created Flight. |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | Creation timestamp. |
| `updated_at` | `TIMESTAMP WITH TIME ZONE` | Last update timestamp. |
## Examples
Minimal Flight, no schedule:
```sql
SELECT flight_id
FROM MD_CREATE_FLIGHT(
name := 'heartbeat',
access_token_name := 'analytics_token',
source_code := 'def main(): print("hello")'
);
```
Scheduled Flight with config:
```sql
SELECT flight_id, current_version
FROM MD_CREATE_FLIGHT(
name := 'hourly_metrics',
access_token_name := 'analytics_token',
source_code := $$
import duckdb
def main():
con = duckdb.connect("md:")
con.execute("INSERT INTO analytics.hourly_counts SELECT now(), COUNT(*) FROM events")
$$,
requirements_txt := 'duckdb==1.5.2',
schedule_cron := '0 * * * *',
config := MAP {'REGION': 'eu-central-1'}
);
```
## Related
- [`MD_UPDATE_FLIGHT`](../md-update-flight) — Modify a Flight's content or metadata.
- [`MD_RUN_FLIGHT`](../md-run-flight) — Trigger an on-demand run.
- [`MD_DELETE_FLIGHT`](../md-delete-flight) — Delete a Flight.
- [`create_flight` MCP tool](/sql-reference/mcp/) — AI-agent equivalent.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-list-dives
# MD_LIST_DIVES
> List all Dives in your MotherDuck account with pagination support.
Lists all [Dives](/key-tasks/ai-and-motherduck/dives) in your MotherDuck account. Returns metadata for each Dive without the component content.
## Syntax
```sql
SELECT * FROM MD_LIST_DIVES();
SELECT * FROM MD_LIST_DIVES("limit" =100, "offset" =0);
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `limit` | `UINTEGER` | No | Maximum number of Dives to return |
| `offset` | `UINTEGER` | No | Number of Dives to skip |
| `include_org_shares` | `BOOLEAN` | No | Include Dives shared with your organization. Defaults to `false`. |
:::tip
`limit` and `offset` are reserved SQL keywords and must be double-quoted when used as named parameters.
:::
## Return columns
| Column | Type | Description |
|--------|------|-------------|
| `id` | `UUID` | Unique identifier of the Dive |
| `title` | `VARCHAR` | Dive title |
| `description` | `VARCHAR` | Dive description |
| `owner_id` | `UUID` | UUID of the Dive owner |
| `current_version` | `INTEGER` | Latest version number (1-based) |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When the Dive was created |
| `updated_at` | `TIMESTAMP WITH TIME ZONE` | When the Dive was last updated |
| `owner_name` | `VARCHAR` | Name of the Dive owner |
## Examples
List all Dives:
```sql
SELECT * FROM MD_LIST_DIVES();
```
List the 10 Dives with the latest updates:
```sql
SELECT id, title, owner_name, updated_at
FROM MD_LIST_DIVES()
ORDER BY updated_at DESC
LIMIT 10;
```
Paginate through Dives:
```sql
SELECT * FROM MD_LIST_DIVES("limit" =20, "offset" =0); -- first page
SELECT * FROM MD_LIST_DIVES("limit" =20, "offset" =20); -- second page
```
## Related
- [`MD_GET_DIVE`](../md-get-dive) — Read a Dive including its content
- [`MD_LIST_DIVE_VERSIONS`](../md-list-dive-versions) — List version history for a Dive
- [`list_dives` MCP tool](/sql-reference/mcp/list-dives) — AI assistant equivalent
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-run-parameter
# MD_RUN parameter
> Control whether table functions run locally or remotely.
For certain DuckDB **Table Functions**, MotherDuck provides an additional parameter, `MD_RUN`, that gives explicit control over where the query is executed.
This parameter is available to the following functions:
- `read_csv()`
- `read_csv_auto()`
- `read_json()`
- `read_json_auto()`
- `read_parquet()` and its alias `parquet_scan()`
To leverage the `MD_RUN` parameter, you can choose:
- `MD_RUN=LOCAL` executes the function in your local DuckDB environment.
- `MD_RUN=REMOTE` executes the function in MotherDuck-hosted DuckDB runtimes in the cloud.
- `MD_RUN=AUTO` executes remotely all `s3://`, `http://`, `https://`, `s3a://`, `s3n://`, `gcs://`, `gs://`, `r2://`, `azure://`, `az://`, `abfss://`, and `hf://` requests, except those to `localhost`/`127.0.0.1`. This is the default option.
The following is an example of using this parameter to execute the function remotely:
```sql
SELECT *
FROM read_csv(
'https://raw.githubusercontent.com/duckdb/duckdb-web/main/data/weather.csv',
MD_RUN = REMOTE
);
```
In this example, `MD_RUN=REMOTE` is redundant because omitting it implies `MD_RUN=AUTO`, and given that this is a non-local `https://` resource, MotherDuck will automatically choose remote execution already.
You can force local execution with `MD_RUN=LOCAL`.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/print-md-token
# PRINT_MD_TOKEN pragma
> Retrieve your MotherDuck authentication token.
You can retrieve your MotherDuck authentication token using the `PRINT_MD_TOKEN` pragma.
In CLI or Python, to avoid having to re-authenticate every time, you can store your token as an environment variable; for example, by running `export motherduck_token='xxxx'` in the terminal. Be sure to replace 'xxxx' with your own token!
# Syntax
```sql
PRAGMA PRINT_MD_TOKEN;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/prompt
# PROMPT
> Generate AI responses directly in SQL with the PROMPT function.
::::warning[Preview Feature]
This is a preview feature. Preview features may be operationally incomplete and may offer limited backward compatibility.
::::
## Prompt function
The `prompt` function sends text to a Large Language Model (LLM) from SQL and returns the model's response. Use it to generate free-form text, extract typed values, or produce structured data.
The function supports OpenAI's `gpt-5` series (`gpt-5`, `gpt-5-mini`, `gpt-5-nano`), `gpt-4o-mini` (default), `gpt-4o`, and the `gpt-4.1` series. All models support single-row prompts and multi-row queries for batch processing.
The `prompt` function runs once per row in the result set. A query like `SELECT prompt('Write a joke') FROM range(0, 10000)` calls the model 10,000 times, even though the prompt text looks like a single call. Cost scales with the number of rows the query evaluates.
Consumption is measured in [AI Units](/about-motherduck/billing/pricing#ai-function-pricing). As a rough guide, one AI Unit covers approximately the following number of rows per model:
- 480 rows with `gpt-4o`
- 8,000 rows with `gpt-4o-mini`
- 600 rows with `gpt-4.1`
- 3,000 rows with `gpt-4.1-mini`
- 12,000 rows with `gpt-4.1-nano`
- 720 rows with `gpt-5`
- 3,600 rows with `gpt-5-mini`
- 18,000 rows with `gpt-5-nano`
These estimates assume about 1,000 input characters and 250 output characters per row. Actual cost depends on token usage, so longer prompts or responses consume more AI Units per row.
## Syntax
```sql
SELECT prompt('Write a poem about ducks'); -- returns a single-cell result with the response
```
### Parameters
| **Parameter** | **Required** | **Description** |
|--------------------|--------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `prompt_text` | Yes | The text input to send to the model |
| `model` | No | Model type: `'gpt-5'`, `'gpt-5-mini'`, `'gpt-5-nano'`, `'gpt-4o-mini'` (default), `'gpt-4o'`, `'gpt-4.1'`, `'gpt-4.1-mini'`, or `'gpt-4.1-nano'` |
| `temperature` | No | Model temperature value between `0` and `1`, default: `0.1`. Lower values produce more deterministic outputs. **Not supported with GPT-5 models** (use `reasoning_effort` instead). |
| `reasoning_effort` | No | Controls reasoning depth for GPT-5 models only. Valid values: `'minimal'` (default), `'low'`, `'medium'`, `'high'`. Higher effort may improve accuracy for complex tasks. **Only available for GPT-5 series models**. |
| `return_type` | No | Specifies the exact SQL type to return (e.g., `'INTEGER'`, `'BOOLEAN'`, `'DATE'`, `'VARCHAR[]'`, `'STRUCT(name VARCHAR, age INTEGER)'`). Supports most DuckDB types including primitives, arrays, structs, and enums. Mutually exclusive with `struct` and `json_schema`. |
| `struct` | No | Output schema as struct, e.g. `{summary: 'VARCHAR', persons: 'VARCHAR[]'}`. Will result in `STRUCT` output. Mutually exclusive with `return_type` and `json_schema`. |
| `struct_descr` | No | Descriptions for struct fields that will be added to the model's context, e.g. `{summary: 'a 1 sentence summary of the text', persons: 'an array of all persons mentioned in the text'}` |
| `json_schema` | No | A JSON schema that adheres to [OpenAI's structured output guide](https://developers.openai.com/api/docs/guides/structured-outputs). Provides more flexibility than the struct/struct_descr parameters. Will result in `JSON` output. Mutually exclusive with `return_type` and `struct`. |
**Note**: The `return_type` and `struct` parameters support enum types for classification tasks. Define enum types first using `CREATE TYPE`, then reference them in the struct schema (e.g., `sentiment: 'sentiment_enum'` or `categories: 'category_enum[]'` for arrays).
### Return types
The `prompt` function can return different data types depending on the parameters used:
- Without structure parameters: Returns `VARCHAR`
- With `return_type` parameter: Returns the exact SQL type specified (e.g., `INTEGER`, `BOOLEAN`, `DATE`, `VARCHAR[]`, `STRUCT(...)`)
- With `struct` parameter: Returns a `STRUCT` with the specified schema
- With `json_schema` parameter: Returns `JSON`
**Note**: The `return_type`, `struct`, and `json_schema` parameters are mutually exclusive. Use only one at a time.
## Example usage
### Basic text generation
```sql
-- Call gpt-4o-mini (default) to generate text
SELECT prompt('Write a poem about ducks') AS response;
-- Call gpt-4o with higher temperature for more creative outputs
SELECT prompt('Write a poem about ducks', model:='gpt-4o', temperature:=1) AS response;
```
### Structured output with struct
```sql
-- Extract structured information from text using struct parameter
SELECT prompt('My zoo visit was amazing, I saw elephants, tigers, and penguins. The staff was friendly.',
struct:={summary: 'VARCHAR', favourite_animals:'VARCHAR[]', star_rating:'INTEGER'},
struct_descr:={star_rating: 'visit rating on a scale from 1 (bad) to 5 (very good)'}) AS zoo_review;
```
This returns a `STRUCT` value that can be accessed with dot notation:
```sql
SELECT
zoo_review.summary,
zoo_review.favourite_animals,
zoo_review.star_rating
FROM (
SELECT prompt('My zoo visit was amazing, I saw elephants, tigers, and penguins. The staff was friendly.',
struct:={summary: 'VARCHAR', favourite_animals:'VARCHAR[]', star_rating:'INTEGER'},
struct_descr:={star_rating: 'visit rating on a scale from 1 (bad) to 5 (very good)'}) AS zoo_review
);
```
### Structured output with JSON schema
```sql
-- Extract structured information using JSON schema
SELECT prompt('My zoo visit was amazing, I saw elephants, tigers, and penguins. The staff was friendly.',
json_schema := '{
"name": "zoo_visit_review",
"schema": {
"type": "object",
"properties": {
"summary": { "type": "string" },
"sentiment": { "type": "string", "enum": ["positive", "negative", "neutral"] },
"animals_seen": { "type": "array", "items": { "type": "string" } }
},
"required": ["summary", "sentiment", "animals_seen"],
"additionalProperties": false
},
"strict": true
}') AS json_review;
```
This returns a `JSON` value that, if saved, can be accessed using JSON extraction functions:
```sql
SELECT
json_extract_string(json_review, '$.summary') AS summary,
json_extract_string(json_review, '$.sentiment') AS sentiment,
json_extract(json_review, '$.animals_seen') AS animals_seen
FROM (
SELECT prompt('My zoo visit was amazing, I saw elephants, tigers, and penguins. The staff was friendly.',
json_schema := '{ ... }') AS json_review
);
```
### Typed output with return type
The `return_type` parameter lets you specify the exact SQL type for the model's response, providing strong typing for single-value extractions:
```sql
-- Extract an integer from text
SELECT prompt('The answer is 42', return_type := 'INTEGER') AS answer;
-- Returns: 42 (as INTEGER type)
-- Extract a boolean
SELECT prompt('Is the sky blue?', return_type := 'BOOLEAN') AS is_blue;
-- Returns: true (as BOOLEAN type)
-- Extract a date
SELECT prompt('When is January 15, 2025?', return_type := 'DATE') AS event_date;
-- Returns: 2025-01-15 (as DATE type)
-- Extract multiple structured fields
SELECT prompt(
'John is 30 years old and lives in NYC',
return_type := 'STRUCT(name VARCHAR, age INTEGER, city VARCHAR)'
) AS person_info;
-- Returns: {'name': 'John', 'age': 30, 'city': 'NYC'} (as STRUCT type)
-- Extract arrays
SELECT prompt('List the days of the week', return_type := 'VARCHAR[]') AS weekdays;
-- Returns: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
```
The `return_type` parameter supports most DuckDB types including:
- **Primitives**: `VARCHAR`, `INTEGER`, `BIGINT`, `DOUBLE`, `BOOLEAN`, `DATE`, `TIMESTAMP`, etc.
- **Arrays**: `INTEGER[]`, `VARCHAR[]`, `DOUBLE[]`, etc.
- **Structs**: `STRUCT(field1 TYPE1, field2 TYPE2, ...)`
- **Enums**: Custom enum types created with `CREATE TYPE`
### GPT-5 reasoning effort
The `reasoning_effort` parameter controls how much computational effort GPT-5 models spend on reasoning. This is only available for GPT-5 series models (`gpt-5`, `gpt-5-mini`, `gpt-5-nano`):
```sql
-- Use minimal reasoning (fastest, default)
SELECT prompt('What is 2+2?', 'gpt-5-mini',
reasoning_effort := 'minimal',
return_type := 'INTEGER') AS result;
-- Use low reasoning for simple tasks
SELECT prompt('Count the letters in "hello"', 'gpt-5-nano',
reasoning_effort := 'low',
return_type := 'INTEGER') AS letter_count;
-- Use medium reasoning for moderate complexity
SELECT prompt('Calculate 5 factorial', 'gpt-5-mini',
reasoning_effort := 'medium',
return_type := 'INTEGER') AS factorial;
-- Use high reasoning for complex tasks
SELECT prompt('Solve this logic puzzle: ...', 'gpt-5',
reasoning_effort := 'high') AS solution;
```
**Note**: The `reasoning_effort` parameter cannot be used with non-GPT-5 models, and `temperature` cannot be used with GPT-5 models. They are mutually exclusive ways of controlling model behavior.
## Use cases
### Text generation
Use the prompt function to write a poem about ducks:
```sql
--- Prompt LLM to write a poem about ducks
SELECT prompt('Write a poem about ducks') AS response;
```
| **response** |
|------------------------------------------------------------------------------------------------------------------|
| 'Beneath the whispering willow trees, Where ripples dance with wayward breeze, A symphony of quacks arise [...]' |
### Summarization
Use the prompt function to create a one-sentence summary of movie descriptions.
The example is based on the sample movies dataset from [MotherDuck's sample data database](/docs/getting-started/interfaces/client-apis/python/query-data).
```sql
--- Create a new table with summaries for the first 100 overview texts
CREATE TABLE my_db.movies AS
SELECT title,
overview,
prompt('Summarize this movie description in one sentence: ' || overview) AS summary
FROM kaggle.movies
LIMIT 100;
```
If write access to the source table is available, the summary column can also be added in place:
```sql
--- Update the existing table to add new column for summaries
ALTER TABLE my_db.movies ADD COLUMN summary VARCHAR;
--- Populate the column with summaries
UPDATE my_db.movies
SET summary = prompt('Summarize this movie description in one sentence: ' || overview);
```
The movies table now contains a new column `summary` with one-sentence summaries of the movies:
```sql
SELECT title, overview, summary
FROM my_db.movies;
```
| **title** | **overview** | **summary** |
|-----------|----------------------------------------------|------------------------------------------------------|
| Toy Story | Led by Woody, Andy's toys live happily [...] | In "Toy Story," Woody's jealousy of the new [...] |
| Jumanji | When siblings Judy and Peter discover [...] | In this thrilling adventure, siblings Judy and [...] |
| ... | ... | ... |
### Structured data extraction
Use the prompt function to extract structured data from text.
The example is based on the same sample movies dataset from [MotherDuck's sample data database](/getting-started/sample-data-queries/datasets). This time we aim to extract structured metadata from the movie's overview description.
We are interested in the main characters mentioned in the descriptions, as well as the movie's genre and a rating of how much action the movie contains, given a scale of 1 (no action) to 5 (lot of action).
For this, we make use of the `struct` and `struct_descr` parameters, which will result in structured output.
```sql
--- Update the existing table to add new column for structured metadata
ALTER TABLE my_db.movies ADD COLUMN metadata STRUCT(main_characters VARCHAR[], genre VARCHAR, action INTEGER);
--- Populate the column with structured information
UPDATE my_db.movies
SET metadata = prompt(
overview,
struct:={main_characters: 'VARCHAR[]', genre: 'VARCHAR', action: 'INTEGER'},
struct_descr:={
main_characters: 'an array of the main character names mentioned in the movie description',
genre: 'the primary genre of the movie based on the description',
action: 'rate on a scale from 1 (no action) to 5 (high action) how much action the movie contains'
}
);
```
The resulting `metadata` field is a `STRUCT` that can be accessed as follows:
```sql
SELECT title,
overview,
metadata.main_characters,
metadata.genre,
metadata.action
FROM my_db.movies;
```
| **title** | **overview** | **metadata.main_characters** | **metadata.genre** | **action** |
|-----------|----------------------------------------------|-------------------------------------------------------------------------|------------------------------|------------|
| Toy Story | Led by Woody, Andy's toys live happily [...] | ['"Woody"', '"Buzz Lightyear"', '"Andy"', '"Mr. Potato Head"', '"Rex"'] | Animation, Adventure, Comedy | 3 |
| Jumanji | When siblings Judy and Peter discover [...] | ['"Judy Shepherd"', '"Peter Shepherd"', '"Alan Parrish"'] | Adventure, Fantasy, Family | 4 |
| ... | ... | ... | ... | ... |
### Classification with enums
The `prompt` function supports enum types for classification tasks, ensuring consistent and constrained outputs. This is particularly useful for sentiment analysis, categorization, and other classification scenarios.
#### Sentiment analysis
```sql
-- Define an enum for sentiment classification
CREATE TYPE sentiment_type AS ENUM ('positive', 'negative', 'neutral');
-- Classify customer reviews
SELECT
review_text,
prompt(
'Classify the sentiment of this review: ' || review_text,
struct := {sentiment: 'sentiment_type'}
).sentiment AS sentiment
FROM (
VALUES
('The product is amazing, I love it!'),
('Terrible quality, waste of money.'),
('It works fine, nothing special.')
) AS reviews(review_text);
```
This returns:
| **review_text** | **sentiment** |
|-----------------|---------------|
| The product is amazing, I love it! | positive |
| Terrible quality, waste of money. | negative |
| It works fine, nothing special. | neutral |
#### Extracting multiple categories
Use enum arrays to extract multiple instances of the same category from text:
```sql
-- Define enums for different types of skills mentioned in text
CREATE TYPE skill_type AS ENUM ('sql', 'python', 'javascript', 'react', 'aws', 'docker', 'git');
CREATE TYPE topic_type AS ENUM ('database', 'frontend', 'backend', 'devops', 'analytics', 'security');
-- Extract skills and topics from job descriptions
SELECT
description,
prompt(
'Extract the technical skills and topics mentioned in this text: ' || description,
struct := {
skills: 'skill_type[]',
topics: 'topic_type[]'
}
) AS extracted
FROM (
VALUES
('Looking for a developer with Python and SQL experience for database analytics work'),
('Frontend role using React and JavaScript, plus Git for version control'),
('DevOps engineer needed for AWS and Docker deployment automation')
) AS jobs(description);
```
This returns arrays of enum values:
| **description** | **extracted.skills** | **extracted.topics** |
|-----------------|---------------------|---------------------|
| Looking for a developer with Python and SQL experience for database analytics work | ['python', 'sql'] | ['database', 'analytics'] |
| Frontend role using React and JavaScript, plus Git for version control | ['javascript', 'react', 'git'] | ['frontend'] |
| DevOps engineer needed for AWS and Docker deployment automation | ['aws', 'docker'] | ['devops'] |
### Retrieval-augmented generation (RAG)
The `prompt` function can be combined with [similarity search on embeddings](/sql-reference/motherduck-sql-reference/ai-functions/embedding/) to build a [RAG](https://motherduck.com/blog/search-using-duckdb-part-2/) pipeline. For advanced retrieval strategies including hybrid search, reranking, and HyDE, see the [Text Search guide](/key-tasks/ai-and-motherduck/text-search-in-motherduck/).
```sql
-- Create a reusable macro for question answering
CREATE OR REPLACE TEMP MACRO ask_question(question_text) AS TABLE (
SELECT question_text AS question, prompt(
'User asks the following question:\n' || question_text || '\n\n' ||
'Here is some additional information:\n' ||
STRING_AGG('Title: ' || title || '; Description: ' || overview, '\n') || '\n' ||
'Please answer the question based only on the additional information provided.',
model := 'gpt-4o'
) AS response
FROM (
SELECT title, overview
FROM kaggle.movies
ORDER BY array_cosine_similarity(overview_embeddings, embedding(question_text)) DESC
LIMIT 3
)
);
-- Use the macro to answer questions
SELECT question, response
FROM ask_question('Can you recommend some good sci-fi movies about AI?');
```
This will result in the following output:
| **question** | **response** |
|-----------------------------------------------------|-----------------------------------------------------------------------------------|
| Can you recommend some good sci-fi movies about AI? | Based on the information provided, here are some sci-fi movies about AI that you might enjoy: [...] |
:::warning
When passing free-text arguments from external sources to the prompt function (e.g., user questions in a RAG application), always use prepared statements to prevent SQL injection.
:::
Using prepared statements in [Python](/docs/getting-started/interfaces/client-apis/python/query-data/):
```python
# First register the macro
con.execute("""
CREATE OR REPLACE TEMP MACRO ask_question(question_text) AS TABLE (
-- Macro definition as above
);
""")
# Then use prepared statements for user input
user_query = "Can you recommend some good sci-fi movies about AI?"
result = con.execute("""
SELECT response FROM ask_question(?)
""", [user_query]).fetchall()[0]
print(result[0])
```
## Batch processing
The `prompt` function can process multiple rows in a single query:
```sql
--- Process multiple rows at once
SELECT
title,
prompt('Write a tagline for this movie: ' || overview) AS tagline
FROM kaggle.movies
LIMIT 10;
```
## Error handling
When usage limits have been reached or an unexpected error occurs while computing prompt responses,
the function returns `NULL` for the affected rows instead of failing the entire query.
To check whether all responses were computed successfully, check for `NULL` values in the resulting column.
```sql
-- Check for NULL values in response column
SELECT count(*)
FROM my_db.movies
WHERE response IS NULL AND overview IS NOT NULL;
```
Missing values can be filled in with a separate query:
```sql
-- Fill in missing prompt responses
UPDATE my_db.movies
SET response = prompt('Summarize this movie description in one sentence: ' || overview)
WHERE response IS NULL AND overview IS NOT NULL;
```
## Performance considerations
- **Batch processing**: When processing multiple rows, consider using `LIMIT` to control the number of API calls.
- **Model selection**: Use `gpt-4o-mini` for faster, less expensive responses when high accuracy isn't critical.
- **Caching**: Results are not cached between queries, so consider storing results in tables for repeated use.
## Notes
These capabilities are provided by MotherDuck's integration with Azure OpenAI. Inputs to the prompt function will be processed by Azure OpenAI.
For availability and usage limits, see [MotherDuck's Pricing Model](/about-motherduck/billing/pricing#motherduck-pricing-model).
Usage limits are in place to safeguard your spend, not because of throughput limitations. MotherDuck has the capacity to handle high-volume embedding workloads and is always open to working alongside customers to support any type of workload and model requirements.
If you need higher usage limits or have specific requirements, please see our [support page](/troubleshooting/support/).
### Regional processing
Requests are processed based on the region of the MotherDuck organization according to the table below. Functions that are not available within the region (no checkmark) will be processed with global compute resources.
| Function | Global | Europe | US West |
|----------|--------|--------|---------|
| `PROMPT` | ✓ | ✓ | ✓ |
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/query_history
# QUERY_HISTORY view
> Access detailed query history and metrics using the QUERY_HISTORY view (Business plan).
:::tip
Organization admins can also see a 24-hour summary of activity across every Duckling in the organization under **Settings** → **Duckling overview**. See [Duckling overview](/getting-started/interfaces/motherduck-quick-tour/#duckling-overview) for details.
You can monitor and cancel running queries in the MotherDuck UI under **Settings** → **Running Queries**. See [Running Queries](/getting-started/interfaces/motherduck-quick-tour/#running-queries) for details.
:::
The `MD_INFORMATION_SCHEMA.QUERY_HISTORY` view provides organization admins with a consolidated view of all queries run across their full organization. This view is available on Business plans and only to organization admins.
## Schema
When you query the `MD_INFORMATION_SCHEMA.QUERY_HISTORY` view, the query results contain one row for each query that was run in the organization. Note that the information in this view will have some delays. A more realtime view of ongoing and completed queries that have not been captured in `QUERY_HISTORY` yet is provided through the [`MD_INFORMATION_SCHEMA.RECENT_QUERIES`](recent_queries.md) view.
The `MD_INFORMATION_SCHEMA.QUERY_HISTORY` view has the following schema:
| Column Name | Data Type | Value |
|-----------------------|-------------|-----------------------------------|
| QUERY_ID | UUID | A unique ID representing the particular query run. You can retrieve this value on the client with [`MD_LAST_QUERY_ID()`](../connection-management/last-query-id.md). |
| QUERY_TEXT | STRING | Query SQL text (up to 100k chars) |
| START_TIME | TIMESTAMPTZ | Start time of the query |
| END_TIME | TIMESTAMPTZ | End time of the query |
| EXECUTION_TIME | INTERVAL | Duration where the query is actively executing |
| WAIT_TIME | INTERVAL | Duration where the query is waiting on resources to become available. For example a query needs to wait because other queries are using all available execution threads, or a query might be waiting on data to become available (in case of data upload). |
| TOTAL_ELAPSED_TIME | INTERVAL | Total duration of the query |
| ERROR_MESSAGE | STRING | Error message, if the query returned an error |
| ERROR_TYPE | STRING | Error type, if the query returned an error |
| USER_AGENT | STRING | User agent of the client |
| USER_NAME | STRING | Identifier for the MotherDuck user in their organization |
| QUERY_NR | UBIGINT | ID of the query within the transaction that ran the query. Number that just increments for each query that is run within a given transaction |
| TRANSACTION_NR | UBIGINT | ID of the transaction that contained the query. Number that just increments for each new transaction on a given connection |
| CONNECTION_ID | UUID | Unique ID for the [client DuckDB connection](../connection-management/connection-duckdb-id.md) where the query was issued |
| DUCKDB_ID | UUID | Unique ID for the [client DuckDB instance](../connection-management/connection-duckdb-id.md) where the query was issued |
| DUCKDB_VERSION | STRING | Client DuckDB version that issued the query |
| INSTANCE_TYPE | STRING | The size of Duckling that the query was run on (Pulse / Standard / Jumbo / Mega / Giga / ...) |
| QUERY_TYPE | STRING | The nature of the query (DDL / DML / QUERY / ...) |
| BYTES_UPLOADED | UBIGINT | Number of bytes uploaded from client to server (relevant for hybrid queries) |
| BYTES_DOWNLOADED | UBIGINT | Number of bytes downloaded from server to client (relevant for hybrid queries) |
| BYTES_SPILLED_TO_DISK | UBIGINT | Total number of bytes [spilled to disk](https://duckdb.org/docs/stable/guides/performance/how_to_tune_workloads.html#spilling-to-disk) for "larger than in-memory" workloads |
| DUCKLING_ID | STRING | Identifies the duckling that ran the query. It is composed of the user name and a qualifier (`rw` for read-write ducklings, or `rs.0`, `rs.1`, ... for the respective read scaling duckling) |
| SESSION_NAME | STRING | The [`session_name`](/key-tasks/authenticating-and-connecting-to-motherduck/connecting-to-motherduck/#session-names) that was supplied when connecting to MotherDuck |
The fields `START_TIME`, `END_TIME`, `TOTAL_ELAPSED_TIME`, `ERROR_MESSAGE`, and `ERROR_TYPE` are captured on the server (that is, when query starts and ends on server). In the future they will be based on client information too (taking better into account the full hybrid context).
## Example usage
```sql
from MD_INFORMATION_SCHEMA.QUERY_HISTORY limit 10;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/recent_queries
# RECENT_QUERIES view
> View recent query activity across your organization using the RECENT_QUERIES view (Business plan).
:::tip
You can also monitor and cancel running queries in the MotherDuck UI under **Settings** → **Running Queries**. See [Running Queries](/getting-started/interfaces/motherduck-quick-tour/#running-queries) for details.
To monitor or interrupt individual connections, see [`md_active_server_connections()`](/sql-reference/motherduck-sql-reference/connection-management/monitor-connections/) and [`md_interrupt_server_connection()`](/sql-reference/motherduck-sql-reference/connection-management/interrupt-connections/).
:::
The `MD_INFORMATION_SCHEMA.RECENT_QUERIES` view provides organization admins with a consolidated view of all running or completed queries across their full organization. It complements the [`MD_INFORMATION_SCHEMA.QUERY_HISTORY`](query_history.md) view, which is geared towards analytics of past events and has some delays, with a more realtime view of active and completed queries that are not yet exposed in `QUERY_HISTORY`. This view is available on Business plans and only to organization admins.
## Schema
When you query the `MD_INFORMATION_SCHEMA.RECENT_QUERIES` view, the query results contain one row for each query that is running or has completed in the organization. The information in this view is updated every couple of seconds.
The `MD_INFORMATION_SCHEMA.RECENT_QUERIES` view shares the same schema as the [`MD_INFORMATION_SCHEMA.QUERY_HISTORY`](query_history.md) view. The main difference is that for queries that have not completed yet the `END_TIME` field is null, and all other fields represent ongoing metrics that will be updated every few seconds.
Full schema:
| Column Name | Data Type | Value |
|-----------------------|-------------|-----------------------------------|
| QUERY_ID | UUID | A unique ID representing the particular query run. You can retrieve this value on the client with [`MD_LAST_QUERY_ID()`](../connection-management/last-query-id.md). |
| QUERY_TEXT | STRING | Query SQL text (up to 100k chars) |
| START_TIME | TIMESTAMPTZ | Start time of the query |
| END_TIME | TIMESTAMPTZ | End time of the query, if the query is completed |
| EXECUTION_TIME | INTERVAL | Duration where the query is actively executing |
| WAIT_TIME | INTERVAL | Duration where the query is waiting on resources to become available. For example a query needs to wait because other queries are using all available execution threads, or a query might be waiting on data to become available (in case of data upload). |
| TOTAL_ELAPSED_TIME | INTERVAL | Total duration of the query (the sum of execution time and wait time) |
| ERROR_MESSAGE | STRING | Error message, if the query returned an error |
| ERROR_TYPE | STRING | Error type, if the query returned an error |
| USER_AGENT | STRING | User agent of the client |
| USER_NAME | STRING | Identifier for the MotherDuck user in their organization |
| QUERY_NR | UBIGINT | ID of the query within the transaction that ran the query. Number that just increments for each query that is run within a given transaction |
| TRANSACTION_NR | UBIGINT | ID of the transaction that contained the query. Number that just increments for each new transaction on a given connection |
| CONNECTION_ID | UUID | Unique ID for the [client DuckDB connection](../connection-management/connection-duckdb-id.md) where the query was issued |
| DUCKDB_ID | UUID | Unique ID for the [client DuckDB instance](../connection-management/connection-duckdb-id.md) where the query was issued |
| DUCKDB_VERSION | STRING | Client DuckDB version that issued the query |
| INSTANCE_TYPE | STRING | The type of duckling that the query was run on (Pulse / Standard / Jumbo / Mega / Giga / ...) |
| QUERY_TYPE | STRING | The nature of the query (DDL / DML / QUERY / ...) |
| BYTES_UPLOADED | UBIGINT | Number of bytes uploaded from client to server (relevant for hybrid queries) |
| BYTES_DOWNLOADED | UBIGINT | Number of bytes downloaded from server to client (relevant for hybrid queries) |
| BYTES_SPILLED_TO_DISK | UBIGINT | Total number of bytes [spilled to disk](https://duckdb.org/docs/stable/guides/performance/how_to_tune_workloads.html#spilling-to-disk) for "larger than in-memory" workloads |
| DUCKLING_ID | STRING | Identifies the duckling that ran the query. It is composed of the user name and a qualifier (`rw` for read-write ducklings, or `rs.0`, `rs.1`, ... for the respective read scaling duckling) |
| SESSION_NAME | STRING | The [`session_name`](/key-tasks/authenticating-and-connecting-to-motherduck/connecting-to-motherduck/#session-names) that was supplied when connecting to MotherDuck |
The fields `START_TIME`, `END_TIME`, `TOTAL_ELAPSED_TIME`, `ERROR_MESSAGE`, and `ERROR_TYPE` are captured on the server (that is, when query starts and ends on server). In the future they will be based on client information too (taking better into account the full hybrid context).
## Example usage
```sql
from MD_INFORMATION_SCHEMA.RECENT_QUERIES where end_time is null limit 10;
```
## Limitations
The `RECENT_QUERIES` view has been optimized for quickly answering questions such as "Which ongoing queries in my organization are taking a long time to complete". Query results of this view are therefore limited to 1000 rows, but support filter pushdowns so that this limit only applies after some basic filters. Take for example the following query:
```sql
from MD_INFORMATION_SCHEMA.RECENT_QUERIES where end_time is null and total_elapsed_time > '5 seconds';
```
The 1000 row limit only applies after the `end_time` and the `total_elapsed_time` filters have been applied, showing at most 1000 queries that are still ongoing and that are taking longer than 5 seconds. To check what filters are pushed down and apply before the row limit, the "filters" section of the MD_SERVER_RECENT_QUERIES table scan operator can be checked in the [query plan explain output](https://duckdb.org/docs/stable/guides/meta/explain).
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/refresh-database
# REFRESH DATABASE
> Sync databases with the latest snapshot or share updates.
There are two types of databases that can be refreshed: **database shares** and databases attached to **read scaling**
connections.
**Read scaling** connections sync automatically every minute. To ensure maximum freshness, run `CREATE SNAPSHOT` on the
writer, followed by `REFRESH DATABASES` on the reader. This pulls the latest snapshot.
**Database shares** can also be refreshed—either automatically or manually. In this case, the writer uses `UPDATE SHARE`
instead of `CREATE SNAPSHOT`, followed by `REFRESH DATABASES` on the reader.
## Behavior by connection mode
How `REFRESH DATABASES` behaves depends on which
[attach mode](/key-tasks/authenticating-and-connecting-to-motherduck/attach-modes/)
your session is in:
- **Workspace mode** (the default; for example, `ATTACH 'md:'` or the `md:`
connection string): Two things happen. First, refreshable databases in the
session (shares and read-scaling) pull their latest snapshot. Second,
MotherDuck reconciles the session's attachment list against the server-side
workspace, so databases created by other connections (for example, R/W
instances) since your last sync are auto-attached. Use this when you want
your session to reflect catalog changes made elsewhere.
- **Single mode** (for example, `md:?attach_mode=single`
connection string, `ATTACH 'md:'` in an existing DuckDB
session, or `SET motherduck_attach_mode='single'` before attaching):
Refreshes only the refreshable databases (shares and read-scaling) already
attached in the session. New databases on the server are **not**
auto-discovered or attached. This is by design -- single mode keeps your
session scoped, doesn't persist attachment changes, and stays out of sync
with parallel connections. Attach more databases explicitly if you need
them.
## Syntax
`REFRESH DATABASES` (plural, no name) and `REFRESH DATABASE `
(singular, with a name) are two distinct forms; you can't combine them.
For example, `REFRESH DATABASES my_db` fails to parse.
```sql
-- Refresh all refreshable databases attached to the current session
REFRESH DATABASES;
-- Refresh a specific share or read-scaling database
REFRESH DATABASE ;
```
The single-database form only works for **database shares** and
**read-scaling** databases. Calling `REFRESH DATABASE ` on a regular
R/W database returns an error:
*"`` is not a share or database on a read-scaling instance."*
The behavior of `REFRESH DATABASES` depends on how you connected to MotherDuck:
- **Workspace mode** (`ATTACH 'md:'`): Refreshes all databases in your workspace, including new databases created by other connections (e.g., R/W instances). This allows you to pick up databases that were created after your initial connection.
## Syntax
```sql
REFRESH { DATABASE | DATABASES } [];
```
## Examples
```sql
REFRESH DATABASES; -- Refreshes all connected databases and shares
┌─────────┬───────────────────┬──────────────────────────┬───────────┐
│ name │ type │ fully_qualified_name │ refreshed │
│ varchar │ varchar │ varchar │ boolean │
├─────────┼───────────────────┼──────────────────────────┼───────────┤
│ │ motherduck │ md: │ false │
│ │ motherduck share │ md:_share// │ true │
└─────────┴───────────────────┴──────────────────────────┴───────────┘
REFRESH DATABASE my_db; -- Alternatively, refresh a specific database
┌─────────┬──────────────────┬──────────────────────────┬───────────┐
│ name │ type │ fully_qualified_name │ refreshed │
│ varchar │ varchar │ varchar │ boolean │
├─────────┼──────────────────┼──────────────────────────┼───────────┤
│ │ motherduck share │ md:_share// │ false │
└─────────┴──────────────────┴──────────────────────────┴───────────┘
```
## Related Content
- [CREATE SNAPSHOT](/sql-reference/motherduck-sql-reference/create-snapshot.md)
- [UPDATE SHARE](/sql-reference/motherduck-sql-reference/update-share.md)
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/revoke-access
# REVOKE READ ON SHARE
> Remove user access from a restricted share.
For restricted shares, use the `REVOKE` command to explicitly remove share access from users that have an existing `GRANT`. After running a `REVOKE` command there may be a delay of a few minutes before access is fully removed if a user is currently querying the share. Only the owner of the share can use the `REVOKE` command to remove access from others. `GRANT` and `REVOKE` do not apply to `UNRESTRICTED` shares.
## Syntax
```sql
REVOKE READ ON SHARE FROM [, , ];
```
If a username contains special characters, such as '@', it must be enclosed in double quotes (`"`).
## Example usage
```sql
-- revokes access to the share 'birds' from the user with username 'duck'
REVOKE READ ON SHARE birds FROM duck;
-- revokes access to the share 'taxis' from the users with usernames 'usr1' and 'usr2'
REVOKE READ ON SHARE taxis FROM usr1, usr2;
-- revokes access from a user whose username contains special characters
REVOKE READ ON SHARE sensitive_data FROM "user@example-com";
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/show-databases
# SHOW ALL DATABASES
> List all MotherDuck, DuckDB, and shared databases.
The `SHOW ALL DATABASES` statement shows all databases, would it be MotherDuck database, DuckDB database or MotherDuck shares.
It returns:
* `alias` (`db_name` or `share_alias`)
* `is_attached` flag to mention if the database is attached or not.
* `type` (e.g. DuckDB, MotherDuck, MotherDuck share)
* `fully_qualified_name` (empty, md:_share/ or md:db_name)
To query specific columns, you can use the table function `MD_ALL_DATABASES()`.
# Syntax
```sql
SHOW ALL DATABASES;
```
or using the table function
```sql
select * from MD_ALL_DATABASES();
```
# Example usage
```sql
SHOW ALL DATABASES;
```
Example output:
```bash
┌──────────────────────────────────────────┬─────────────┬──────────────────┬─────────────────────────────────────────────────────────────────────────────────────────┐
│ alias │ is_attached │ type │ fully_qualified_name │
│ varchar │ boolean │ varchar │ varchar │
├──────────────────────────────────────────┼─────────────┼──────────────────┼─────────────────────────────────────────────────────────────────────────────────────────┤
│ TEST_DB_02d6fc2158094bd693b6f285dbd402f7 │ true │ motherduck │ md:TEST_DB_02d6fc2158094bd693b6f285dbd402f7 │
│ TEST_DB_62b53d968a4f4b6682ed117a7251b814 │ true │ motherduck │ md:TEST_DB_62b53d968a4f4b6682ed117a7251b814 │
│ base │ false │ motherduck │ md:base │
│ base2 │ true │ motherduck │ md:base2 │
│ db1 │ false │ motherduck │ md:db1 │
│ integration_test_001 │ false │ motherduck │ md:integration_test_001 │
│ my_db │ true │ motherduck │ md:my_db │
│ my_share_1 │ true │ motherduck share │ md:_share/integration_test_001/18d6dbdb-e130-4cdf-97c4-60782ed5972b │
│ sample_data │ false │ motherduck │ md:sample_data │
│ source_db │ true │ motherduck │ md:source_db │
│ test_db_115 │ false │ motherduck │ md:test_db_115 │
│ test_db_28d │ false │ motherduck │ md:test_db_28d │
│ test_db_cc9 │ false │ motherduck │ md:test_db_cc9 │
│ test_share │ true │ motherduck share │ md:_share/source_db/b990b424-2f9a-477a-b216-680a22c3f43f │
│ test_share_002 │ true │ motherduck share │ md:_share/integration_test_001/06cc5500-e49a-4f62-9203-105e89a4b8ae │
├──────────────────────────────────────────┴─────────────┴──────────────────┴─────────────────────────────────────────────────────────────────────────────────────────┤
│ 15 rows (15 shown) 4 columns │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/shutdown-terminate
# SHUTDOWN
> Gracefully shut down or force-terminate your Duckling to manage compute costs and recover from stuck queries.
Each [Duckling size](/about-motherduck/billing/duckling-sizes/) has a [cooldown period](/about-motherduck/billing/duckling-sizes/#configuring-the-cooldown-period) which is the time it stays active after completing the last query to keep it warm for follow-up queries. If you know your workload is done, you can use the `SHUTDOWN` command to skip the remaining cooldown. When using `SHUTDOWN` the duckling tries to gracefully shutdown after which the billing also stops. You will always be billed for a minimum of 60 seconds. If multiple clients are connected to the same duckling and actively querying when the shutdown is initiated, the duckling might be prevented from shutting down to allow the other clients to keep querying.
MotherDuck provides two shutdown commands: a graceful shutdown that waits for activity to complete, and a forced termination for stuck or unresponsive Ducklings.
## `SHUTDOWN`
Gracefully shuts down the Duckling at the earliest opportunity. Running queries are allowed to complete, and no existing work is interrupted.
### Syntax
```sql
SHUTDOWN;
-- or equivalently:
SHUTDOWN NORMAL;
```
### Behavior
- The command returns immediately after the shutdown intent is registered — it does not wait for the Duckling to fully shut down.
- Running queries and open transactions are **not** interrupted and will complete normally.
- Other connected clients can continue querying. The Duckling shuts down once all clients become inactive.
- If new queries are issued after the command, they execute normally — the Duckling stays alive while there is activity, but shuts down once activity stops.
### Example
```sql
-- Shut down the Duckling after current work completes
SHUTDOWN;
```
## `SHUTDOWN TERMINATE`
Force-terminates a stuck or unresponsive Duckling by cancelling all running queries and initiating an immediate shutdown. This is intended for situations where queries cannot be cancelled using [`md_interrupt_server_connection`](/sql-reference/motherduck-sql-reference/connection-management/interrupt-connections/) or where the Duckling is otherwise not making progress.
### Syntax
```sql
SHUTDOWN TERMINATE;
-- Optionally provide a reason (for observability and diagnostics)
SHUTDOWN TERMINATE (REASON 'reason for shutdown');
```
### Behavior
- All running queries are interrupted and cancelled.
- The command returns a result once the shutdown process has been initiated.
- Newly issued queries from any client are queued until a new Duckling starts.
- The **minimum 1-minute billing charge** still applies.
- Works on all [Duckling sizes](/about-motherduck/billing/duckling-sizes/), including Pulse.
### Example
Spin up a Giga Duckling, run a batch job, and shut it down immediately to minimize costs:
```sql
-- Run your batch job
CREATE TABLE my_db.results AS
SELECT * FROM my_db.raw_events
WHERE event_date >= '2025-01-01'
GROUP BY ALL;
-- Shut down the Duckling immediately (billed for 1 min minimum)
SHUTDOWN;
```
In this example, instead of waiting for the Giga Duckling's default 10-minute cooldown period, `SHUTDOWN` stops the Duckling right away. You are billed for the actual query time (wall clock time) plus the 1-minute minimum, not the full cooldown.
```sql
-- Force-terminate a stuck Duckling with a reason
SHUTDOWN TERMINATE (REASON 'stuck query on large join');
```
## Choosing between `SHUTDOWN` and `SHUTDOWN TERMINATE`
| | `SHUTDOWN` | `SHUTDOWN TERMINATE` |
|---|---|---|
| **Running queries** | Allowed to complete | Cancelled immediately |
| **New queries** | Continue normally | Queued until new Duckling starts |
| **Shutdown timing** | After all activity stops | Immediate |
| **Use case** | Skip idle cooldown after a job | Recover from stuck queries |
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/storage_info
# STORAGE_INFO views
> View storage footprint, billing, and lifecycle information for all databases in your MotherDuck organization
:::note Admin Only Feature
This feature can only be used by Admin users.
:::
## Overview
MotherDuck provides two views to look at how much storage is used - a current snapshot (`STORAGE_INFO`) and the previous 30 days of history (`STORAGE_INFO_HISTORY`).
The `MD_INFORMATION_SCHEMA.STORAGE_INFO` view provides comprehensive storage information for all databases in your MotherDuck organization. This view is essential for understanding storage usage, billing calculations, and database lifecycle management.
The `MD_INFORMATION_SCHEMA.STORAGE_INFO_HISTORY` view provides storage information for up to the past 30 days of usage.
If you're an admin, you can view your organization's storage breakdown on the [databases page](https://app.motherduck.com/settings/databases). Here, you'll find the total breakdown of current bytes across all your databases, as well as a breakdown for each database. You can also click on a row to get a lifecycle breakdown for a given database.
## Syntax
To see the latest snapshot:
```sql
SELECT * FROM MD_INFORMATION_SCHEMA.STORAGE_INFO;
```
To see the history:
```sql
SELECT * FROM MD_INFORMATION_SCHEMA.STORAGE_INFO_HISTORY;
```
## Columns
The `MD_INFORMATION_SCHEMA.STORAGE_INFO` view returns one row for each database in your organization with the following columns:
| Column Name | Data Type | Description |
| ----------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `database_name` | VARCHAR | Name of the database |
| `database_id` | UUID | Unique ID for the database |
| `created_ts` | TIMESTAMP | Time when the database was created |
| `deleted_ts` | TIMESTAMP | Time when the database was deleted (NULL if not deleted) |
| `user_name` | VARCHAR | Username of the database owner |
| `active_bytes` | BIGINT | Actively referenced bytes of the database |
| `historical_bytes` | BIGINT | Non-active bytes that are referenced by a share of this database |
| `retained_for_clone_bytes` | BIGINT | Bytes referenced by other databases (through zero-copy clone) that are no longer referenced by this database as active or historical bytes |
| `failsafe_bytes` | BIGINT | Bytes that are no longer referenced by any database or share |
| `transient` | BOOLEAN | Whether the database is transient |
| `historical_snapshot_retention` | INTERVAL | Period of time the database's snapshots are retained after becoming inactive |
| `computed_ts` | TIMESTAMP | Time at which active_bytes, historical_bytes, etc. were computed |
The `MD_INFORMATION_SCHEMA.STORAGE_INFO_HISTORY` view has the same schema, but will return results from up to the past 30 days, so a single database might have multiple entries reflecting its state at different points in time.
## Examples
### Basic usage
View storage information for all databases in your organization:
```sql
-- Get storage information for all databases
SELECT * FROM MD_INFORMATION_SCHEMA.STORAGE_INFO;
```
**Sample results:**
| database_name | database_id | created_ts | deleted_ts | user_name | active_bytes | historical_bytes | retained_for_clone_bytes | failsafe_bytes | transient | historical_snapshot_retention | computed_ts |
| ------------- | ------------------------------------ | ------------------- | ---------- | -------- | ------------ | ---------------- | --------------------- | -------------- | -------- | --------------------- | ---------------------- |
| test_db_1 | 7ed1baf3-e4ff-42c9-a37b-9f683905ce45 | 2024-12-02 20:18:36 | NULL | bob | 82063360 | 0 | 268496896 | 0 | false | 1 day | 2025-06-25 16:46:16.37 |
| test_db_2 | fcc16e53-d761-4e40-84ec-15570fab363e | 2024-11-12 03:38:52 | NULL | jim | 274432 | 0 | 0 | 0 | false | 1 day | 2025-06-25 16:46:16.37 |
### Filtering and analysis
Find databases with high storage usage:
```sql
-- Find databases using more than 1GB of active storage
SELECT
database_name,
user_name,
active_bytes,
ROUND(active_bytes / 1000.0 / 1000.0 / 1000.0, 2) as active_gb
FROM MD_INFORMATION_SCHEMA.STORAGE_INFO
WHERE active_bytes > 1000000000 -- 1GB in bytes
ORDER BY active_bytes DESC;
```
### Storage cost analysis
Analyze storage costs by user:
```sql
-- Calculate total storage usage per user
SELECT
user_name,
COUNT(*) as database_count,
SUM(active_bytes) as total_active_bytes,
SUM(historical_bytes) as total_historical_bytes,
SUM(retained_for_clone_bytes) as total_cloned_bytes,
SUM(failsafe_bytes) as total_failsafe_bytes
FROM MD_INFORMATION_SCHEMA.STORAGE_INFO
GROUP BY user_name
ORDER BY total_active_bytes DESC;
```
Analyze active and failsafe storage footprint over the past week for a specific database:
```sql
SELECT active_bytes, failsafe_bytes, computed_ts
FROM MD_INFORMATION_SCHEMA.STORAGE_INFO_HISTORY
WHERE database_name = "my_database"
AND computed_ts >= NOW - INTERVAL 7 DAYS
ORDER BY computed_ts DESC;
```
## Notes
- **Data Refresh**: Information in this view refreshes every 1-6 hours
- **Retention**: STORAGE_INFO_HISTORY only returns one set of results per day, even though the latest results are re-computed multiple times per day
- **Billing Data**: This view returns the underlying data used to power MotherDuck storage billing
- **Permissions**: You must have appropriate permissions to access this view
- **Organization Scope**: Only shows databases within your current organization
### Understanding timestamps
The `created_ts` column in `STORAGE_INFO` represents when the **database** was created. This is useful for understanding database age and lifecycle.
For [point-in-time restore](/concepts/data-recovery) scenarios, use [`DATABASE_SNAPSHOTS`](/sql-reference/motherduck-sql-reference/md_information_schema/database_snapshots) instead, where `created_ts` represents when each **snapshot** was created.
| View | `created_ts` meaning | Use case |
|------|---------------------|----------|
| `STORAGE_INFO` | When the database was created | Storage billing, database lifecycle management |
| `DATABASE_SNAPSHOTS` | When the snapshot was created | Point-in-time restore, finding snapshots to recover |
## Troubleshooting
### Common issues
**Outdated information**
- Data refreshes only happen periodically, so recent changes may not be immediately visible
**Permission denied errors**
- Contact your organization administrator to ensure you have the necessary permissions
- This feature is only for Admins
- Verify your authentication token is valid and has the required scope
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/temporary-tables
# TEMPORARY TABLES
> Create local temporary tables for session-scoped data.
The `CREATE TEMPORARY TABLE` statement creates a new a temporary from a sql query. This command is used to create a local temporary table. [More information can be found in the DuckDB documentation.](https://duckdb.org/docs/sql/statements/create_table.html#temporary-tables)
## Syntax
```sql
CREATE [ OR REPLACE ] TEMPORARY TABLE [ IF NOT EXISTS ] AS ...
```
Temporary Tables can be created traditionally with column names and types, or with `Create Table ... As Select` (CTAS).
### Shorthand Convention
The word `TEMP` can be used interchangably with `TEMPORARY`.
## Example Usage
```sql
CREATE TEMPORARY TABLE flights AS
FROM 'https://duckdb.org/data/flights.csv';
```
This will create a local table with data from the duckdb `flights.csv` file.
## Notes
- Temporary Tables in MotherDuck persist locally, not on the server. As such, local constraints should be considered when using them.
- Because they are bound to your session, when your session ends, any temporary tables will no longer be available.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/undrop-database
# UNDROP DATABASE
> Restore a dropped MotherDuck database within its snapshot retention window.
The `UNDROP DATABASE` statement restores a previously dropped MotherDuck database and its snapshot history, as long as the drop is still within the database's snapshot retention window.
This statement applies to MotherDuck native storage databases (standard or transient). DuckLake databases do not support snapshots.
## Syntax
```sql
UNDROP DATABASE
```
## Notes
- A dropped database can be undropped only while historical snapshots are still retained. The retention period is controlled by `SNAPSHOT_RETENTION_DAYS`. Use [`ALTER DATABASE`](/sql-reference/motherduck-sql-reference/alter-database) to change it.
- After undropping, the database is not automatically attached in your current session. Re-attach it with `ATTACH 'md:'`, then `USE ` if needed.
- For retention defaults and plan limits, see the [data recovery guide](/concepts/data-recovery) and [storage lifecycle](/concepts/storage-lifecycle#storage-management).
## Examples
Drop a database, then undrop and attach it:
```sql
DROP DATABASE test_db;
UNDROP DATABASE test_db;
ATTACH 'md:test_db';
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/update-share
# UPDATE SHARE
> Manually update a share with a new database snapshot.
Shares can either be manually or automatically updated by the share creator. All users of the share will automatically see share updates within 1 minute, containing both DDL (like CREATE TABLE) and DML (inserts, updates, or deletes) changes.
These updates are transactionally consistent snapshots, i.e. never partial database updates.
The share creator can have the share be automatically updated when the underlying database changes. This is done by specifying the `UPDATE AUTOMATIC` option during [share creation](create-share.md).
Alternatively the share creator can manually update the share with a new point-in-time snapshot of the database. This is done by running the `UPDATE SHARE` command.
# Syntax
```sql
UPDATE SHARE ;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/use-sql-query
# useSQLQuery hook
> React hook for querying MotherDuck data from within Dives.
The `useSQLQuery` hook is a React hook that runs SQL queries against MotherDuck from within a [Dive](/key-tasks/ai-and-motherduck/dives). It handles loading states and error reporting so your component can focus on rendering data.
## Import
```jsx
import { useSQLQuery } from "@motherduck/react-sql-query";
```
## Syntax
```jsx
const { data, isLoading, isError, error, exportAs } = useSQLQuery(sql, options);
```
## Parameters
### `sql`
| Type | Required |
|------|----------|
| `string` | Yes |
A SQL query string to run against MotherDuck. The Dive runtime returns rows as objects.
Use fully qualified, double-quoted table names in your queries (`"database"."schema"."table"`) to avoid issues when the Dive runs outside your current database context.
### `options`
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `enabled` | `boolean` | `true` | Set to `false` to skip query execution. Useful when a query depends on user input that isn't available yet. |
## Return value
| Property | Type | Description |
|----------|------|-------------|
| `data` | array or `undefined` | Query result as an array of row objects. `undefined` while loading. |
| `isLoading` | `boolean` | `true` while the query is running |
| `isError` | `boolean` | `true` if the query failed |
| `error` | `Error` or `null` | Error object if the query failed |
| `exportAs` | `(options) => Promise` | Exports this query as a file |
:::warning
`data` is the row array directly — there is no `data.rows` wrapper. Always guard against `undefined`:
```jsx
const rows = Array.isArray(data) ? data : [];
```
:::
## Numeric values
DuckDB returns `BIGINT`, `HUGEINT`, and `DECIMAL` as JavaScript `BigInt` or special objects, not `number`. These crash if rendered in JSX or used with `.toFixed()`. Define this helper at the top of every Dive and wrap all numeric values:
```jsx
const N = (v) => (v != null ? Number(v) : 0);
```
## Examples
### Basic query
```jsx
import { useSQLQuery } from "@motherduck/react-sql-query";
const N = (v) => (v != null ? Number(v) : 0);
export default function Dive() {
const { data, isLoading } = useSQLQuery(`
SELECT category, SUM(amount) AS total
FROM "my_db"."main"."sales"
GROUP BY ALL
`);
if (isLoading) return Loading...
;
const rows = Array.isArray(data) ? data : [];
return (
{rows.map((row) => (
{row.category}: ${N(row.total).toLocaleString()}
))}
);
}
```
### Conditional queries with `enabled`
Skip a query until a user selection is available:
```jsx
const [selected, setSelected] = useState(null);
const { data: details } = useSQLQuery(`
SELECT * FROM "my_db"."main"."products"
WHERE category = '${selected}'
`, { enabled: !!selected });
```
### Multiple independent queries
Each `useSQLQuery` call loads independently. Render the page layout immediately and show inline placeholders per section instead of a single loading spinner:
```jsx
const summary = useSQLQuery(`
SELECT COUNT(*) AS total, SUM(revenue) AS revenue
FROM "my_db"."main"."orders"
`);
const monthly = useSQLQuery(`
SELECT strftime(date_trunc('month', order_date), '%Y-%m') AS month,
SUM(revenue) AS revenue
FROM "my_db"."main"."orders"
GROUP BY 1 ORDER BY 1
`);
return (
{summary.isLoading
?
:
{N(summary.data?.[0]?.revenue)}
}
{monthly.isLoading
?
:
}
);
```
### Export query results
Use `exportAs()` when you want to export the same SQL query used by a `useSQLQuery()` hook. Exports must start from a user action, such as a button click.
```jsx
import { useSQLQuery } from "@motherduck/react-sql-query";
export default function Dive() {
const orders = useSQLQuery(`
SELECT *
FROM "my_db"."main"."orders"
ORDER BY order_date DESC
`);
return (
orders.exportAs({
format: "csv",
title: "Orders",
filename: "orders",
})
}
>
Export orders
);
}
```
Use `useExport()` when the export should run a different SQL query than the rows rendered on the page:
```jsx
import { useExport } from "@motherduck/react-sql-query";
export default function DiveExportButton() {
const { exportQuery } = useExport();
return (
exportQuery({
sql: `
SELECT customer_id, SUM(amount) AS total_amount
FROM "my_db"."main"."orders"
GROUP BY ALL
ORDER BY total_amount DESC
`,
format: "parquet",
title: "Customer totals",
filename: "customer-totals",
})
}
>
Export customer totals
);
}
```
Supported formats are `csv`, `json`, `parquet`, and `xlsx`. The `filename` value is a base name; MotherDuck adds the file extension. You can pass DuckDB `COPY` writer options under `csv`, `json`, `parquet`, or `xlsx`:
```jsx
orders.exportAs({
format: "xlsx",
filename: "orders",
xlsx: {
sheet: "Orders",
header: true,
},
});
```
Exports run with DuckDB `COPY TO`, not from the rows already materialized in React. This means an export can contain more rows than the Dive renders. Export SQL must be read-only.
## Tips
- **Format dates in SQL, not JavaScript.** Use DuckDB's `strftime()` to format dates and timestamps as strings. DuckDB date types are returned as special objects that don't render in JSX.
- **Fill time series gaps in SQL.** Recharts does not interpolate missing time periods. Use `generate_series` with a `LEFT JOIN` to produce a continuous date spine.
- **Dollar-quoted strings.** When passing Dive content through SQL (for example, with [`MD_CREATE_DIVE`](../md-create-dive)), use [dollar-quoted string literals](https://duckdb.org/docs/stable/sql/data_types/literal_types#dollar-quoted-string-literals) to avoid escaping issues with nested quotes.
## Related
- [Dives SQL functions](/sql-reference/motherduck-sql-reference/ai-functions/dives/) — Manage Dives with SQL
- [`useDiveState` hook](/sql-reference/motherduck-sql-reference/ai-functions/dives/use-dive-state) — Store shareable filters, sorting, and view state in the Dive URL
- [Creating visualizations with Dives](/key-tasks/ai-and-motherduck/dives) — How-to guide
- [Embedding Dives in your web application](/key-tasks/ai-and-motherduck/dives/embedding-dives) — Handle embedded Dive sessions and exports
- [MCP Server](/sql-reference/mcp/) — Create Dives through AI assistants
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/use-dive-state
# useDiveState hook
> React hook for storing shareable UI state in MotherDuck Dives.
The `useDiveState` hook is a React hook for storing interactive state in a [Dive](/key-tasks/ai-and-motherduck/dives). It works like React's `useState`, but it also syncs the value to the Dive URL so viewers can share the current filters, sorting, selected view, and drill-down state.
Use `useDiveState` for state that should survive a page refresh or travel with a shared URL. Use React's `useState` for temporary UI state such as input drafts, open dialogs, or dismissed banners.
## Import
```jsx
import { useDiveState } from "@motherduck/react-sql-query";
```
## Syntax
```jsx
const [value, setValue] = useDiveState(key, initialValue);
```
In TypeScript, pass the value type explicitly when you want a narrowed literal union or when the initial value is an empty array:
```tsx
const [view, setView] = useDiveState<"cards" | "list" | "compact">(
"view",
"cards"
);
const [selectedRegions, setSelectedRegions] = useDiveState(
"selectedRegions",
[]
);
```
## Parameters
### `key`
| Type | Required |
|------|----------|
| `string` | Yes |
A stable key for the state value. If two components in the same Dive call `useDiveState` with the same key, they read and write the same value.
Use short, descriptive keys such as `region`, `sortBy`, `selectedCustomer`, or `chartView`.
### `initialValue`
| Type | Required |
|------|----------|
| JSON-serializable value | Yes |
The value to use when the URL does not contain a value for `key`.
Values must be JSON-serializable: strings, numbers, booleans, `null`, arrays, and plain objects made from those values. Do not store `Date`, `Map`, `Set`, functions, class instances, credentials, or large row payloads in Dive state.
If TypeScript reports `Expected 3 arguments, but got 2` with a label about `useDiveState defaultValue must be JSON-serializable`, the `initialValue` is not a supported JSON value. There is no third argument to pass; change the value shape instead.
## Return value
| Property | Type | Description |
|----------|------|-------------|
| `value` | same type as `initialValue` | The current value for `key`, read from the URL state when present. |
| `setValue` | function | Updates the value and syncs it to the URL state. |
`setValue` accepts either a new value or an updater function, matching React's `useState` setter pattern.
## Reset state
Pass `undefined` to the setter to remove the key from the URL state. After reset, the hook reads from `initialValue` again.
```jsx
const [view, setView] = useDiveState("view", "summary");
return (
setView(undefined)}>
Reset view
);
```
## Examples
### Share a filtered view
```jsx
import { useDiveState, useSQLQuery } from "@motherduck/react-sql-query";
export default function Dive() {
const [region, setRegion] = useDiveState("region", "all");
const regionFilter = {
all: "",
amer: "WHERE region = 'Americas'",
emea: "WHERE region = 'EMEA'",
apac: "WHERE region = 'APAC'",
}[region] ?? "";
const { data = [], isLoading } = useSQLQuery(`
SELECT region, SUM(revenue) AS revenue
FROM "analytics"."main"."orders"
${regionFilter}
GROUP BY ALL
ORDER BY revenue DESC
`);
if (isLoading) return Loading...
;
return (
setRegion(event.target.value)}>
All regions
Americas
EMEA
APAC
{data.map((row) => (
{row.region}: {Number(row.revenue).toLocaleString()}
))}
);
}
```
When a viewer changes the selected region, the Dive URL updates. Copying that URL shares the same selected region with another viewer.
### Share sort order
```jsx
const [sortBy, setSortBy] = useDiveState("sortBy", "revenue_desc");
const orderBy = {
revenue_desc: "revenue DESC",
revenue_asc: "revenue ASC",
customer: "customer_name ASC",
}[sortBy] ?? "revenue DESC";
```
Use a controlled set of sort values and map them to SQL fragments. Do not concatenate unrestricted user input into SQL.
### Share state between components
```jsx
function RegionPicker() {
const [region, setRegion] = useDiveState("region", "all");
return setRegion(event.target.value)} />;
}
function RevenueChart() {
const [region] = useDiveState("region", "all");
return ;
}
```
Both components use the same `region` key, so changing the picker updates the chart without a separate context provider.
## Limitations
- State is visible to anyone who has the URL. Do not store secrets, tokens, credentials, or sensitive row-level data.
- Keep state small. Large encoded state creates long URLs that may be truncated by chat apps, browsers, or URL shorteners.
- Store selections and identifiers, not full query results. If the value can be reconstructed from SQL, store the small key and query for the data again.
- URL state is per Dive view. It does not change the saved Dive source or its default `initialValue`.
## Related
- [`useSQLQuery` hook](/sql-reference/motherduck-sql-reference/ai-functions/dives/use-sql-query) — Query data from within Dives
- [Creating visualizations with Dives](/key-tasks/ai-and-motherduck/dives) — How-to guide
- [Embedding Dives in your web application](/key-tasks/ai-and-motherduck/dives/embedding-dives) — Handle embedded Dive sessions and exports
- [MCP Server](/sql-reference/mcp/) — Create Dives through AI assistants
---
Source: https://motherduck.com/docs/sql-reference/mcp/list-shares
# list_shares
> List database shares that have been shared with you
List all database [shares](/key-tasks/sharing-data/sharing-overview) that have been shared with you.
## Description
The `list_shares` tool returns all database shares that have been shared with you by other users. Each share includes its name and URL, which can be used to attach the share as a database using the `query` tool.
To attach a share, execute: `ATTACH '' AS my_alias;`
To detach a share: `DETACH ;`
## Input Parameters
This tool takes no input parameters.
## Output Schema
```json
{
"success": boolean,
"shares": [ // List of shares (on success)
{
"name": string, // Share name
"url": string // Share URL for attaching
}
],
"error": string // Error message (on failure)
}
```
## Example Usage
**List available shares:**
```text
What shares have been shared with me?
```
The AI assistant will call the tool with no parameters.
**Attach a share after listing:**
```text
Attach the sales_data share so I can query it
```
After getting the share URL from `list_shares`, the AI will use the `query` tool:
```json
{
"database": "my_db",
"sql": "ATTACH 'md:_share/org123/sales_data' AS sales_data"
}
```
## Success Response Example
```json
{
"success": true,
"shares": [
{
"name": "sales_data",
"url": "md:_share/org123/sales_data"
},
{
"name": "product_catalog",
"url": "md:_share/org456/product_catalog"
},
{
"name": "analytics_benchmark",
"url": "md:_share/org789/analytics_benchmark"
}
]
}
```
## Empty Response Example
When no shares have been shared with you:
```json
{
"success": true,
"shares": []
}
```
## Related
- [Sharing Overview](/key-tasks/sharing-data/sharing-overview) - Learn about MotherDuck's data sharing capabilities
- [Managing Shares](/key-tasks/sharing-data/managing-shares) - How to create and manage shares
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-get-dive
# MD_GET_DIVE
> Retrieve a Dive by ID including its full React component content.
Retrieves a single [Dive](/key-tasks/ai-and-motherduck/dives) by ID, including the full React component source code for the current version.
## Syntax
```sql
SELECT * FROM MD_GET_DIVE(id ='your-dive-uuid'::UUID);
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | `UUID` | Yes | The unique identifier of the Dive |
## Return columns
| Column | Type | Description |
|--------|------|-------------|
| `id` | `UUID` | Unique identifier of the Dive |
| `title` | `VARCHAR` | Dive title |
| `description` | `VARCHAR` | Dive description |
| `owner_id` | `UUID` | UUID of the Dive owner |
| `current_version` | `INTEGER` | Latest version number (1-based) |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When the Dive was created |
| `updated_at` | `TIMESTAMP WITH TIME ZONE` | When the Dive was last updated |
| `owner_name` | `VARCHAR` | Name of the Dive owner |
| `version_id` | `UUID` | UUID of the current version |
| `version_storage_url` | `VARCHAR` | Storage URL of the current version content |
| `version_description` | `VARCHAR` | Description/commit message for the current version |
| `version_created_at` | `TIMESTAMP WITH TIME ZONE` | When the current version was created |
| `version_api_version` | `UINTEGER` | API version used to create this version |
| `content` | `VARCHAR` | Full JSX/React component source code |
## Examples
Read a Dive by ID:
```sql
SELECT title, description, content
FROM MD_GET_DIVE(id ='a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID);
```
Get the metadata without the content:
```sql
SELECT id, title, owner_name, current_version, updated_at
FROM MD_GET_DIVE(id ='a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID);
```
## Errors
Returns an error if the Dive does not exist.
## Related
- [`MD_GET_DIVE_VERSION`](../md-get-dive-version) — Retrieve a specific historical version
- [`MD_LIST_DIVES`](../md-list-dives) — List all Dives to find IDs
- [`read_dive` MCP tool](/sql-reference/mcp/read-dive) — AI assistant equivalent
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/connection-management/interrupt-connections
# MD_INTERRUPT_SERVER_CONNECTION
> Cancel running queries and terminate active connections to MotherDuck using SQL commands.
:::info
This is a preview feature. Preview features may be operationally incomplete and may offer limited backward compatibility.
:::
# MD_INTERRUPT_SERVER_CONNECTION
:::tip
You can also cancel running queries in the MotherDuck UI under **Settings** → **Running Queries**. See [Running Queries](/getting-started/interfaces/motherduck-quick-tour/#running-queries) for details.
To identify long-running queries across your organization, see the [`RECENT_QUERIES`](/sql-reference/motherduck-sql-reference/md_information_schema/recent_queries/) view (for admins on the Business plan).
:::
The `md_interrupt_server_connection` scalar function can be used to interrupt an active transaction on a server-side connection.
This will interrupt and fail / rollback the active transaction (when executing for example a long-running query), but will allow the connection to be used for future transactions and queries.
The function takes as input the `client_connection_id`, i.e. the unique identifier for the client DuckDB connection that initiated the server connection.
## Syntax
```sql
SELECT md_interrupt_server_connection();
```
## Return value
Returns a `BOOLEAN`:
- `true` — the interrupt signal was successfully sent to the connection
- `false` — the interrupt could not be sent, which can happen if: the connection is already closed, the transaction is committing or rolling back, or the server-side connection could not be found
## Example usage
Interrupting a specific connection:
```sql
SELECT md_interrupt_server_connection('2601e799-51b3-47a7-a64f-18688d148887');
```
Using `md_interrupt_server_connection` in conjunction with [`md_active_server_connections`](documentation/sql-reference/motherduck-sql-reference/connection-management/monitor-connections.md) to interrupt a subset or all of the active connections:
```sql
-- Interrupt all connections where a `CREATE TABLE` query is running
SELECT md_interrupt_server_connection(client_connection_id)
FROM md_active_server_connections()
WHERE client_query ILIKE 'CREATE TABLE%';
```
The query returns one boolean per matched connection indicating whether each interrupt succeeded. If 0 rows are returned, no active connections matched the filter — the query may have already finished.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-update-flight
# MD_UPDATE_FLIGHT
> Update a Flight's source code, requirements, config, token, secrets, name, or schedule.
Updates an existing [Flight](/concepts/flights). Behaves as a PATCH: only the parameters you pass are modified, and unspecified fields are left unchanged.
Updates to `source_code`, `requirements_txt`, `config`, `access_token_name`, or `flight_secret_names` produce a fresh `FlightVersion`. Updates to `name` or `schedule_cron` are metadata-only and do not bump the version.
## Syntax
```sql
CALL MD_UPDATE_FLIGHT(
flight_id := '',
name := '',
schedule_cron := '0 0 * * *',
source_code := '',
requirements_txt := '',
config := MAP {'KEY': 'value'},
access_token_name := '',
flight_secret_names := ['secret_name']
);
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight to update. |
| `name` | `VARCHAR` | No | New Flight name. Must be non-empty when provided. Metadata-only. |
| `schedule_cron` | `VARCHAR` | No | New cron expression (UTC, 5 fields). Pass `''` (empty string) to clear the schedule. Metadata-only. |
| `source_code` | `VARCHAR` | No | New Python source. Bumps the version. |
| `requirements_txt` | `VARCHAR` | No | New `requirements.txt` contents. Bumps the version. |
| `config` | `MAP(VARCHAR, VARCHAR)` | No | Replacement config map (full replace, not merge). Bumps the version. |
| `access_token_name` | `VARCHAR` | No | New access token label. Bumps the version. |
| `flight_secret_names` | `LIST(VARCHAR)` | No | Replacement secret names list (full replace). Bumps the version. |
At least one of the above (besides `flight_id`) must be set.
## Return columns
`MD_UPDATE_FLIGHT` returns the updated `FlightSummary`:
| Column | Type | Description |
|---|---|---|
| `flight_id` | `UUID` | The Flight identifier. |
| `flight_name` | `VARCHAR` | The current name. |
| `schedule_cron` | `VARCHAR` | The current cron expression, or `NULL`. |
| `status` | `VARCHAR` | Schedule status. |
| `current_version` | `INTEGER` | The current version (incremented for content updates). |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | Original creation timestamp. |
| `updated_at` | `TIMESTAMP WITH TIME ZONE` | Most recent update timestamp. |
## Behavior
- **Full-replace semantics.** `config` and `flight_secret_names` are replaced, not merged. To change one entry, send the full updated map or list.
- **Carry-forward semantics.** When you patch one content field, the resulting version carries unchanged content fields forward from the previous version.
- **Empty schedule.** `schedule_cron := ''` clears the schedule; omit it to leave the existing schedule untouched.
## Examples
Rename a Flight (metadata-only, no new version):
```sql
CALL MD_UPDATE_FLIGHT(
flight_id := '',
name := 'analytics_hourly_sync'
);
```
Update the source (bumps the version):
```sql
CALL MD_UPDATE_FLIGHT(
flight_id := '',
source_code := $$
def main():
print("v2")
$$
);
```
Clear the schedule, leave everything else:
```sql
CALL MD_UPDATE_FLIGHT(
flight_id := '',
schedule_cron := ''
);
```
## Related
- [`MD_CREATE_FLIGHT`](../md-create-flight) — Create a Flight.
- [`MD_GET_FLIGHT`](../md-get-flight) — Inspect the current Flight summary.
- [`MD_FLIGHT_VERSIONS`](../md-flight-versions) — List historical versions.
- [`update_flight` MCP tool](/sql-reference/mcp/) — AI-agent equivalent (uses `md_token_name` / `md_secret_names`).
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/owned_shares
# OWNED_SHARES view
> Query the OWNED_SHARES view to see database shares you have created.
The `MD_INFORMATION_SCHEMA.OWNED_SHARES` view provides information about shares created by the current user.
:::note
Shares are **region-scoped** based on your Organization's cloud region. Each MotherDuck Organization is scoped to a single cloud region that must be chosen at Org creation when signing up.
MotherDuck is available on AWS in three regions:
- **US East (N. Virginia):** `us-east-1`
- **US West (Oregon):** `us-west-2`
- **Europe (Frankfurt):** `eu-central-1`
:::
## Schema
Querying the `MD_INFORMATION_SCHEMA.OWNED_SHARES` view will return query results that contain one row for each share created by the current user.
The `MD_INFORMATION_SCHEMA.OWNED_SHARES` view has the following schema:
| Column Name | Data Type | Value |
|-------------|-----------|-----------------------------------|
| NAME | STRING | The name of the share |
| URL | STRING | The share_url which can be used to attach the share |
| SOURCE_DB_NAME | STRING | The name of the database where this share was created from |
| SOURCE_DB_UUID | UUID | UUID of the database where this share was created from |
| ACCESS | STRING | Whether anyone (referred to as UNRESTRICTED) or only organization members (referred to as ORGANIZATION) can attach to the share by its share_url |
| GRANTS | STRUCT(username VARCHAR, access VARCHAR)[] | A list of all grants that are active for the share |
| VISIBILITY | STRING | Whether the share is DISCOVERABLE or HIDDEN |
| UPDATE | STRING | The share’s update mode (MANUAL vs. AUTOMATIC) |
| CREATED_TS | TIMESTAMP | The share’s creation time |
## Example usage
```sql
from MD_INFORMATION_SCHEMA.OWNED_SHARES;
select name, url, created_ts from MD_INFORMATION_SCHEMA.OWNED_SHARES;
```
| name | url | source_db_name |
|----------|---------------------------------------------------------|----------------|
| my_share | md:_share/my_share/2ef6b580-2445-4f4f-bce8-c13a85812464 | db1 |
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/query-syntax
# Query syntax
> DuckDB query syntax including SELECT, FROM, WHERE, GROUP BY, ORDER BY, and other clauses.
Query syntax in MotherDuck works the same as in DuckDB. See [SELECT Clause](https://duckdb.org/docs/stable/sql/query_syntax/select) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/data-types
# Data types
> Supported data types in DuckDB including numeric, string, date/time, and complex types.
Supported data types in MotherDuck works the same as in DuckDB. See [Data Types](https://duckdb.org/docs/stable/sql/data_types/overview) in the DuckDB documentation for complete details.
## VARIANT type
Starting with DuckDB 1.5, the `VARIANT` type provides a high-performance way to store and query semi-structured data. It is a strongly typed alternative to storing data as plain `JSON` or `VARCHAR` columns that delivers significantly faster reads and writes.
### How VARIANT works
When data is stored as `VARIANT`, DuckDB automatically "shreds" (decomposes) the semi-structured values into their underlying typed columns in Parquet files. This means a column of mixed JSON objects is stored as efficiently typed columnar data rather than opaque strings, enabling:
- **Columnar compression** on the underlying typed values
- **Predicate pushdown** using row group statistics
- **Faster reads** by scanning only the fields you reference in your query
### Using VARIANT
```sql
-- Create a table with a VARIANT column
CREATE TABLE events (
id INTEGER,
payload VARIANT
);
-- Insert JSON data -- it is automatically converted to VARIANT
INSERT INTO events VALUES
(1, '{"user": "alice", "action": "click", "ts": "2026-03-19T10:00:00Z"}'::VARIANT),
(2, '{"user": "bob", "action": "purchase", "amount": 42.50}'::VARIANT);
-- Query individual fields
SELECT
id,
payload->>'user' AS user_name,
payload->>'action' AS action
FROM events;
```
### VARIANT in DuckLake
[DuckLake](/integrations/file-formats/ducklake/) tables support `VARIANT` columns starting with DuckLake 0.4. This combination is particularly effective for workloads with high-volume semi-structured data because DuckLake's Parquet-backed storage takes full advantage of VARIANT shredding.
For complete details on the VARIANT type, see [VARIANT](https://duckdb.org/docs/stable/sql/data_types/variant) in the DuckDB documentation.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/enum
# Enum data type
> DuckDB enum data type for defining columns with a fixed set of string values.
Enum data types in MotherDuck works the same as in DuckDB. See [enum data type](https://duckdb.org/docs/stable/sql/data_types/enum.html) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/expressions
# Expressions
> DuckDB expression syntax including operators, CASE, subqueries, and type casts.
Supported expressions in MotherDuck works the same as in DuckDB. See [Expressions](https://duckdb.org/docs/stable/sql/expressions/overview) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/mcp/list-tables
# list_tables
> List tables and views in a MotherDuck database
List all tables and views in a MotherDuck database with their comments.
## Description
The `list_tables` tool returns all tables and views in a specified database, including their schema, type (table or view), and any comments that have been added. You can optionally filter by schema.
## Input Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `database` | string | Yes | Database name to list tables from |
| `schema` | string | No | Schema name to filter by (defaults to all schemas) |
## Output Schema
```json
{
"success": boolean,
"database": string, // Database name
"schema": string, // Schema filter used ("all" if not specified)
"tables": [ // List of tables and views (on success)
{
"schema": string, // Schema name
"name": string, // Table or view name
"type": "table" | "view", // Object type
"comment": string | null // Table/view comment if set
}
],
"tableCount": number, // Number of tables
"viewCount": number, // Number of views
"error": string // Error message (on failure)
}
```
## Example Usage
**List all tables in a database:**
```text
Show me all tables in my_database
```
The AI assistant will call the tool with:
```json
{
"database": "my_database"
}
```
**List tables in a specific schema:**
```text
What tables are in the staging schema of analytics_db?
```
```json
{
"database": "analytics_db",
"schema": "staging"
}
```
## Success Response Example
```json
{
"success": true,
"database": "my_database",
"schema": "all",
"tables": [
{
"schema": "main",
"name": "customers",
"type": "table",
"comment": "Customer master data"
},
{
"schema": "main",
"name": "orders",
"type": "table",
"comment": "Order transactions"
},
{
"schema": "main",
"name": "monthly_sales",
"type": "view",
"comment": "Aggregated monthly sales view"
},
{
"schema": "staging",
"name": "raw_events",
"type": "table",
"comment": null
}
],
"tableCount": 3,
"viewCount": 1
}
```
## Error Response Example
```json
{
"success": false,
"error": "Catalog Error: Database \"nonexistent_db\" does not exist"
}
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-create-dive
# MD_CREATE_DIVE
> Create a new Dive in your MotherDuck account.
Creates a new [Dive](/key-tasks/ai-and-motherduck/dives) in your MotherDuck account. Returns the created Dive's metadata and initial version information.
## Syntax
```sql
SELECT * FROM MD_CREATE_DIVE(
title ='My Dive',
content ='',
description ='A brief description',
api_version =1
);
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `title` | `VARCHAR` | Yes | The title of the Dive |
| `content` | `VARCHAR` | Yes | The JSX/React component code |
| `description` | `VARCHAR` | No | A brief description of the Dive |
| `api_version` | `UINTEGER` | No | API version for the Dive format. Defaults to `1`. |
## Return columns
| Column | Type | Description |
|--------|------|-------------|
| `id` | `UUID` | Unique identifier of the created Dive |
| `title` | `VARCHAR` | Dive title |
| `description` | `VARCHAR` | Dive description |
| `owner_id` | `UUID` | UUID of the Dive owner |
| `current_version` | `INTEGER` | Version number (1 for newly created Dives) |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When the Dive was created |
| `updated_at` | `TIMESTAMP WITH TIME ZONE` | When the Dive was last updated |
| `owner_name` | `VARCHAR` | Name of the Dive owner |
| `version_id` | `UUID` | UUID of the initial version |
| `version_storage_url` | `VARCHAR` | Storage URL of the version content |
| `version_description` | `VARCHAR` | Description for this version |
| `version_created_at` | `TIMESTAMP WITH TIME ZONE` | When this version was created |
| `version_api_version` | `UINTEGER` | API version used |
## Examples
Create a Dive with title and content:
```sql
SELECT id, title, current_version
FROM MD_CREATE_DIVE(
title ='Revenue Trends',
content ='import { useSQLQuery } from "@motherduck/react-sql-query";
export default function Dive() {
const { data } = useSQLQuery(`SELECT * FROM sales`);
return {JSON.stringify(data)}
;
}'
);
```
Create a Dive with a description:
```sql
SELECT *
FROM MD_CREATE_DIVE(
title ='Monthly Revenue',
description ='Line chart of revenue by month',
content =''
);
```
## Related
- [`MD_UPDATE_DIVE_CONTENT`](../md-update-dive-content) — Update a Dive's content (creates an additional version)
- [`MD_UPDATE_DIVE_METADATA`](../md-update-dive-metadata) — Update a Dive's title or description
- [`save_dive` MCP tool](/sql-reference/mcp/save-dive) — AI assistant equivalent
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/connection-management/connection-duckdb-id
# MD_CURRENT_CLIENT_CONNECTION_ID and MD_CURRENT_CLIENT_DUCKDB_ID
> Retrieve connection identifiers and DuckDB instance IDs for debugging and monitoring.
:::info
This is a preview feature. Preview features may be operationally incomplete and may offer limited backward compatibility.
:::
# MD_CURRENT_CLIENT_CONNECTION_ID and MD_CURRENT_CLIENT_DUCKDB_ID
`md_current_client_connection_id` and `md_current_client_duckdb_id` are two scalar functions that can be used to identify the current `client_connection_id` and `client_duckdb_id`.
## Syntax
```sql
SELECT md_current_client_connection_id();
SELECT md_current_client_duckdb_id();
```
## Example usage
To [interrupt](documentation/sql-reference/motherduck-sql-reference/connection-management/interrupt-connections.md) all server-side connections that are initiated by the current client DuckDB instance, we can use:
```sql
SELECT md_interrupt_server_connection(client_connection_id)
FROM md_active_server_connections()
WHERE client_duckdb_id = md_current_client_duckdb_id()
AND client_connection_id != md_current_client_connection_id();
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-delete-flight
# MD_DELETE_FLIGHT
> Delete a Flight, its versions, runs, and logs.
Deletes a [Flight](/concepts/flights). All associated `FlightVersion` records, runs, and logs are removed. Active or pending runs are cancelled.
Deleting an already-deleted Flight returns a `does not exist` error.
## Syntax
```sql
CALL MD_DELETE_FLIGHT(flight_id := '');
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight to delete. |
## Examples
```sql
CALL MD_DELETE_FLIGHT(flight_id := '80000000-0000-0000-0000-000000000001');
```
After deletion, the Flight is no longer reachable through `MD_FLIGHTS`, `MD_GET_FLIGHT`, `MD_FLIGHT_VERSIONS`, or any other Flight function.
## Related
- [`MD_FLIGHTS`](../md-flights) — List remaining Flights.
- [`delete_flight` MCP tool](/sql-reference/mcp/) — AI-agent equivalent.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/shared_with_me
# SHARED_WITH_ME view
> Query the SHARED_WITH_ME view to see database shares available to you.
The `MD_INFORMATION_SCHEMA.SHARED_WITH_ME` view provides information about all shares that the current user can attach to (excluding their own created shares).
:::note
Shares are **region-scoped** based on your Organization's cloud region. Each MotherDuck Organization is scoped to a single cloud region that must be chosen at Org creation when signing up.
MotherDuck is available on AWS in three regions:
- **US East (N. Virginia):** `us-east-1`
- **US West (Oregon):** `us-west-2`
- **Europe (Frankfurt):** `eu-central-1`
:::
## Schema
When you query the `MD_INFORMATION_SCHEMA.SHARED_WITH_ME` view, the query results contain one row for each share that the current user can discover.
The `MD_INFORMATION_SCHEMA.SHARED_WITH_ME` view has the following schema:
| Column Name | Data Type | Value |
|-------------|-----------|-----------------------------------|
| NAME | STRING | The name of the share |
| URL | STRING | The share_url which can be used to attach the share |
| CREATED_TS | TIMESTAMP | The share’s creation time |
| UPDATE | STRING | The share’s update mode (MANUAL vs. AUTOMATIC) |
| ACCESS | STRING | Whether anyone (referred to as UNRESTRICTED) or only organization members (referred to as ORGANIZATION) can attach to the share by its share_url |
## Example usage
```sql
from MD_INFORMATION_SCHEMA.SHARED_WITH_ME;
```
| name | url | created_ts |update | access |
|-----------------------------|----------------------------------------------------------------------------|------------------------|----------|-----------|
| efs_ia_benchmark | md:_share/efs_ia_benchmark/11597119-359a-4e02-8e5c-bc2b9b8c1908 | 2024-07-16 15:09:11-04 | MANUAL | ORGANIZATION |
| hf_load_test_share | md:_share/hf_load_test_share/f76062a5-f1f5-4024-987d-fc2eea48311b | 2024-07-29 09:07:33-04 | MANUAL | ORGANIZATION |
| mdw | md:_share/mdw/87be4635-fbfd-4d4b-9cae-b629842733d5 | 2024-10-16 17:04:42-04 | AUTOMATIC | ORGANIZATION |
| my_sample_share | md:_share/my_sample_share/c4ee2a30-2fb6-4cb5-b664-9030ae43ffdc | 2024-09-24 17:53:23-04 | MANUAL | ORGANIZATION |
---
Source: https://motherduck.com/docs/sql-reference/mcp/list-columns
# list_columns
> List columns of a table or view with types and comments
List all columns of a table or view with their types and comments.
## Description
The `list_columns` tool returns detailed column information for a specified table or view, including data types, nullability, and any comments. This is useful for understanding table structure before writing queries.
## Input Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `table` | string | Yes | Table or view name |
| `database` | string | Yes | Database name |
| `schema` | string | No | Schema name (defaults to `main`) |
## Output Schema
```json
{
"success": boolean,
"database": string, // Database name
"schema": string, // Schema name
"table": string, // Table or view name
"objectType": "table" | "view", // Whether it's a table or view
"columns": [ // List of columns (on success)
{
"name": string, // Column name
"type": string, // Data type
"nullable": boolean, // Whether nulls are allowed
"comment": string | null // Column comment if set
}
],
"columnCount": number, // Number of columns
"error": string // Error message (on failure)
}
```
## Example Usage
**Get columns for a table:**
```text
What columns does the customers table have in my_database?
```
The AI assistant will call the tool with:
```json
{
"table": "customers",
"database": "my_database"
}
```
**Get columns in a specific schema:**
```text
Show me the schema of staging.raw_events in analytics_db
```
```json
{
"table": "raw_events",
"database": "analytics_db",
"schema": "staging"
}
```
## Success Response Example
```json
{
"success": true,
"database": "my_database",
"schema": "main",
"table": "customers",
"objectType": "table",
"columns": [
{
"name": "id",
"type": "INTEGER",
"nullable": false,
"comment": "Primary key"
},
{
"name": "email",
"type": "VARCHAR",
"nullable": false,
"comment": "Customer email address"
},
{
"name": "name",
"type": "VARCHAR",
"nullable": true,
"comment": "Full name"
},
{
"name": "created_at",
"type": "TIMESTAMP",
"nullable": false,
"comment": null
},
{
"name": "metadata",
"type": "JSON",
"nullable": true,
"comment": "Additional customer attributes"
}
],
"columnCount": 5
}
```
## Error Response Example
```json
{
"success": false,
"error": "Catalog Error: Table \"nonexistent_table\" does not exist"
}
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-get-flight
# MD_GET_FLIGHT
> Fetch the summary metadata for a single Flight.
Returns the `FlightSummary` fields for a single [Flight](/concepts/flights). For version-specific content (source code, requirements, config), use [`MD_GET_FLIGHT_VERSION`](../md-get-flight-version).
## Syntax
```sql
SELECT * FROM MD_GET_FLIGHT(flight_id := '');
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight. |
## Return columns
| Column | Type | Description |
|---|---|---|
| `flight_id` | `UUID` | The Flight identifier. |
| `flight_name` | `VARCHAR` | The current name. |
| `schedule_cron` | `VARCHAR` | The current cron expression, or `NULL` for on-demand only. |
| `status` | `VARCHAR` | Schedule status (for example, `JOB_STATUS_ACTIVE`). |
| `current_version` | `INTEGER` | The latest version number. |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | Creation timestamp. |
| `updated_at` | `TIMESTAMP WITH TIME ZONE` | Last update timestamp. |
## Examples
```sql
SELECT flight_id, flight_name, schedule_cron, current_version
FROM MD_GET_FLIGHT(flight_id := '80000000-0000-0000-0000-000000000001');
```
## Related
- [`MD_FLIGHTS`](../md-flights) — List all Flights.
- [`MD_GET_FLIGHT_VERSION`](../md-get-flight-version) — Fetch a specific version's content.
- [`get_flight` MCP tool](/sql-reference/mcp/) — AI-agent equivalent.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/connection-management/last-query-id
# MD_LAST_QUERY_ID
> Use MD_LAST_QUERY_ID() to get the UUID of the most recent query sent to MotherDuck.
`MD_LAST_QUERY_ID()` is a scalar function that returns the UUID of the most recent query sent to the MotherDuck server from the current DuckDB [connection](/key-tasks/authenticating-and-connecting-to-motherduck/connecting-to-motherduck/#create-a-connection). This is the same `QUERY_ID` that appears in the [`QUERY_HISTORY`](../md_information_schema/query_history.md) and [`RECENT_QUERIES`](../md_information_schema/recent_queries.md) views.
The function returns `NULL` if no query has been sent to the server yet on the current connection.
## Syntax
```sql
SELECT MD_LAST_QUERY_ID();
```
## Return type
`UUID`: the unique identifier of the last query, or `NULL` if no server-side query has been run.
## Example usage
### Get the ID of your last query
```sql
SELECT MD_LAST_QUERY_ID();
```
### Look up details for last query from this connection in the query history
```sql
SELECT *
FROM MD_INFORMATION_SCHEMA.QUERY_HISTORY
WHERE QUERY_ID = MD_LAST_QUERY_ID();
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-update-dive-metadata
# MD_UPDATE_DIVE_METADATA
> Update a Dive's title or description without creating a new version.
Updates the title and/or description of an existing [Dive](/key-tasks/ai-and-motherduck/dives). This does not create an additional version—only the metadata is changed.
## Syntax
```sql
SELECT * FROM MD_UPDATE_DIVE_METADATA(
id ='your-dive-uuid'::UUID,
title ='New Title',
description ='New description'
);
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | `UUID` | Yes | The unique identifier of the Dive to update |
| `title` | `VARCHAR` | No | New title for the Dive |
| `description` | `VARCHAR` | No | New description for the Dive |
At least one of `title` or `description` should be provided.
## Return columns
| Column | Type | Description |
|--------|------|-------------|
| `id` | `UUID` | Unique identifier of the Dive |
| `title` | `VARCHAR` | Updated Dive title |
| `description` | `VARCHAR` | Updated Dive description |
| `owner_id` | `UUID` | UUID of the Dive owner |
| `current_version` | `INTEGER` | Current version number (unchanged) |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When the Dive was created |
| `updated_at` | `TIMESTAMP WITH TIME ZONE` | When the Dive was last updated |
| `owner_name` | `VARCHAR` | Name of the Dive owner |
## Examples
Update a Dive's title:
```sql
SELECT id, title, updated_at
FROM MD_UPDATE_DIVE_METADATA(
id ='a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID,
title ='Q1 Revenue Dashboard'
);
```
Update both title and description:
```sql
SELECT *
FROM MD_UPDATE_DIVE_METADATA(
id ='a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID,
title ='Q1 Revenue Dashboard',
description ='Revenue breakdown by region for Q1 2025'
);
```
## Errors
Returns an error if the Dive does not exist.
## Related
- [`MD_UPDATE_DIVE_CONTENT`](../md-update-dive-content) — Update a Dive's content (creates an additional version)
- [`update_dive` MCP tool](/sql-reference/mcp/update-dive) — AI assistant equivalent
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/functions
# Functions
> Built-in scalar functions in DuckDB for string manipulation, math, dates, and more.
Supported functions in MotherDuck works the same as in DuckDB. See [Functions](https://duckdb.org/docs/stable/sql/functions/overview) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-get-flight-version
# MD_GET_FLIGHT_VERSION
> Fetch the full content (source, requirements, config, token, secrets) for a specific Flight version.
Returns the full content of a single `FlightVersion`. Use this when you need the source code or requirements that ran for a specific historical run.
## Syntax
```sql
SELECT * FROM MD_GET_FLIGHT_VERSION(
flight_id := '',
version_number :=
);
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight. |
| `version_number` | `INTEGER` | Yes | The version to fetch. Version numbers start at `1` and increment on each content update. |
## Return columns
| Column | Type | Description |
|---|---|---|
| `flight_version` | `INTEGER` | The version number. |
| `source_code` | `VARCHAR` | The Python source as of this version. |
| `requirements_txt` | `VARCHAR` | The `requirements.txt` contents as of this version. |
| `access_token_name` | `VARCHAR` | The access token label as of this version. |
| `flight_secret_names` | `LIST(VARCHAR)` | The secret names list as of this version. |
| `config` | `MAP(VARCHAR, VARCHAR)` | The config map as of this version. |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When this version was created. |
## Behavior
Content fields that are not patched in an update **carry forward** from the previous version. For example, a `source_code`-only update on version 2 produces a version 3 where `requirements_txt`, `config`, `access_token_name`, and `flight_secret_names` match version 2 but `source_code` is the new value.
## Examples
```sql
SELECT flight_version, source_code, requirements_txt
FROM MD_GET_FLIGHT_VERSION(
flight_id := '80000000-0000-0000-0000-000000000001',
version_number := 1
);
```
Cross-reference a run's version to read the exact source it executed:
```sql
WITH r AS (
SELECT flight_version
FROM MD_FLIGHT_RUNS(flight_id := '')
WHERE run_number =
)
SELECT v.source_code, v.requirements_txt
FROM r, MD_GET_FLIGHT_VERSION(flight_id := '', version_number := r.flight_version) v;
```
## Related
- [`MD_FLIGHT_VERSIONS`](../md-flight-versions) — List all versions for a Flight.
- [`MD_GET_FLIGHT`](../md-get-flight) — Fetch current summary metadata only.
- [`get_flight` MCP tool](/sql-reference/mcp/) — AI-agent equivalent (pass a `version` argument).
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-update-dive-content
# MD_UPDATE_DIVE_CONTENT
> Update a Dive's React component code, creating a new version.
Updates the content of an existing [Dive](/key-tasks/ai-and-motherduck/dives), creating an additional version. Each call increments the version number. Previous versions remain accessible through [`MD_GET_DIVE_VERSION`](../md-get-dive-version).
## Syntax
```sql
SELECT * FROM MD_UPDATE_DIVE_CONTENT(
id ='your-dive-uuid'::UUID,
content =''
);
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | `UUID` | Yes | The unique identifier of the Dive to update |
| `content` | `VARCHAR` | Yes | The new JSX/React component code |
| `description` | `VARCHAR` | No | Version description or commit message |
| `api_version` | `UINTEGER` | No | API version for the Dive format. Defaults to `1`. |
## Return columns
| Column | Type | Description |
|--------|------|-------------|
| `id` | `UUID` | UUID of the created version (not the Dive UUID) |
| `version` | `UINTEGER` | Created version number (0-based) |
| `storage_url` | `VARCHAR` | Storage URL of the version content |
| `description` | `VARCHAR` | Version description |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When this version was created |
| `api_version` | `UINTEGER` | API version used |
## Examples
Update a Dive's content:
```sql
SELECT version, created_at
FROM MD_UPDATE_DIVE_CONTENT(
id ='a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID,
content =''
);
```
Update with a version description:
```sql
SELECT *
FROM MD_UPDATE_DIVE_CONTENT(
id ='a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID,
content ='',
description ='Added region filter'
);
```
## Errors
Returns an error if the Dive does not exist.
## Related
- [`MD_UPDATE_DIVE_METADATA`](../md-update-dive-metadata) — Update title or description without creating an additional version
- [`MD_LIST_DIVE_VERSIONS`](../md-list-dive-versions) — List all versions of a Dive
- [`update_dive` MCP tool](/sql-reference/mcp/update-dive) — AI assistant equivalent
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/database_size
# Database Size
> Get storage size information for MotherDuck databases using PRAGMA database_size.
Database size can be fetched with `PRAGMA database_size;`. It contains attributes to allow insights into the sizes of MotherDuck databases.
## Alternative invocations
This Pragma can also be invoked as a tabular function with:
- `FROM pragma_database_size();`
## Schema
`PRAGMA database_size` has the following schema:
| Column Name | Data Type | Value |
|-----------------------|-------------|-----------------------------------|
| database_name | VARCHAR | name of the database |
| database_size | VARCHAR | database size in 1000 byte increments (i.e. Kilobytes) |
| block_size | BIGINT | _not currently returned_ |
| used_blocks | BIGINT | _not currently returned_ |
| total_blocks | BIGINT | _not currently returned_ |
| free_blocks | BIGINT | _not currently returned_ |
| wal_size | VARCHAR | _not currently returned_ |
| memory_usage | VARCHAR | _not currently returned_ |
| memory_limit | VARCHAR | _not currently returned_ |
## Example Usage
```sql
PRAGMA database_size;
```
Example result:
| database_name | database_size | block_size | used_blocks | total_blocks | free_blocks | wal_size | memory_usage | memory_limit |
|---------------|---------------|------------|-------------|--------------|-------------|----------|--------------|--------------|
| my_db | 153.9 GiB | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| another_database | 3.1 TiB | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
In some cases, you may want to filter the dataset, in which case you can use a tabular function in your `FROM` clause. An example is shown below:
```sql
SELECT *
FROM pragma_database_size()
WHERE database_name = 'my_db'
```
---
Source: https://motherduck.com/docs/sql-reference/mcp/search-catalog
# search_catalog
> Fuzzy search across databases, schemas, tables, columns, and shares
Search the catalog for databases, schemas, tables, columns, and shares using fuzzy matching.
## Description
The `search_catalog` tool performs fuzzy search across your entire MotherDuck catalog. It finds matching objects by name using partial matching, supporting underscores, dots, and multi-word queries. This is useful for discovering available data when you don't know exact names.
The search uses Jaro-Winkler similarity scoring and returns results ranked by relevance. Results are limited per category to provide a balanced view across different object types.
## Input Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | Search term to find in object names (supports partial matching, underscores, dots) |
| `object_types` | string[] | No | Filter results to specific types: `"database"`, `"schema"`, `"table"`, `"column"`, `"share"` |
## Output Schema
```json
{
"success": boolean,
"query": string, // Search query used
"resultCount": number, // Total results found
"results": [ // Search results (on success)
{
"type": "database" | "schema" | "table" | "column" | "share",
"name": string, // Object name
"fullyQualifiedName": string, // Full path (e.g., "db.schema.table.column")
"database": string | null, // Database (null for shares)
"schema": string | null, // Schema (null for databases/shares)
"table": string | null, // Table (only for columns)
"dataType": string | null, // Data type (columns) or URL (shares)
"comment": string | null, // Object comment if set
"relevanceScore": number // Match score 0-1 (higher is better)
}
],
"error": string, // Error message (on failure)
"errorType": string // Error type (on failure)
}
```
## Result Limits
Results are limited per object type to provide balanced coverage:
- Shares: 10 results
- Columns: 40 results
- Tables: 30 results
- Schemas: 20 results
- Databases: 20 results
Maximum total results: 100
## Example Usage
**Search for tables with "sales" in the name:**
```text
Find all tables related to sales data
```
The AI assistant will call the tool with:
```json
{
"query": "sales"
}
```
**Search only for columns:**
```text
Find columns containing "email"
```
```json
{
"query": "email",
"object_types": ["column"]
}
```
**Search with qualified name:**
```text
Find anything matching analytics.events
```
```json
{
"query": "analytics.events"
}
```
## Success Response Example
```json
{
"success": true,
"query": "sales",
"resultCount": 8,
"results": [
{
"type": "table",
"name": "sales_data",
"fullyQualifiedName": "analytics.main.sales_data",
"database": "analytics",
"schema": "main",
"table": null,
"dataType": null,
"comment": "Daily sales transactions",
"relevanceScore": 0.95
},
{
"type": "table",
"name": "monthly_sales",
"fullyQualifiedName": "analytics.main.monthly_sales",
"database": "analytics",
"schema": "main",
"table": null,
"dataType": null,
"comment": null,
"relevanceScore": 0.89
},
{
"type": "column",
"name": "total_sales",
"fullyQualifiedName": "analytics.main.revenue.total_sales",
"database": "analytics",
"schema": "main",
"table": "revenue",
"dataType": "DECIMAL(18,2)",
"comment": "Total sales amount",
"relevanceScore": 0.87
},
{
"type": "share",
"name": "regional_sales_share",
"fullyQualifiedName": "regional_sales_share",
"database": "regional_sales_share",
"schema": null,
"table": null,
"dataType": "md:_share/org123/regional_sales_share",
"comment": null,
"relevanceScore": 0.82
}
]
}
```
## Error Response Example
```json
{
"success": false,
"error": "Search query cannot be empty",
"errorType": "ValidationError"
}
```
---
Source: https://motherduck.com/docs/sql-reference/wasm-client
# MotherDuck Wasm client
> Connect browser applications to MotherDuck using the DuckDB WebAssembly client and Hybrid Query Execution.
[MotherDuck](https://motherduck.com/) is a managed DuckDB-in-the-cloud service.
[DuckDB Wasm](https://github.com/duckdb/duckdb-wasm) brings DuckDB to every browser thanks to WebAssembly.
The MotherDuck Wasm Client library enables using MotherDuck through DuckDB Wasm in your own browser applications.
## Examples
Example projects and live demos can be found in the [wasm-client GitHub repository](https://github.com/motherduckdb/wasm-client).
## DuckDB version support
- Each version of the MotherDuck Wasm Client library uses a specific version of DuckDB, as indicated by the package version. Check `pragma version` to see which DuckDB version is in use.
## Installation
`npm install @motherduck/wasm-client`
## Dependencies
The MotherDuck Wasm Client library depends on `apache-arrow` as a peer dependency.
If you use `npm` version 7 or later to install `@motherduck/wasm-client`, then `apache-arrow` will automatically be installed, if it is not already.
If you already have `apache-arrow` installed, then `@motherduck/wasm-client` will use it, as long as it is a compatible version (`^17.0.0` at the time of this writing).
Optionally, you can use a variant of `@motherduck/wasm-client` that bundles `apache-arrow` instead of relying on it as a peer dependency.
Don't use this option if you are using `apache-arrow` elsewhere in your application, because different copies of this library don't work together.
To use this version, change your imports to:
```ts
import '@motherduck/wasm-client/with-arrow';
```
instead of:
```ts
import '@motherduck/wasm-client';
```
## Usage
The MotherDuck Wasm Client library is written in TypeScript and exposes full TypeScript type definitions. These instructions assume you are using it from TypeScript.
Once you have installed `@motherduck/wasm-client`, you can import the main class, `MDConnection`, as follows:
```ts
import { MDConnection } from '@motherduck/wasm-client';
```
### Creating connections
To create a `connection` to a MotherDuck-connected DuckDB instance, call the `create` static method:
```ts
const connection = MDConnection.create({
mdToken: token
});
```
The `mdToken` parameter is required and should be set to a valid MotherDuck access token. You can create a MotherDuck access token in the MotherDuck UI. For more information, see [Authenticating to MotherDuck](/key-tasks/authenticating-and-connecting-to-motherduck/authenticating-to-motherduck#authentication-using-an-access-token).
The `create` call returns immediately, but starts the process of loading the DuckDB Wasm assets from `https://app.motherduck.com` and starting the DuckDB Wasm worker.
This initialization process happens asynchronously. Any query evaluated before initialization is complete will be queued.
To determine whether initialization is complete, call the `isInitialized` method, which returns a promise resolving to `true` when DuckDB Wasm is initialized:
```ts
await connection.isInitialized();
```
Multiple connections can be created. Connections share a DuckDB Wasm instance, so creating subsequent connections will not repeat the initialization process.
Queries evaluated on different connections happen concurrently; queries evaluated on the same connection are queued sequentially.
### Evaluating queries
To evaluate a query, call the `evaluateQuery` method on the `connection` object:
```ts
try {
const result = await connection.evaluateQuery(sql);
console.log('query result', result);
} catch (err) {
console.log('query failed', err);
}
```
The `evaluateQuery` method returns a [promise](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises) for the result. In an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function), you can use the `await` syntax as above. Or, you can use the `then` and/or `catch` methods:
```ts
connection.evaluateQuery(sql).then((result) => {
console.log('query result', result);
}).catch((reason) => {
console.log('query failed', reason);
});
```
See [Results](#results) below for the structure of the result object.
### Prepared statements
To create a [prepared](https://duckdb.org/docs/api/c/prepared) [statement](https://duckdb.org/docs/api/wasm/query#prepared-statements) for later evaluation, use the `prepareQuery` method:
```ts
const prepareResult = await this.prepareQuery('SELECT v + ? FROM generate_series(0, 10000) AS t(v);');
```
This returns an [AsyncPreparedStatement](https://shell.duckdb.org/docs/classes/index.AsyncPreparedStatement.html), which can be evaluated later using the `send` method:
```ts
const arrowStream = await prepareResult.send(234);
```
Note: The `query` method of the AsyncPreparedStatement should not be used, because it can lead to deadlock when combined with the MotherDuck extension.
To immediately evaluate a prepared statement, call the `evaluatePreparedStatement` method:
```ts
const result = await connection.evaluatePreparedStatement('SELECT v + ? FROM generate_series(0, 10000) AS t(v);', [234]);
```
This returns a materialized result, as described in [Results](#results) below.
### Canceling queries
To evaluate a query that can be canceled, use the `enqueueQuery` and `evaluateQueuedQuery` methods:
```ts
const queryId = connection.enqueueQuery(sql);
const result = await connection.evaluateQueuedQuery(queryId);
```
To cancel a query evaluated in this fashion, use the `cancelQuery` method, passing the `queryId` returned by `enqueueQuery`:
```ts
const queryWasCanceled = await connection.cancelQuery(queryId);
```
The `cancelQuery` method returns a promise for a boolean indicating whether the query was successfully canceled.
The result promise of a canceled query will be rejected with and error message. The `cancelQuery` method takes an optional second argument for controlling this message:
```ts
const queryWasCanceled = await connection.cancelQuery(queryId, 'custom error message');
```
### Streaming results
The query methods above return fully materialized results. To evaluate a query and return a stream of results, use `evaluateStreamingQuery` or `evaluateStreamingPreparedStatement`:
```ts
const result = await connection.evaluateStreamingQuery(sql);
```
See [Results](#results) below for the structure of the result object.
### Error handling
The query result promises returned by `evaluateQuery`, `evaluatePreparedStatement`, `evaluateQueuedQuery`, and `evaluateStreamingQuery` will be rejected in the case of an error.
For convenience, "safe" variants of these three method are provided that catch this error and always resolve to a value indicating success or failure. For example:
```ts
const result = await connection.safeEvaluateQuery(sql);
if (result.status === 'success') {
console.log('rows', result.rows);
} else {
console.log('error', result.err);
}
```
### Results
A successful query result may either be fully materialized, or it may contain a stream.
Use the `type` property of the result object, which is either `'materialized'` or `'streaming'`, to distinguish these.
#### Materialized results
A materialized result contains a `data` property, which provides several methods for getting the results.
The number of columns and rows in the result are available through the `columnCount` and `rowCount` properties of `data`.
Column names and types can be retrieved using the `columnName(columnIndex)` and `columnType(columnIndex)` methods.
Individual values can be accessed using the `value(columnIndex, rowIndex)` method. See below for details about the forms values can take.
Several convenience methods also simplify common access patterns; see `singleValue()`, `columnNames()`, `deduplicatedColumnNames()`, and `toRows()`.
The `toRows()` method is especially useful in many cases. It returns the result as an array of row objects.
Each row object has one property per column, named after that column. (Multiple columns with the same name are deduplicated with suffixes.)
The type of each column property of a row object depends on the type of the corresponding column in DuckDB.
Many values are converted to a JavaScript primitive type, such as `boolean`, `number`, or `string`.
Some numeric values too large to fit in a JavaScript `number` (e.g a DuckDB [BIGINT](https://duckdb.org/docs/sql/data_types/numeric#integer-types)) are converted to a JavaScript `bigint`.
Some DuckDB types, such as [DATE](https://duckdb.org/docs/sql/data_types/date), [TIME](https://duckdb.org/docs/sql/data_types/time), [TIMESTAMP](https://duckdb.org/docs/sql/data_types/timestamp), and [DECIMAL](https://duckdb.org/docs/sql/data_types/numeric#fixed-point-decimals), are converted to JavaScript objects implementing an interface specific to that type. Nested types such as DuckDB [LIST](https://duckdb.org/docs/sql/data_types/list), [MAP](https://duckdb.org/docs/sql/data_types/map), and [STRUCT](https://duckdb.org/docs/sql/data_types/struct) are also exposed through special JavaScript objects.
These objects all implement `toString` to return a string representation. For primitive, this representation is identical to DuckDB's string conversion (e.g. using [CAST](https://duckdb.org/docs/sql/expressions/cast.html) to VARCHAR). For nested types, the representation is equivalent to the syntax used to construct these types.
They also have properties exposing the underlying value. For example, the object for a DuckDB TIME has a `microseconds` property (of type `bigint`). See the TypeScript type definitions for details.
Note that these result types differ from those returned by DuckDB Wasm without the MotherDuck Wasm Client library. The MotherDuck Wasm Client library implements custom conversion logic to preserve the full range of some types.
#### Streaming results
A streaming result contains three ways to consume the results, `arrowStream`, `dataStream`, and `dataReader`. The first two (`arrowStream` and `dataStream`) implement the async iterator protocol, and return items representing batches of rows, but return different kinds of batch objects. Batches correspond to DuckDB DataChunks, which are no more than 2048 rows. The third (`dataReader`) wraps `dataStream` and makes consuming multiple batches easier.
The `dataStream` iterator returns a sequence of `data` objects, each of which implements the same interface as the `data` property of a materialized query result, described above.
The `dataReader` implements the same `data` interface, but also adds useful methods such as `readAll` and `readUntil`, which can be used to read at least a given number of rows, possibly across multiple batches.
The `arrowStream` property provides access to the underlying Arrow RecordBatch stream reader. This can be useful if you need the underlying Arrow representation. Also, this stream has convenience methods such as `readAll` to materialize all batches.
Note, however, that Arrow performs sometimes lossy conversion of the underlying data to JavaScript types for certain DuckDB types, especially dates, times, and decimals.
Also, converting Arrow values to strings will not always match DuckDB's string conversion.
Note that results of remote queries are not streamed end-to-end yet.
Results of remote queries are fully materialized on the client upstream of this API.
So the first batch will not be returned from this API until all results have been received by the client.
End-to-end streaming of remote query results is on our roadmap.
### DuckDB Wasm API
To access the underlying DuckDB Wasm instance, use the `getAsyncDuckDb` function. Note that this function returns (a Promise to) a singleton instance of DuckDB Wasm also used by the MotherDuck Wasm Client.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/aggregate-functions
# Aggregate functions
> DuckDB aggregate functions like SUM, COUNT, AVG, and statistical functions.
Aggregate functions in MotherDuck works the same as in DuckDB. See [Aggregate Functions](https://duckdb.org/docs/stable/sql/aggregates) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-delete-dive
# MD_DELETE_DIVE
> Permanently delete a Dive by ID.
Permanently deletes a [Dive](/key-tasks/ai-and-motherduck/dives) and all its versions. This action cannot be undone.
## Syntax
```sql
SELECT * FROM MD_DELETE_DIVE(id = 'your-dive-uuid'::UUID);
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | `UUID` | Yes | The unique identifier of the Dive to delete |
## Return columns
| Column | Type | Description |
|--------|------|-------------|
| `success` | `BOOLEAN` | `true` if the Dive was deleted |
## Examples
Delete a Dive:
```sql
SELECT * FROM MD_DELETE_DIVE(id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID);
```
## Errors
Returns an error if the Dive does not exist.
## Related
- [`MD_LIST_DIVES`](../md-list-dives) — List Dives to find the ID
- [`delete_dive` MCP tool](/sql-reference/mcp/delete-dive) — AI assistant equivalent
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-flights
# MD_FLIGHTS
> List the Flights you own with summary metadata.
Returns the summary metadata for every [Flight](/concepts/flights) owned by the caller. Use the optional `LIMIT` and `OFFSET` parameters to page through large result sets.
## Syntax
```sql
SELECT * FROM MD_FLIGHTS(
"LIMIT" := ,
"OFFSET" :=
);
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `LIMIT` | `BIGINT` | No | Maximum number of Flights to return. |
| `OFFSET` | `BIGINT` | No | Skip this many Flights before returning. |
`LIMIT` and `OFFSET` collide with SQL keywords and must be quoted with double quotes when passed as named arguments.
## Return columns
| Column | Type | Description |
|---|---|---|
| `flight_id` | `UUID` | Flight identifier. |
| `flight_name` | `VARCHAR` | The Flight name. |
| `schedule_cron` | `VARCHAR` | Cron expression, or `NULL` for on-demand. |
| `status` | `VARCHAR` | Schedule status (for example, `JOB_STATUS_ACTIVE`). |
| `current_version` | `INTEGER` | Latest version number. |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | Creation timestamp. |
| `updated_at` | `TIMESTAMP WITH TIME ZONE` | Last update timestamp. |
Version-specific content (`source_code`, `requirements_txt`, `config`) is not on this row; query [`MD_GET_FLIGHT_VERSION`](../md-get-flight-version) when you need it.
## Examples
List all Flights:
```sql
SELECT flight_id, flight_name, schedule_cron, current_version
FROM MD_FLIGHTS();
```
Page through results:
```sql
SELECT flight_name
FROM MD_FLIGHTS("LIMIT" := 50, "OFFSET" := 100);
```
Find Flights with active schedules:
```sql
SELECT flight_name, schedule_cron
FROM MD_FLIGHTS()
WHERE schedule_cron IS NOT NULL;
```
## Related
- [`MD_GET_FLIGHT`](../md-get-flight) — Fetch a single Flight's summary.
- [`MD_FLIGHT_RUNS`](../md-flight-runs) — List a Flight's runs.
- [`list_flights` MCP tool](/sql-reference/mcp/) — AI-agent equivalent (supports a `keywords` filter).
---
Source: https://motherduck.com/docs/sql-reference/postgres-endpoint
# Postgres Endpoint
> Connection parameters, SSL options, session settings, and limitations for the MotherDuck Postgres wire protocol endpoint
MotherDuck's Postgres endpoint lets you query your databases using any client that speaks the [PostgreSQL wire protocol](https://www.postgresql.org/docs/current/protocol.html) — without installing a DuckDB client library.
For a how-to guide on connecting, see [Connect through the Postgres endpoint](/key-tasks/authenticating-and-connecting-to-motherduck/postgres-endpoint).
## Connection parameters
| Parameter | Value |
|-----------|-------|
| **Host** | `pg.-aws.motherduck.com` (for example, `pg.us-east-1-aws.motherduck.com`) |
| **Port** | `5432` |
| **Database** | `md:` for your default database, or a specific database name |
| **User** | `postgres` |
| **Password** | Your [MotherDuck access token](/key-tasks/authenticating-and-connecting-to-motherduck/authenticating-to-motherduck) |
## Connection string formats
```sh
# psql
PGPASSWORD=$MOTHERDUCK_TOKEN psql -h pg.us-east-1-aws.motherduck.com -p 5432 -U postgres "dbname=md: sslmode=verify-full sslrootcert=system"
```
```sh
# libpq URI
postgresql://postgres:$MOTHERDUCK_TOKEN@pg.us-east-1-aws.motherduck.com:5432/md:?sslmode=verify-full&sslrootcert=system
```
```sh
# DSN keyword/value
host=pg.us-east-1-aws.motherduck.com port=5432 dbname=md: user=postgres password=$MOTHERDUCK_TOKEN sslmode=verify-full sslrootcert=system
```
Use `md:` as the database name to connect to your default database. You can also specify a database by name, for example `sample_data`.
## SSL and certificate verification
The Postgres endpoint requires encrypted connections. For the best security, verify the server certificate.
### SSL modes
| Mode | Encryption | Server verification | Recommendation |
|------|-----------|-------------------|----------------|
| `verify-full` | Yes | Yes | Recommended for production |
| `require` | Yes | No | Fallback if certificate verification is not possible |
### Use the system certificate store (recommended)
Set `sslmode=verify-full` with `sslrootcert=system` to use your operating system's trusted root certificates. This is supported in libpq 16 and later, and in libraries that wrap libpq (like psycopg v3).
```sh
sslmode=verify-full sslrootcert=system
```
### Use a specific certificate file
If your client doesn't support `sslrootcert=system`, download the [ISRG Root X1](https://letsencrypt.org/certs/isrgrootx1.pem) certificate from Let's Encrypt and point your client to it:
```sh
sslmode=verify-full sslrootcert=/path/to/isrgrootx1.pem
```
### Library-specific SSL handling
Some libraries have their own SSL implementations that don't use libpq directly:
| Library | SSL behavior | Workaround |
|---------|-------------|------------|
| **psycopg (v3)** | Wraps libpq — `sslrootcert=system` works | None needed |
| **psycopg2** | Bundles its own OpenSSL — `sslrootcert=system` is not supported | Use `sslrootcert=certifi.where()` with the `certifi` package |
| **PostgreSQL JDBC** | Looks for `~/.postgresql/root.crt` by default | Set `sslfactory=org.postgresql.ssl.DefaultJavaSSLFactory` to use JVM truststore |
| **node-postgres (`pg`)** | Reads `sslrootcert` as a file path — `system` causes `ENOENT` | Use config object: `ssl: { rejectUnauthorized: true }` |
| **Cloudflare Workers (`pg-cloudflare`)** | TLS handled by the Workers runtime at the socket level — application-level verification settings are not exposed through the `pg` client | Use `?sslmode=require` in the connection string |
## Session options
You can pass DuckDB session options using the `PGOPTIONS` environment variable:
```bash
PGOPTIONS="--attach_mode=single --session_name=pg-using-options" psql -h pg.us-east-1-aws.motherduck.com -p 5432 -U postgres md:
```
| Option | Description |
|--------|-------------|
| `--attach_mode=single` | Only attach the specified database. Recommended when connecting from IDEs or BI tools to avoid seeing objects from other databases. See [Attach Modes](/key-tasks/authenticating-and-connecting-to-motherduck/attach-modes/). |
## Supported features and limitations
### DuckDB SQL, not PostgreSQL
The Postgres endpoint is a PostgreSQL-wire interface to MotherDuck. You write **DuckDB SQL**, not PostgreSQL SQL.
### Best suited for
- query execution against MotherDuck tables
- DDL and DML that run entirely inside MotherDuck
- metadata inspection
- server-side reads from remote storage
### Use a DuckDB client path instead when you need
- local-file workflows such as local-file `COPY`, `EXPORT DATABASE`, or `IMPORT DATABASE`
- local or in-memory attachments such as `ATTACH ':memory:'` or `ATTACH '/path/to/file.duckdb'`
- local execution paths such as `MD_RUN=LOCAL`
- extension-based workflows such as `INSTALL`, `LOAD`, or cloud-storage `CREATE SECRET`
- DuckDB-client session features such as `CREATE RESULT`
### Compatibility notes
- PostgreSQL-specific features such as `pg_*` functions, PostgreSQL indexes, sequences, and stored procedures are not supported.
- Transaction semantics follow the DuckDB model. Nested transactions are not supported.
- Some commands are further restricted in PG server mode. For example, `SET threads` and `CREATE TEMP TABLE` are not supported through the Postgres endpoint.
### Operational limitations
- **Configuration settings are restricted.** The Postgres endpoint connects in [SaaS mode](/key-tasks/authenticating-and-connecting-to-motherduck/authenticating-to-motherduck#authentication-using-saas-mode), a MotherDuck mode that blocks most DuckDB configuration changes after connecting and disables installing or loading extensions. Avoid using `SET` statements in your client code.
- **IDE schema browsers may show extra objects.** Some IDEs display tables from all attached databases. Use `attach_mode=single` to scope the catalog to your target database.
- **Use connection pooling in production.** Each connection consumes server resources. For applications that need many connections, use a connection pooler (for example, [Cloudflare Hyperdrive](https://developers.cloudflare.com/hyperdrive/), PgBouncer) rather than rapidly opening and closing connections.
- **Third-party tool support is in early stages.** Check the [Integrations](/integrations/) page for tools that support the Postgres endpoint.
---
Source: https://motherduck.com/docs/sql-reference/mcp/query
# query
> Execute SQL queries against MotherDuck databases
Execute **read-only** SQL queries against MotherDuck databases.
## Description
The `query` tool executes SQL queries against your MotherDuck databases. For cross-database queries, use fully qualified names: `database.schema.table` (or `database.table` for the main schema).
`query` is for read-only SQL. Operations that modify data, schema, or account settings, or trigger side effects, are rejected. For SQL that can change data or schema, use [`query_rw`](/sql-reference/mcp/query-rw/).
## Input Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `database` | string | Yes | Database name to query |
| `sql` | string | Yes | DuckDB SQL query to execute |
## Output Schema
```json
{
"success": boolean,
"columns": string[], // Column names (on success)
"columnTypes": string[], // Column types (on success)
"rows": any[][], // Query results (on success)
"rowCount": number, // Number of rows returned (on success)
"error": string, // Error message (on failure)
"errorType": string // Error type (on failure)
}
```
## Limits
- **Result limit:** Maximum 2,048 rows and 50,000 characters. Results exceeding these limits will be truncated with a truncation message.
- **Query timeout:** 55 seconds, to stay within common client timeouts. Queries exceeding this limit will be cancelled server-side and the tool will respond with an error message.
## Example Usage
**Simple query:**
```text
Query the top 5 customers by total orders from my_database
```
The AI assistant will call the tool with:
```json
{
"database": "my_database",
"sql": "SELECT customer_name, COUNT(*) as order_count FROM orders GROUP BY customer_name ORDER BY order_count DESC LIMIT 5"
}
```
**Cross-database query:**
```text
Join the users table from auth_db with orders from sales_db
```
```json
{
"database": "auth_db",
"sql": "SELECT u.name, o.order_id, o.amount FROM auth_db.main.users u JOIN sales_db.main.orders o ON u.id = o.user_id LIMIT 100"
}
```
## Success Response Example
```json
{
"success": true,
"columns": ["customer_name", "order_count"],
"columnTypes": ["VARCHAR", "BIGINT"],
"rows": [
["Acme Corp", 150],
["TechStart Inc", 89],
["Global Services", 72]
],
"rowCount": 3
}
```
## Error Response Example
```json
{
"success": false,
"error": "Query is not read-only",
"errorType": "ForbiddenQueryError"
}
```
---
Source: https://motherduck.com/docs/sql-reference/mcp/query-rw
# query_rw
> Execute SQL queries that can modify data or schema in MotherDuck
Execute SQL queries that can modify data or schema in MotherDuck.
## Description
The `query_rw` tool executes SQL against your MotherDuck databases, including operations that change data or schema. For cross-database queries, use fully qualified names: `database.schema.table` (or `database.table` for the main schema).
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `database` | string | No | Database context for the query. Required when the statement targets database objects. Optional for account-level operations. |
| `sql` | string | Yes | DuckDB SQL statement to execute |
## Output schema
Same as [`query`](/sql-reference/mcp/query/):
```json
{
"success": boolean,
"columns": string[], // Column names (on success)
"columnTypes": string[], // Column types (on success)
"rows": any[][], // Query results (on success)
"rowCount": number, // Number of rows returned (on success)
"error": string, // Error message (on failure)
"errorType": string // Error type (on failure)
}
```
## Limits
- **Result limit:** Maximum 2,048 rows and 50,000 characters. Results exceeding these limits will be truncated with a truncation message.
- **Query timeout:** 55 seconds. Queries exceeding this limit will be cancelled server-side and the tool will respond with an error message.
## Example usage
**Insert rows:**
```text
Insert a new customer 'Acme Corp' with id 100 into my_database.customers
```
```json
{
"database": "my_database",
"sql": "INSERT INTO customers (id, name) VALUES (100, 'Acme Corp')"
}
```
**Update and delete:**
```text
In my_database, set status to 'shipped' for all orders in the orders table where status is 'pending', then delete the old log entries from audit_log
```
The AI assistant can call `query_rw` with the appropriate UPDATE and DELETE statements (or multiple calls if the client requires one statement per call).
**Create table:**
```text
Create a table my_database.main.events with columns id (BIGINT), name (VARCHAR), created_at (TIMESTAMP)
```
```json
{
"database": "my_database",
"sql": "CREATE TABLE main.events (id BIGINT, name VARCHAR, created_at TIMESTAMP)"
}
```
**Account-level operations (database optional):**
```text
Create a new database called reporting
```
```json
{
"sql": "CREATE DATABASE reporting"
}
```
For account-level operations, omit `database` and pass only `sql`.
:::tip Read-only access
To restrict the MCP server so the AI can only read data, see [Restricting to read-only access](/key-tasks/ai-and-motherduck/securing-read-only-access/).
:::
---
Source: https://motherduck.com/docs/sql-reference/mcp/ask-docs-question
# ask_docs_question
> Ask questions about DuckDB or MotherDuck documentation
Ask a question about DuckDB or MotherDuck and get answers from official documentation.
## Description
The `ask_docs_question` tool queries the official DuckDB and MotherDuck documentation to answer questions about SQL syntax, features, best practices, and more. This is useful when you need help with DuckDB-specific SQL syntax or MotherDuck features.
The tool uses MotherDuck's documentation assistant to provide accurate answers based on official documentation sources.
## Input Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `question` | string | Yes | Question about DuckDB or MotherDuck |
## Output Schema
```json
{
"success": boolean,
"question": string, // Original question (on success)
"answer": string, // Documentation-based answer (on success)
"sources": string, // Source references (optional, on success)
"error": string // Error message (on failure)
}
```
## Example Usage
**Ask about DuckDB syntax:**
```text
How do I use window functions in DuckDB?
```
The AI assistant will call the tool with:
```json
{
"question": "How do I use window functions in DuckDB?"
}
```
**Ask about MotherDuck features:**
```text
How do I create a share in MotherDuck?
```
```json
{
"question": "How do I create a share in MotherDuck?"
}
```
**Ask about data types:**
```text
What's the difference between LIST and ARRAY types in DuckDB?
```
```json
{
"question": "What's the difference between LIST and ARRAY types in DuckDB?"
}
```
## Success Response Example
```json
{
"success": true,
"question": "How do I use window functions in DuckDB?",
"answer": "Window functions in DuckDB allow you to perform calculations across a set of rows related to the current row. Here's how to use them:\n\n**Basic syntax:**\n```sql\nSELECT \n column,\n SUM(value) OVER (PARTITION BY category ORDER BY date) as running_total\nFROM table_name;\n```\n\n**Common window functions:**\n- `ROW_NUMBER()` - assigns unique row numbers\n- `RANK()` and `DENSE_RANK()` - ranking with/without gaps\n- `LAG()` and `LEAD()` - access previous/next rows\n- `FIRST_VALUE()` and `LAST_VALUE()` - first/last value in window\n\n**Using QUALIFY:**\nDuckDB supports the QUALIFY clause to filter window function results:\n```sql\nSELECT *\nFROM sales\nQUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) = 1;\n```\n\nThis returns only the top sale per region.",
"sources": "https://duckdb.org/docs/sql/window_functions"
}
```
## Tips for Good Questions
- Be specific about what you want to know
- Include context about what you're trying to accomplish
- Mention specific functions or features if known
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-flight-versions
# MD_FLIGHT_VERSIONS
> List the version history of a Flight.
Returns every `FlightVersion` for a single [Flight](/concepts/flights), newest first. Use this to browse the history of source, requirements, config, token, and secrets changes.
## Syntax
```sql
SELECT * FROM MD_FLIGHT_VERSIONS(
flight_id := '',
"LIMIT" := ,
"OFFSET" :=
);
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight. |
| `LIMIT` | `BIGINT` | No | Maximum number of versions to return. |
| `OFFSET` | `BIGINT` | No | Skip this many versions before returning. |
`LIMIT` and `OFFSET` are SQL keywords and must be quoted when used as named arguments.
## Return columns
| Column | Type | Description |
|---|---|---|
| `flight_version` | `INTEGER` | Version number, newest first. |
| `source_code` | `VARCHAR` | Python source for this version. |
| `requirements_txt` | `VARCHAR` | `requirements.txt` contents for this version. |
| `access_token_name` | `VARCHAR` | Access token label for this version. |
| `flight_secret_names` | `LIST(VARCHAR)` | Secret names list for this version. |
| `config` | `MAP(VARCHAR, VARCHAR)` | Config map for this version. |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When this version was created. |
## Examples
Get the full version history:
```sql
SELECT flight_version, source_code, requirements_txt
FROM MD_FLIGHT_VERSIONS(flight_id := '');
```
Just the latest version:
```sql
SELECT flight_version, source_code
FROM MD_FLIGHT_VERSIONS(flight_id := '', "LIMIT" := 1);
```
Skip the latest, get the rest:
```sql
SELECT flight_version, source_code
FROM MD_FLIGHT_VERSIONS(flight_id := '', "OFFSET" := 1);
```
## Related
- [`MD_GET_FLIGHT_VERSION`](../md-get-flight-version) — Fetch a single version by number.
- [`MD_FLIGHT_RUNS`](../md-flight-runs) — Each run row includes the `flight_version` it used.
- [`list_flight_versions` MCP tool](/sql-reference/mcp/) — AI-agent equivalent.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-list-dive-versions
# MD_LIST_DIVE_VERSIONS
> List all versions of a specific Dive with pagination support.
Lists all versions of a specific [Dive](/key-tasks/ai-and-motherduck/dives) with pagination support. Each time a Dive's content is updated using [`MD_UPDATE_DIVE_CONTENT`](../md-update-dive-content), an additional version is created. This function returns version metadata without the content.
## Syntax
```sql
SELECT * FROM MD_LIST_DIVE_VERSIONS(id = 'your-dive-uuid'::UUID);
SELECT * FROM MD_LIST_DIVE_VERSIONS(
id = 'your-dive-uuid'::UUID,
"limit" = 100,
"offset" = 0
);
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | `UUID` | Yes | The unique identifier of the Dive |
| `limit` | `UINTEGER` | No | Maximum number of versions to return |
| `offset` | `UINTEGER` | No | Number of versions to skip |
:::tip
`limit` and `offset` are reserved SQL keywords and must be double-quoted when used as named parameters.
:::
## Return columns
| Column | Type | Description |
|--------|------|-------------|
| `id` | `UUID` | UUID of this version |
| `version` | `UINTEGER` | Version number (0-based) |
| `storage_url` | `VARCHAR` | Storage URL of the version content |
| `description` | `VARCHAR` | Version description or commit message |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When this version was created |
| `api_version` | `UINTEGER` | API version used to create this version |
## Examples
List all versions of a Dive:
```sql
SELECT version, description, created_at
FROM MD_LIST_DIVE_VERSIONS(id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID);
```
Get the 5 most recent versions:
```sql
SELECT version, description, created_at
FROM MD_LIST_DIVE_VERSIONS(id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID)
ORDER BY version DESC
LIMIT 5;
```
## Errors
Returns an error if the Dive does not exist.
## Related
- [`MD_GET_DIVE_VERSION`](../md-get-dive-version) — Retrieve a specific version including content
- [`MD_UPDATE_DIVE_CONTENT`](../md-update-dive-content) — Create an additional version
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/window-functions
# Window functions
> DuckDB window functions for ranking, running totals, and analytical queries.
Window functions in MotherDuck works the same as in DuckDB. See [Window Functions](https://duckdb.org/docs/stable/sql/window_functions) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/configurations
# Configurations
> DuckDB configuration options for memory, threads, and query behavior.
Configuration of DuckDB settings in MotherDuck works the same as in DuckDB. See [Configuration](https://duckdb.org/docs/stable/sql/configuration) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/mcp/get-dive-guide
# get_dive_guide
> Load instructions for creating MotherDuck Dives
Load instructions for creating MotherDuck [Dives](/docs/key-tasks/ai-and-motherduck/dives). Call this before creating or saving dives.
## Description
The `get_dive_guide` tool returns comprehensive instructions on how to write MotherDuck Dives—interactive React data apps that query live MotherDuck data. It provides guidance on the [`useSQLQuery` hook](/sql-reference/motherduck-sql-reference/ai-functions/dives/use-sql-query), data type conversions, available libraries, and design system. The guide content is tailored to the AI client you are using.
Call this tool before using [`save_dive`](../save-dive) or [`update_dive`](../update-dive) to ensure the generated code follows the correct format.
:::note
Dives are available on all MotherDuck plans at no additional charge.
:::
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `client` | string | Yes | The AI client being used: `"claude"`, `"chatgpt"`, `"claude_code"`, or `"other"` |
### Client options
| Client | Use case |
|--------|----------|
| `claude` | Claude (Anthropic) through Claude.ai or API |
| `chatgpt` | ChatGPT (OpenAI) |
| `claude_code` | Claude Code (terminal-based agent) |
| `other` | Any other AI client or custom integration |
## Output schema
```json
{
"success": boolean,
"guide": string, // Dive guide content (on success) or upgrade message
"client": string, // The client that was used (on success)
"reason": string, // "upgrade_required" (when plan doesn't support Dives)
"plan": string, // Current plan name (when upgrade required)
"error": string // Error message (on failure)
}
```
On success, `guide` contains the client-specific instructions for building Dives.
## Example usage
**Build a new Dive from Claude:**
```text
Create a Dive showing monthly revenue trends for my sales database
```
The AI assistant will first call `get_dive_guide` to load the instructions:
```json
{
"client": "claude"
}
```
**Build a Dive from ChatGPT:**
```text
Create a Dive with a bar chart of customer signups by region
```
```json
{
"client": "chatgpt"
}
```
**Build a Dive from Claude Code:**
```text
Create a Dive showing daily active users over the past 90 days
```
```json
{
"client": "claude_code"
}
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions/dives/md-get-dive-version
# MD_GET_DIVE_VERSION
> Retrieve a specific historical version of a Dive including its content.
Retrieves a specific version of a [Dive](/key-tasks/ai-and-motherduck/dives), including the full React component source code. Version numbers are 0-based—the first version of a Dive is version `0`.
## Syntax
```sql
SELECT * FROM MD_GET_DIVE_VERSION(
id = 'your-dive-uuid'::UUID,
version = 0
);
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | `UUID` | Yes | The unique identifier of the Dive |
| `version` | `UINTEGER` | Yes | The version number to retrieve (0-based) |
## Return columns
| Column | Type | Description |
|--------|------|-------------|
| `id` | `UUID` | UUID of this version |
| `version` | `UINTEGER` | Version number |
| `storage_url` | `VARCHAR` | Storage URL of the version content |
| `description` | `VARCHAR` | Version description or commit message |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When this version was created |
| `api_version` | `UINTEGER` | API version used to create this version |
| `content` | `VARCHAR` | Full JSX/React component source code |
## Examples
Read the original version of a Dive:
```sql
SELECT content
FROM MD_GET_DIVE_VERSION(
id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID,
version = 0
);
```
Compare version metadata:
```sql
SELECT version, description, created_at
FROM MD_GET_DIVE_VERSION(
id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'::UUID,
version = 2
);
```
## Errors
Returns an error if the Dive or the specified version does not exist.
## Related
- [`MD_LIST_DIVE_VERSIONS`](../md-list-dive-versions) — List all versions to find version numbers
- [`MD_GET_DIVE`](../md-get-dive) — Get the latest version of a Dive
- [`read_dive` MCP tool](/sql-reference/mcp/read-dive) — AI assistant equivalent (supports `version` parameter)
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-run-flight
# MD_RUN_FLIGHT
> Trigger an on-demand execution of a Flight using its current version.
Triggers a new run of a [Flight](/concepts/flights) using the Flight's current version. The run is asynchronous: `MD_RUN_FLIGHT` returns immediately with a `RUN_STATUS_RUNNING` (or `RUN_STATUS_PENDING`) row. Use [`MD_FLIGHT_RUNS`](../md-flight-runs) to poll for completion and [`MD_FLIGHT_LOGS`](../md-flight-logs) to read the output.
## Syntax
```sql
SELECT * FROM MD_RUN_FLIGHT(flight_id := '');
```
`MD_RUN_FLIGHT` is a table function; you can also call it with `CALL` when you don't need the result row:
```sql
CALL MD_RUN_FLIGHT(flight_id := '');
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight to run. |
## Return columns
| Column | Type | Description |
|---|---|---|
| `flight_id` | `UUID` | The Flight identifier. |
| `flight_name` | `VARCHAR` | The Flight name. |
| `flight_version` | `INTEGER` | The version this run locked to. |
| `status` | `VARCHAR` | Initial run status (`RUN_STATUS_PENDING` or `RUN_STATUS_RUNNING`). |
| `is_scheduled` | `BOOLEAN` | `false` for on-demand runs. |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When the run was created. |
## Behavior
- The new run locks to the Flight's current version. Subsequent updates to the Flight do not affect this run.
- The run number is assigned sequentially per Flight and visible through [`MD_FLIGHT_RUNS`](../md-flight-runs).
- Multiple concurrent runs of the same Flight are allowed; each gets its own run number.
## Examples
Trigger a run and capture the row:
```sql
SELECT flight_version, status
FROM MD_RUN_FLIGHT(flight_id := '80000000-0000-0000-0000-000000000001');
```
Trigger and then poll until the run finishes:
```sql
-- Kick off the run
CALL MD_RUN_FLIGHT(flight_id := '');
-- Poll the latest run's status
SELECT run_number, status
FROM MD_FLIGHT_RUNS(flight_id := '')
ORDER BY run_number DESC
LIMIT 1;
```
## Related
- [`MD_FLIGHT_RUNS`](../md-flight-runs) — List runs for a Flight.
- [`MD_FLIGHT_LOGS`](../md-flight-logs) — Read combined stdout/stderr for a run.
- [`MD_CANCEL_FLIGHT_RUN`](../md-cancel-flight-run) — Cancel an in-progress run.
- [`run_flight` MCP tool](/sql-reference/mcp/) — AI-agent equivalent.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/constraints
# Constraints
> Table constraints in DuckDB including PRIMARY KEY, UNIQUE, NOT NULL, and CHECK.
Constraints in MotherDuck works the same as in DuckDB. See [Constraints](https://duckdb.org/docs/stable/sql/constraints) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/mcp/list-dives
# list_dives
> List all Dives in your MotherDuck workspace
List all owned [Dives](/docs/key-tasks/ai-and-motherduck/dives) in MotherDuck. Dives are interactive React data apps that query live data. Returns metadata including `current_version` (the latest version number, 1-indexed) for each Dive. Use [`read_dive`](../read-dive) with the optional `version` parameter to retrieve a specific historical version. Optionally filter by keywords to search in title and description.
## Description
The `list_dives` tool returns a list of all Dives in your MotherDuck workspace. Each Dive includes its ID, title, description, owner, version history, and timestamps. Use this to discover existing Dives before reading, updating, or deleting them.
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `keywords` | string | No | Keywords to filter dives by title or description (case-insensitive, all words must match) |
## Output schema
```json
{
"success": boolean,
"dives": [ // Array of dives (on success)
{
"id": string, // Unique identifier (UUID)
"title": string, // Dive title
"description": string, // Dive description
"owner_name": string, // Name of the Dive owner
"current_version": number, // Latest version number (1-indexed)
"created_at": string, // ISO 8601 creation timestamp
"updated_at": string // ISO 8601 last update timestamp
}
],
"count": number, // Number of dives returned
"totalCount": number, // Total number of matching dives
"truncated": boolean, // Whether the results were truncated
"message": string, // Truncation message (when truncated)
"error": string // Error message (on failure)
}
```
## Example usage
**List all Dives:**
```text
What Dives do I have in my workspace?
```
The AI assistant will call the tool with no parameters.
**Filter Dives by keywords:**
```text
Show me my revenue-related Dives
```
The AI assistant will call the tool with keywords:
```json
{
"keywords": "revenue"
}
```
**Find a specific Dive to update:**
```text
Show me my existing Dives so I can update the revenue dashboard
```
## Success response example
```json
{
"success": true,
"dives": [
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Monthly Revenue Trends",
"description": "Line chart showing revenue by month with category breakdown",
"owner_name": "alice",
"current_version": 3,
"created_at": "2025-01-15T10:30:00Z",
"updated_at": "2025-01-20T14:45:00Z"
},
{
"id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
"title": "Customer Signups by Region",
"description": "Bar chart of customer signups grouped by region",
"owner_name": "bob",
"current_version": 1,
"created_at": "2025-01-18T09:00:00Z",
"updated_at": "2025-01-18T09:00:00Z"
}
],
"count": 2,
"totalCount": 2
}
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-flight-runs
# MD_FLIGHT_RUNS
> List the execution history of a Flight, newest first.
Returns every run of a single [Flight](/concepts/flights). Each row has a status, a sequential run number, and the version of the Flight that ran.
## Syntax
```sql
SELECT * FROM MD_FLIGHT_RUNS(
flight_id := '',
"LIMIT" := ,
"OFFSET" :=
);
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight. |
| `LIMIT` | `BIGINT` | No | Maximum number of runs to return. |
| `OFFSET` | `BIGINT` | No | Skip this many runs before returning. |
`LIMIT` and `OFFSET` are SQL keywords and must be quoted when used as named arguments.
## Return columns
| Column | Type | Description |
|---|---|---|
| `flight_id` | `UUID` | Flight identifier. |
| `flight_name` | `VARCHAR` | Flight name at the time of the run. |
| `flight_version` | `INTEGER` | The version this run locked to at start. |
| `run_number` | `INTEGER` | Sequential run number, starting at `1`. |
| `is_scheduled` | `BOOLEAN` | `true` if the run was triggered by the schedule, `false` for on-demand. |
| `status` | `VARCHAR` | Run status: `RUN_STATUS_PENDING`, `RUN_STATUS_RUNNING`, `RUN_STATUS_SUCCEEDED`, `RUN_STATUS_FAILED`, or `RUN_STATUS_CANCELLED`. |
| `created_at` | `TIMESTAMP WITH TIME ZONE` | When the run was created. |
## Examples
Latest 10 runs, newest first:
```sql
SELECT run_number, status, flight_version, created_at
FROM MD_FLIGHT_RUNS(flight_id := '')
ORDER BY run_number DESC
LIMIT 10;
```
Find recent failures:
```sql
SELECT run_number, flight_version, created_at
FROM MD_FLIGHT_RUNS(flight_id := '')
WHERE status = 'RUN_STATUS_FAILED'
ORDER BY run_number DESC;
```
Total runs per version:
```sql
SELECT flight_version, COUNT(*) AS runs
FROM MD_FLIGHT_RUNS(flight_id := '')
GROUP BY flight_version
ORDER BY flight_version DESC;
```
## Related
- [`MD_RUN_FLIGHT`](../md-run-flight) — Trigger an on-demand run.
- [`MD_FLIGHT_LOGS`](../md-flight-logs) — Read a specific run's output.
- [`MD_CANCEL_FLIGHT_RUN`](../md-cancel-flight-run) — Cancel an in-progress run.
- [`list_flight_runs` MCP tool](/sql-reference/mcp/) — AI-agent equivalent.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/information-schema
# Information schema
> DuckDB information_schema views for querying database metadata.
Information schema views in MotherDuck works the same as in DuckDB. See [Information schema](https://duckdb.org/docs/stable/sql/meta/information_schema) in the DuckDB documentation for complete details.
If you want to query information about your MotherDuck entities, take a look at [md_information_schema](/sql-reference/motherduck-sql-reference/md_information_schema/introduction).
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-flight-logs
# MD_FLIGHT_LOGS
> Read the combined stdout and stderr captured during a Flight run.
Returns the captured logs for a single [Flight](/concepts/flights) run. The output combines stdout and stderr in the order the runtime captured them.
## Syntax
```sql
SELECT logs FROM MD_FLIGHT_LOGS(
flight_id := '',
run_number :=
);
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight. |
| `run_number` | `INTEGER` | Yes | The run number to fetch logs for. |
## Return columns
| Column | Type | Description |
|---|---|---|
| `logs` | `VARCHAR` | The full combined stdout/stderr captured during the run. |
## Behavior
- Returns an error when no run with the given `run_number` exists for the Flight, or when the Flight itself doesn't exist.
- Available for runs in any terminal status (`SUCCEEDED`, `FAILED`, `CANCELLED`) and during a `RUNNING` run.
## Examples
Read the latest run's logs:
```sql
WITH latest AS (
SELECT run_number
FROM MD_FLIGHT_RUNS(flight_id := '')
ORDER BY run_number DESC LIMIT 1
)
SELECT logs
FROM latest, MD_FLIGHT_LOGS(flight_id := '', run_number := latest.run_number);
```
Read a specific run:
```sql
SELECT logs
FROM MD_FLIGHT_LOGS(
flight_id := '80000000-0000-0000-0000-000000000001',
run_number := 42
);
```
## Related
- [`MD_FLIGHT_RUNS`](../md-flight-runs) — Find the run number to read logs for.
- [`MD_RUN_FLIGHT`](../md-run-flight) — Trigger an on-demand run.
- [`get_flight_run_logs` MCP tool](/sql-reference/mcp/) — AI-agent equivalent, with a `max_bytes` cap.
---
Source: https://motherduck.com/docs/sql-reference/mcp/read-dive
# read_dive
> Read a specific Dive by ID, including its full component code
Read a specific [Dive](/docs/key-tasks/ai-and-motherduck/dives) by ID, including its full JSX/React component code. Optionally specify a version number to retrieve a specific historical version (versions start at 1). If no version is specified, the latest version is returned.
## Description
The `read_dive` tool retrieves a Dive's complete details, including its title, description, timestamps, and the full React component source code. Use this to inspect an existing Dive before updating it, or to understand how a Dive is built.
Use [`list_dives`](../list-dives) first to find the Dive ID and its `current_version`.
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | The unique identifier (UUID) of the Dive to read |
| `version` | number | No | Version number to retrieve (1-indexed). Defaults to the latest version. |
## Output schema
```json
{
"success": boolean,
"dive": { // Dive object (on success)
"id": string, // Unique identifier (UUID)
"title": string, // Dive title
"description": string, // Dive description
"content": string, // Full JSX/React component code
"current_version": number, // Current version number
"created_at": string, // ISO 8601 creation timestamp
"updated_at": string // ISO 8601 last update timestamp
},
"error": string // Error message (on failure)
}
```
## Example usage
**Read a Dive to inspect its code:**
```text
Show me the code for my revenue trends Dive
```
The AI assistant will call the tool with the Dive's ID:
```json
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
```
**Read a specific version of a Dive:**
```text
Show me version 1 of my revenue trends Dive
```
```json
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"version": 1
}
```
**Read a Dive before updating it:**
```text
I want to modify my customer signups Dive—can you show me what it looks like?
```
## Success response example
```json
{
"success": true,
"dive": {
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Monthly Revenue Trends",
"description": "Line chart showing revenue by month",
"content": "import { useSQLQuery } from \"@motherduck/react-sql-query\";\n\nexport default function Dive() {\n const { data, isLoading } = useSQLQuery(`SELECT ...`);\n // ...\n}",
"current_version": 3,
"created_at": "2025-01-15T10:30:00Z",
"updated_at": "2025-01-20T14:45:00Z"
}
}
```
## Error response example
```json
{
"success": false,
"error": "Dive with ID 'invalid-uuid' not found"
}
```
---
Source: https://motherduck.com/docs/sql-reference/mcp/view-dive
# view_dive
> Render a MotherDuck Dive as a live, interactive MCP app inside the host client.
Render a [Dive](/key-tasks/ai-and-motherduck/dives) as an interactive MCP app inside hosts that support the dive viewer. The tool fetches the Dive's source code and metadata from MotherDuck; the host's dive viewer compiles and renders it client-side.
## Description
The `view_dive` tool opens a Dive in the host's MCP dive viewer, where the agent and the user can interact with live data. Optional inputs let you preview the same Dive against different databases or with a specific starting UI state without re-saving the Dive.
The tool also returns `dive_app_url` — a chat-side link the agent can offer to open the same Dive in `app.motherduck.com`. When `initial_state` is supplied, it rides along in the URL so the linked-to Dive opens at the same configured view as the inline preview.
Use [`list_dives`](../list-dives) to find a Dive's ID before calling `view_dive`.
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `dive_id` | string (UUID) | Yes | The unique identifier of the Dive to render. |
| `required_resources` | array of `{ url, alias? }` | No | Override the Dive's source-declared `REQUIRED_DATABASES` for this preview. |
| `initial_state` | object | No | Seed the Dive's initial UI state for this preview. Keys match those used by the `useDiveState` hook inside the Dive's code. Values must be JSON-serializable. |
### `required_resources` shape
```json
[
{
"url": "md:_share//",
"alias": ""
}
]
```
`url` accepts a share URL (`md:_share//`) or an owned database identifier (`md:`). `alias` defaults to the database name from the URL when omitted.
When supplied, `required_resources` **replaces** the Dive's source-declared `REQUIRED_DATABASES` for the preview. Use it when the user wants to render a Dive against a specific share or embed configuration. For a permanent change to the Dive's target databases, edit the source and use [`update_dive`](../update-dive) instead.
### `initial_state` shape
```json
{
"": ,
"":
}
```
Each key matches a `useDiveState(key, ...)` call inside the Dive's source. Interactive changes during the preview do not round-trip back to the MCP host; pass another `initial_state` on the next call if you want to start from the new state. Do not use `initial_state` for ephemeral UI state (input drafts, dialog open/close) — those use plain `useState` inside the Dive.
## Output schema
```json
{
"success": boolean,
"dive_id": string, // UUID of the rendered Dive
"title": string, // Dive title
"source": string, // Full JSX/React component source
"current_version": number, // Latest version number for the Dive
"dive_app_url": string, // Chat-side link to open the Dive in app.motherduck.com
"initial_state": object, // Echoed back when supplied in the request
"required_resources": array, // Echoed back when supplied in the request
"error": string // Error message (on failure)
}
```
When `initial_state` is supplied, `dive_app_url` carries it in the URL fragment, so clicking the link opens the Dive at the same starting view as the inline preview. `required_resources` is **not** carried in `dive_app_url`: clicking the link opens the Dive against its source-declared `REQUIRED_DATABASES`, not the override. Use the [embed session API](/key-tasks/ai-and-motherduck/dives/embedding-dives/#override-required-databases) if you need the override to survive into the linked-to Dive.
## Example usage
**Open a Dive in the host's dive viewer:**
```text
Open my revenue trends Dive
```
The agent calls the tool with the Dive's ID:
```json
{
"dive_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
```
**Preview a Dive against a specific database:**
```text
Show me the customer analytics Dive against the staging share
```
```json
{
"dive_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"required_resources": [
{
"url": "md:_share/staging_data/9f4a2b8c-1234-5678-90ab-cdef01234567",
"alias": "customer_analytics"
}
]
}
```
**Preview a Dive in a specific UI state:**
```text
Show me the sales overview Dive filtered to EMEA, last quarter
```
```json
{
"dive_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"initial_state": {
"region": "emea",
"dateRange": { "start": "2026-01-01", "end": "2026-03-31" }
}
}
```
## Success response example
```json
{
"success": true,
"dive_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Monthly Revenue Trends",
"source": "import { useSQLQuery } from \"@motherduck/react-sql-query\";\n\nexport default function Dive() {\n // ...\n}",
"current_version": 3,
"dive_app_url": "https://app.motherduck.com/dives/a1b2c3d4-e5f6-7890-abcd-ef1234567890/monthly-revenue-trends#state=eyJyZWdpb24iOiJlbWVhIn0",
"initial_state": {
"region": "emea"
}
}
```
## Error response example
```json
{
"success": false,
"error": "Dive 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' not found"
}
```
## Data exports from the dive viewer
The MCP dive viewer supports data export through the Dive's [`exportAs`](/sql-reference/motherduck-sql-reference/ai-functions/dives/use-sql-query/#export-query-results) buttons. When a user starts an export, the dive viewer generates the file (CSV, Parquet, or XLSX) from the browser DuckDB connection:
- **Hosts that support file downloads** receive the completed file directly through the MCP `downloadFile` capability.
- **Hosts that do not support `downloadFile`** show a fallback dialog with a link back to the Dive in MotherDuck so the user can export there.
Exports do not require any additional `view_dive` parameters; they're enabled by the Dive's source code.
## Related resources
- [Creating visualizations with Dives](/key-tasks/ai-and-motherduck/dives/)
- [Embedding Dives in your web application](/key-tasks/ai-and-motherduck/dives/embedding-dives/) — the embed-session equivalents of `required_resources` and `initial_state`
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights/md-cancel-flight-run
# MD_CANCEL_FLIGHT_RUN
> Cancel an in-progress Flight run.
Cancels an in-progress run of a [Flight](/concepts/flights). The run transitions to `RUN_STATUS_CANCELLED`.
Cancelling a run that's already in a terminal status (`SUCCEEDED`, `FAILED`, `CANCELLED`) or a run that doesn't exist returns an error.
## Syntax
```sql
CALL MD_CANCEL_FLIGHT_RUN(
flight_id := '',
run_number :=
);
```
## Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `flight_id` | `UUID` | Yes | Identifier of the Flight. |
| `run_number` | `INTEGER` | Yes | The run number to cancel. |
## Examples
Cancel the most recent run if it's still in progress:
```sql
WITH latest AS (
SELECT run_number, status
FROM MD_FLIGHT_RUNS(flight_id := '')
ORDER BY run_number DESC LIMIT 1
)
SELECT MD_CANCEL_FLIGHT_RUN(flight_id := '', run_number := latest.run_number)
FROM latest
WHERE latest.status IN ('RUN_STATUS_PENDING', 'RUN_STATUS_RUNNING');
```
Cancel a specific run:
```sql
CALL MD_CANCEL_FLIGHT_RUN(
flight_id := '80000000-0000-0000-0000-000000000001',
run_number := 42
);
```
## Related
- [`MD_FLIGHT_RUNS`](../md-flight-runs) — Find runs that are still in progress.
- [`MD_RUN_FLIGHT`](../md-run-flight) — Trigger an on-demand run.
- [`cancel_flight_run` MCP tool](/sql-reference/mcp/) — AI-agent equivalent.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/metadata-functions
# Metadata functions
> DuckDB functions for querying table and column metadata programmatically.
The duckdb_ metadata functions for tables in MotherDuck works the same as in DuckDB. See [DuckDB_% Metadata Functions](https://duckdb.org/docs/stable/sql/duckdb_table_functions) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/mcp/save-dive
# save_dive
> Save a new Dive to your MotherDuck workspace
Save a new [Dive](/docs/key-tasks/ai-and-motherduck/dives) to MotherDuck. Returns a URL to the Dive in MotherDuck as a link that the user can click to view the Dive.
## Description
The `save_dive` tool creates a new Dive in your MotherDuck workspace. It accepts a title, optional description, and the JSX/React component code. Before saving, the tool validates the code to check for common issues like invalid SQL queries or missing exports.
After saving, the tool analyzes which databases the Dive queries. If any referenced databases are not yet shared with your organization, it prompts you to use [`share_dive_data`](../share-dive-data) so others in your organization can view the Dive.
Call [`get_dive_guide`](../get-dive-guide) first to learn the required JSX/React format.
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `title` | string | Yes | The title of the Dive |
| `description` | string | No | A brief description of the Dive |
| `content` | string | Yes | The JSX/React component code for the Dive |
## Output schema
```json
{
"success": boolean,
"dive": { // Created dive info (on success)
"id": string, // Unique identifier (UUID)
"title": string, // Dive title
"description": string | null // Dive description
},
"dive_url": string, // URL to view the Dive (on success)
"warnings": string[], // Validation warnings (if any)
"database_warnings": string[], // Warnings from database analysis (if any)
"unshared_databases": string[], // Database names not yet shared with the org (if any)
"next_steps": string[], // Ordered instructions for the AI to follow after saving
"error": string, // Error message (on failure)
"validationErrors": [ // Validation errors (on failure)
{
"type": string, // Error type
"message": string, // Error description
"details": string // Additional details
}
]
}
```
## Example usage
**Create a new Dive:**
```text
Create a Dive showing monthly revenue trends for my analytics database
```
The AI assistant will first call [`get_dive_guide`](../get-dive-guide) to load the instructions, then call `save_dive`:
```json
{
"title": "Monthly Revenue Trends",
"description": "Line chart showing revenue by month with year-over-year comparison",
"content": "import { useSQLQuery } from \"@motherduck/react-sql-query\";\nimport { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer } from \"recharts\";\n\nexport default function Dive() {\n const { data, isLoading, isError, error } = useSQLQuery(`\n SELECT DATE_TRUNC('month', order_date) as month, SUM(revenue) as revenue\n FROM analytics.sales\n GROUP BY 1 ORDER BY 1\n `);\n // ... component code\n}"
}
```
## Success response example
```json
{
"success": true,
"dive": {
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Monthly Revenue Trends",
"description": "Line chart showing revenue by month with year-over-year comparison"
},
"dive_url": "https://app.motherduck.com/dives/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"unshared_databases": ["analytics"],
"next_steps": [
"Regenerate the dive preview artifact with the updated banner...",
"Show the dive to the user in chat as a markdown hyperlink: [Monthly Revenue Trends](https://app.motherduck.com/dives/a1b2c3d4-...)",
"The dive references databases not yet shared with the organization: analytics. Ask the user if they want to share them."
]
}
```
## Validation error response example
```json
{
"success": false,
"error": "Dive validation failed",
"validationErrors": [
{
"type": "SQL_ERROR",
"message": "Query validation failed: Table 'analytics.nonexistent_table' not found",
"details": "SELECT * FROM analytics.nonexistent_table"
}
],
"hint": "Please fix the errors above and try again."
}
```
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/pragma-statements
# PRAGMA statements
> PRAGMA statements for DuckDB configuration and metadata queries.
The PRAGMA statements in MotherDuck works the same as in DuckDB. See [Pragmas](https://duckdb.org/docs/stable/sql/pragmas) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/mcp/update-dive
# update_dive
> Update an existing Dive's title, description, or content
Update an existing [Dive's](/docs/key-tasks/ai-and-motherduck/dives) title, description, or content. Returns a URL to the Dive in MotherDuck as a link the user can click to view the updated Dive.
## Description
The `update_dive` tool modifies an existing Dive in your MotherDuck workspace. You can update the title, description, content (React component code), or any combination. At least one field must be provided.
When updating content, the tool validates the new code before saving, just like [`save_dive`](../save-dive). It also analyzes which databases the Dive queries and reports any unshared databases.
Use [`list_dives`](../list-dives) to find the Dive ID, and [`read_dive`](../read-dive) to inspect the current code before modifying it.
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | The unique identifier (UUID) of the Dive to update |
| `title` | string | No | New title for the Dive |
| `description` | string | No | New description for the Dive |
| `content` | string | No | New JSX/React component code |
At least one of `title`, `description`, or `content` must be provided.
## Output schema
```json
{
"success": boolean,
"dive": { // Updated dive info (on success)
"id": string // Dive identifier
},
"dive_url": string, // URL to view the Dive (on success)
"warnings": string[], // Validation warnings (if any)
"database_warnings": string[], // Warnings from database analysis (if any)
"unshared_databases": string[], // Database names not yet shared with the org (if any)
"next_steps": string[], // Ordered instructions for the AI to follow after updating
"error": string, // Error message (on failure)
"validationErrors": [ // Validation errors (on failure)
{
"type": string,
"message": string,
"details": string
}
]
}
```
## Example usage
**Update a Dive's content:**
```text
Add a region filter to my revenue trends Dive
```
The AI assistant will call `read_dive` to get the current code, modify it, then call `update_dive`:
```json
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"content": "import { useSQLQuery } from \"@motherduck/react-sql-query\";\n// ... updated component with region filter\n"
}
```
**Update just the title and description:**
```text
Rename my revenue Dive to "Q1 Revenue Dashboard"
```
```json
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Q1 Revenue Dashboard",
"description": "Revenue trends filtered to Q1 2025"
}
```
## Success response example
```json
{
"success": true,
"dive": {
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
},
"dive_url": "https://app.motherduck.com/dives/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"next_steps": [
"Regenerate the dive preview artifact with the updated banner...",
"Show the dive to the user in chat as a markdown hyperlink using the dive title: [dive title](https://app.motherduck.com/dives/a1b2c3d4-...)"
]
}
```
## Error response example
```json
{
"success": false,
"error": "At least one of title, description, or content must be provided"
}
```
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/sample
# SAMPLE
> SAMPLE clause for retrieving random subsets of query results in DuckDB.
Samples in MotherDuck works the same as in DuckDB. See [Samples](https://duckdb.org/docs/stable/sql/samples) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/mcp/share-dive-data
# share_dive_data
> Share the data for a Dive with your organization
Share the data for a [Dive](/docs/key-tasks/ai-and-motherduck/dives) with your organization. Creates org-scoped shares for owned databases used in the Dive, so others in the organization can view it.
## Description
The `share_dive_data` tool makes a Dive's underlying data accessible to your organization. When a Dive queries databases that you own but haven't shared, other users in your organization won't be able to view the Dive. This tool creates shares for those databases and updates the Dive to reference the shared versions.
The tool:
1. Verifies you own the Dive
2. Analyzes the Dive's SQL queries to find referenced databases
3. Creates org-scoped shares for any databases that aren't already shared
4. Updates the Dive to use the shared database references
Use this after [`save_dive`](../save-dive) or [`update_dive`](../update-dive) when you want your team to be able to view a Dive that queries your private databases.
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `diveId` | string | Yes | The unique identifier (UUID) of the Dive to share data for |
## Output schema
```json
{
"success": boolean,
"dive": { // Dive info (on success)
"id": string, // Dive identifier
"title": string, // Dive title
"version": number // New version number after update
},
"shares": [ // Shares created (on success)
{
"database": string, // Database name
"shareName": string, // Share name
"shareUrl": string, // Share URL for the database
"created": boolean // Whether the share was newly created
}
],
"requiredDatabases": [ // All databases referenced by the Dive
{
"type": string, // "share" or "database"
"path": string, // Share URL or database path
"alias": string // Database alias name
}
],
"url": string, // URL to view the Dive (on success)
"message": string, // Status message (on success)
"warnings": string[], // Warnings from analysis or sharing (if any)
"error": string // Error message (on failure)
}
```
## Example usage
**Share a Dive's data after saving:**
```text
Share the data for my revenue Dive with the rest of my team
```
The AI assistant will call the tool with the Dive's ID:
```json
{
"diveId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
```
**Respond to a sharing prompt after save:**
After calling [`save_dive`](../save-dive), the tool may suggest sharing unshared databases. The AI assistant will call `share_dive_data` to make the data accessible:
```json
{
"diveId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
```
## Success response example
```json
{
"success": true,
"dive": {
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Monthly Revenue Trends",
"version": 4
},
"shares": [
{
"database": "analytics",
"shareName": "analytics",
"shareUrl": "md:_share/analytics/a1b2c3d4-...",
"created": true
}
],
"requiredDatabases": [
{
"type": "share",
"path": "md:_share/analytics/a1b2c3d4-...",
"alias": "analytics"
}
],
"url": "https://app.motherduck.com/dives/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"message": "Created 1 share(s). Dive updated with share URLs."
}
```
## Nothing to share response example
When all referenced databases are already shared:
```json
{
"success": true,
"message": "All referenced databases are already shared. No action needed.",
"shares": [],
"requiredDatabases": [
{
"type": "share",
"path": "md:_share/analytics/a1b2c3d4-...",
"alias": "analytics"
}
],
"dive": {
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"version": 3
}
}
```
## Error response example
```json
{
"success": false,
"error": "You don't own this dive or it doesn't exist"
}
```
---
Source: https://motherduck.com/docs/sql-reference/mcp/delete-dive
# delete_dive
> Permanently delete a Dive by ID
Delete a [Dive](/docs/key-tasks/ai-and-motherduck/dives) by ID. This action is permanent and cannot be undone.
## Description
The `delete_dive` tool permanently removes a Dive from your MotherDuck workspace. Once deleted, the Dive cannot be recovered.
Use [`list_dives`](../list-dives) to find the Dive ID before deleting.
## Input parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | The unique identifier (UUID) of the Dive to delete |
## Output schema
```json
{
"success": boolean,
"message": string, // Status message (on success)
"error": string // Error message (on failure)
}
```
## Example usage
**Delete a Dive:**
```text
Delete the old revenue Dive I no longer need
```
The AI assistant will call `list_dives` to find the Dive, confirm with the user, then call `delete_dive`:
```json
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
```
## Success response example
```json
{
"success": true,
"message": "Dive 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' deleted successfully."
}
```
## Error response example
```json
{
"success": false,
"error": "Dive with id 'invalid-uuid' not found"
}
```
---
Source: https://motherduck.com/docs/sql-reference/mcp/get-flight-guide
# get_flight_guide
> Load the canonical instructions for authoring, scheduling, running, and troubleshooting MotherDuck Flights.
Loads the authoritative guide for working with [Flights](/concepts/flights). Call this tool first whenever the conversation turns to creating, updating, or operating a Flight, before reaching for any other `*_flight*` MCP tool.
## Description
`get_flight_guide` returns a single guide document covering: the anatomy of a Flight, the difference between config and secrets, scheduling, run lifecycle, and common failure patterns. It does not take any arguments.
The human-readable equivalent of this guide lives at the [Flights concept page](/concepts/flights). The guide returned by this tool is what AI agents should consult inside an agent session.
## Input parameters
This tool takes no arguments.
## Output schema
```json
{
"success": boolean,
"guide": string // Markdown content of the guide
}
```
## Example usage
When the user asks for anything Flight-related, the assistant should call this tool before calling [`create_flight`](../create-flight) or other flight tools:
```text
Create a Flight that ingests Postgres data into MotherDuck hourly.
```
The assistant first calls `get_flight_guide`, reads the guide, and then proceeds to author the Flight.
## Related
- [`create_flight`](../create-flight) — Create a new Flight.
- [`list_flights`](../list-flights) — List Flights you own.
- [Flights concept](/concepts/flights) — The human-readable overview.
---
Source: https://motherduck.com/docs/sql-reference/mcp/list-flights
# list_flights
> List the Flights you own with summary metadata, optionally filtered by keywords.
List all [Flights](/concepts/flights) owned by the caller. Each Flight in the response includes its UUID, name, schedule, status, and current version. Optionally filter by keywords matching the Flight name.
## Description
The `list_flights` tool returns Flight summary metadata, not version-specific content. Use [`get_flight`](../get-flight) with the returned `id` to fetch source code, requirements, and config.
The corresponding SQL function is [`MD_FLIGHTS`](/sql-reference/motherduck-sql-reference/flights/md-flights).
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `keywords` | string | No | Keywords to filter Flights by name (case-insensitive, all words must match). |
| `limit` | integer | No | Max results to return (default: 100, max: 500). |
## Output schema
```json
{
"success": boolean,
"flights": [
{
"id": string, // Flight UUID
"name": string,
"schedule_cron": string|null, // Cron expression or null for on-demand
"status": string, // Schedule status (e.g. JOB_STATUS_ACTIVE)
"current_version": number,
"created_at": string, // ISO 8601
"updated_at": string // ISO 8601
}
],
"count": number,
"error": string // On failure
}
```
## Example usage
```text
What Flights do I have?
```
The assistant calls the tool with no arguments. To filter:
```json
{ "keywords": "metrics" }
```
## Related
- [`get_flight`](../get-flight) — Fetch a single Flight's content.
- [`MD_FLIGHTS`](/sql-reference/motherduck-sql-reference/flights/md-flights) — SQL equivalent.
---
Source: https://motherduck.com/docs/sql-reference/mcp/get-flight
# get_flight
> Fetch a Flight's metadata and version snapshot by UUID, optionally at a specific historical version.
Fetch a single [Flight](/concepts/flights). Returns Flight metadata plus the content of a specific version (source code, requirements, config, secret names, token name). Omit `version` for the current version; pass a 1-indexed `version` to inspect history.
## Description
The `get_flight` tool combines metadata and version content into one response, so the assistant does not need separate calls for "find the Flight" and "read its source." Use it to inspect a Flight before editing, or to read the source that ran for a specific past run.
The SQL equivalent is [`MD_GET_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-get-flight) plus [`MD_GET_FLIGHT_VERSION`](/sql-reference/motherduck-sql-reference/flights/md-get-flight-version).
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
| `version` | integer | No | 1-indexed version number. Omit for the current version. |
## Output schema
```json
{
"success": boolean,
"flight": {
"id": string,
"name": string,
"schedule_cron": string|null,
"status": string,
"current_version": number,
"version": {
"version": number,
"source_code": string,
"requirements_txt": string,
"config": { "": "" },
"md_token_name": string,
"md_secret_names": string[]
},
"created_at": string,
"updated_at": string
},
"error": string
}
```
## Example usage
Inspect the current Flight:
```json
{ "id": "80000000-0000-0000-0000-000000000001" }
```
Inspect version 2:
```json
{ "id": "80000000-0000-0000-0000-000000000001", "version": 2 }
```
## Related
- [`list_flight_versions`](../list-flight-versions) — Find available version numbers.
- [`list_flight_runs`](../list-flight-runs) — Each run includes the version it ran against.
- [`MD_GET_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-get-flight) — SQL equivalent for current summary.
---
Source: https://motherduck.com/docs/sql-reference/mcp/list-flight-versions
# list_flight_versions
> List the version history of a Flight, newest first.
List every immutable version of a [Flight](/concepts/flights), newest first. Each update to `source_code`, `requirements_txt`, `config`, `md_token_name`, or `md_secret_names` produces a fresh version. Updates to `name` or `schedule_cron` are metadata-only and do not appear here.
## Description
Use `list_flight_versions` to browse what changed between versions, or to find the version a specific run executed. The corresponding SQL function is [`MD_FLIGHT_VERSIONS`](/sql-reference/motherduck-sql-reference/flights/md-flight-versions).
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
| `limit` | integer | No | Max results to return (default: 100, max: 500). |
## Output schema
```json
{
"success": boolean,
"versions": [
{
"version": number,
"source_code": string,
"requirements_txt": string,
"md_token_name": string,
"md_secret_names": string[],
"config": { "": "" },
"created_at": string
}
],
"count": number,
"error": string
}
```
## Example usage
```json
{ "id": "80000000-0000-0000-0000-000000000001" }
```
## Related
- [`get_flight`](../get-flight) — Fetch one version's full content.
- [`list_flight_runs`](../list-flight-runs) — Runs reference the version they used.
- [`MD_FLIGHT_VERSIONS`](/sql-reference/motherduck-sql-reference/flights/md-flight-versions) — SQL equivalent.
---
Source: https://motherduck.com/docs/sql-reference/mcp/create-flight
# create_flight
> Create a new Flight from Python source code, requirements, token, and an optional schedule.
Create a new [Flight](/concepts/flights). A Flight is a Python entrypoint plus an optional `requirements.txt` that runs on MotherDuck compute. Provide `md_token_name` so the Flight can connect to MotherDuck at runtime. Optionally provide a 5-field cron expression to run on a schedule.
Call [`get_flight_guide`](../get-flight-guide) first if you need the authoring reference.
## Description
`create_flight` is the marquee entry point for the MCP Flights surface. The SQL equivalent is [`MD_CREATE_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-create-flight).
The parameter names on the MCP tool keep the `md_*` prefix (for example, `md_token_name`, `md_secret_names`); the equivalent SQL function uses unprefixed names (`access_token_name`, `flight_secret_names`).
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `name` | string | Yes | Flight name (used in logs and listings). |
| `source_code` | string | Yes | Python source for the Flight. A single-file program with a top-level `def main(): ...`. |
| `md_token_name` | string | Yes | Label of a MotherDuck access token. Injected as `MOTHERDUCK_TOKEN` at runtime. List labels with `SELECT * FROM md_access_tokens();`. |
| `schedule_cron` | string | No | 5-field cron expression in UTC. Omit for on-demand only. |
| `requirements_txt` | string | No | `requirements.txt` contents, one pinned package per line. |
| `config` | object | No | Non-secret key/value pairs surfaced as environment variables. |
| `md_secret_names` | string[] | No | MotherDuck secret names surfaced as environment variables. End-to-end secret delivery is in development. |
## Output schema
```json
{
"success": boolean,
"flight": {
"id": string,
"name": string,
"schedule_cron": string|null,
"current_version": number
},
"error": string
}
```
## Example usage
Minimal Flight:
```json
{
"name": "heartbeat",
"source_code": "import duckdb\n\ndef main():\n duckdb.connect('md:').execute('SELECT 1').fetchall()\n print('ok')\n",
"md_token_name": "analytics_token",
"requirements_txt": "duckdb==1.5.2"
}
```
Scheduled Flight with config:
```json
{
"name": "hourly_metrics",
"source_code": "...",
"md_token_name": "analytics_token",
"requirements_txt": "duckdb==1.5.2\nrequests==2.32.4",
"schedule_cron": "0 * * * *",
"config": { "REGION": "eu-central-1" }
}
```
## Related
- [`update_flight`](../update-flight) — Modify an existing Flight.
- [`edit_flight_source`](../edit-flight-source) — Surgical source edit.
- [`run_flight`](../run-flight) — Trigger a manual run after creation.
- [`MD_CREATE_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-create-flight) — SQL equivalent.
---
Source: https://motherduck.com/docs/sql-reference/mcp/update-flight
# update_flight
> Update a Flight's source, requirements, config, token, secrets, name, or schedule.
Update a [Flight](/concepts/flights). Any subset of `name`, `source_code`, `requirements_txt`, `schedule_cron`, `config`, `md_token_name`, or `md_secret_names` may be provided.
Updates to `source_code`, `requirements_txt`, `config`, `md_secret_names`, or `md_token_name` produce a new `FlightVersion`. Updates to `name` or `schedule_cron` are metadata-only.
## Description
`update_flight` is a PATCH operation: omitted fields are left unchanged. To clear the schedule, pass `schedule_cron` as an empty string; omitting it leaves the schedule unchanged.
`config` and `md_secret_names` are **full replacements** — to change one entry, send the full map or list with the change applied.
The SQL equivalent is [`MD_UPDATE_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-update-flight).
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
| `name` | string | No | Updated Flight name. Metadata-only. |
| `schedule_cron` | string | No | Updated 5-field cron expression (UTC). Pass `""` to clear the schedule. Metadata-only. |
| `source_code` | string | No | Updated Python entrypoint source. Bumps the version. |
| `requirements_txt` | string | No | Updated `requirements.txt` contents. Bumps the version. |
| `config` | object | No | Replacement config map (full replace). Bumps the version. |
| `md_token_name` | string | No | Updated MotherDuck access token label. Bumps the version. |
| `md_secret_names` | string[] | No | Replacement list of secret names (full replace). Bumps the version. |
## Output schema
```json
{
"success": boolean,
"flight": {
"id": string,
"name": string,
"schedule_cron": string|null,
"current_version": number
},
"error": string
}
```
## Example usage
Rename only:
```json
{ "id": "80000000-...", "name": "analytics_hourly_sync" }
```
Update source (bumps version):
```json
{
"id": "80000000-...",
"source_code": "def main():\n print('v2')\n"
}
```
Clear the schedule:
```json
{ "id": "80000000-...", "schedule_cron": "" }
```
## Related
- [`edit_flight_source`](../edit-flight-source) — Edit source without resending the whole file.
- [`get_flight`](../get-flight) — Read current state before editing.
- [`MD_UPDATE_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-update-flight) — SQL equivalent.
---
Source: https://motherduck.com/docs/sql-reference/mcp/edit-flight-source
# edit_flight_source
> Edit a Flight's source code with one or more find-and-replace operations, producing a new version.
Edit a [Flight](/concepts/flights)'s `source_code` by applying one or more text replacements, then save as a new `FlightVersion`. The tool reads the current source, applies the edits in sequence, validates the result, and persists.
Use this when you want to change a small part of a Flight without resending the entire file through [`update_flight`](../update-flight).
## Description
Each edit is a `{old_string, new_string, replace_all?}` object. `old_string` must occur exactly once in the source unless `replace_all` is true. Edits apply sequentially: edit N sees the source after edits 1 through N-1.
No prior `get_flight` call is required — the tool reads the current source itself.
This tool is MCP-only; there is no direct SQL equivalent. To achieve the same outcome in SQL, read the source through [`MD_GET_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-get-flight), modify it client-side, and call [`MD_UPDATE_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-update-flight) with the full updated source.
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
| `edits` | array | Yes | List of edit objects (see below). Must contain at least one. |
Each entry in `edits`:
| Field | Type | Required | Description |
|---|---|---|---|
| `old_string` | string | Yes | Exact text to find and replace. Must be unique in the source unless `replace_all` is true. |
| `new_string` | string | Yes | The replacement text. Must differ from `old_string`. |
| `replace_all` | boolean | No | If true, replace every occurrence. Default `false`. |
## Output schema
```json
{
"success": boolean,
"flight": {
"id": string,
"name": string,
"current_version": number
},
"error": string
}
```
## Example usage
Change one line:
```json
{
"id": "80000000-...",
"edits": [
{
"old_string": "duckdb==1.5.1",
"new_string": "duckdb==1.5.2"
}
]
}
```
Rename every occurrence of a variable:
```json
{
"id": "80000000-...",
"edits": [
{
"old_string": "raw_table",
"new_string": "raw_events",
"replace_all": true
}
]
}
```
## Related
- [`update_flight`](../update-flight) — Send a full replacement source.
- [`get_flight`](../get-flight) — Inspect the source before editing.
- [`list_flight_versions`](../list-flight-versions) — See the versions created by edits.
---
Source: https://motherduck.com/docs/sql-reference/mcp/delete-flight
# delete_flight
> Permanently delete a Flight, its versions, schedule, and run history.
Permanently delete a [Flight](/concepts/flights), including all versions, schedule, and run history. This action cannot be undone.
The SQL equivalent is [`MD_DELETE_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-delete-flight).
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
## Output schema
```json
{
"success": boolean,
"error": string
}
```
## Example usage
```json
{ "id": "80000000-0000-0000-0000-000000000001" }
```
After deletion, calls to other `*_flight*` tools with the same `id` return `does not exist`.
## Related
- [`list_flights`](../list-flights) — Verify the Flight is gone.
- [`MD_DELETE_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-delete-flight) — SQL equivalent.
---
Source: https://motherduck.com/docs/sql-reference/mcp/run-flight
# run_flight
> Trigger an on-demand execution of a Flight using its current version.
Trigger an on-demand execution of a [Flight](/concepts/flights). Returns a Run record immediately; the run is asynchronous and starts in `PENDING` or `RUNNING`. Use [`list_flight_runs`](../list-flight-runs) to poll for completion and [`get_flight_run_logs`](../get-flight-run-logs) to read the output.
The SQL equivalent is [`MD_RUN_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-run-flight).
## Description
`run_flight` locks the new run to the Flight's current version. Subsequent updates to the Flight do not affect this run; only the next run picks up the updated source.
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
## Output schema
```json
{
"success": boolean,
"run": {
"flight_id": string,
"flight_name": string,
"flight_version": number,
"run_number": number,
"status": string, // PENDING | RUNNING
"is_scheduled": boolean, // false for on-demand
"created_at": string
},
"error": string
}
```
## Example usage
```json
{ "id": "80000000-0000-0000-0000-000000000001" }
```
## Related
- [`list_flight_runs`](../list-flight-runs) — Watch for completion.
- [`get_flight_run_logs`](../get-flight-run-logs) — Read stdout/stderr.
- [`cancel_flight_run`](../cancel-flight-run) — Cancel an in-progress run.
- [`MD_RUN_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-run-flight) — SQL equivalent.
---
Source: https://motherduck.com/docs/sql-reference/mcp/list-flight-runs
# list_flight_runs
> List the execution history of a Flight, newest first.
List the runs of a [Flight](/concepts/flights), newest first. Each run has a sequential `run_number`, a status (`PENDING`, `RUNNING`, `SUCCEEDED`, `FAILED`, or `CANCELLED`), and timing metadata.
The SQL equivalent is [`MD_FLIGHT_RUNS`](/sql-reference/motherduck-sql-reference/flights/md-flight-runs).
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
| `limit` | integer | No | Max results to return (default: 100, max: 500). |
## Output schema
```json
{
"success": boolean,
"runs": [
{
"flight_id": string,
"flight_name": string,
"flight_version": number,
"run_number": number,
"is_scheduled": boolean,
"status": string,
"created_at": string
}
],
"count": number,
"error": string
}
```
## Example usage
```json
{ "id": "80000000-0000-0000-0000-000000000001", "limit": 10 }
```
## Related
- [`run_flight`](../run-flight) — Trigger an on-demand run.
- [`get_flight_run_logs`](../get-flight-run-logs) — Read a run's output.
- [`cancel_flight_run`](../cancel-flight-run) — Cancel an in-progress run.
- [`MD_FLIGHT_RUNS`](/sql-reference/motherduck-sql-reference/flights/md-flight-runs) — SQL equivalent.
---
Source: https://motherduck.com/docs/sql-reference/mcp/get-flight-run-logs
# get_flight_run_logs
> Fetch the logs and run record for a single Flight run.
Fetch the plain-text combined stdout and stderr of a [Flight](/concepts/flights) run, plus the matching `Run` record (status, exit code, timing). The response also reports whether the log was truncated.
The SQL equivalent is [`MD_FLIGHT_LOGS`](/sql-reference/motherduck-sql-reference/flights/md-flight-logs) — note that the SQL surface returns only the logs, while this MCP tool also returns the run record.
## Description
Use `get_flight_run_logs` to interpret a failed run without a follow-up call: status, exit code, and timing arrive in the same response as the log content. For runs with large logs, pass `max_bytes` to cap the response size; the response returns the tail and sets `truncated: true`.
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
| `run_number` | integer | Yes | Sequential run number from [`list_flight_runs`](../list-flight-runs). |
| `max_bytes` | integer | No | Maximum log bytes to return. Minimum 1024. Truncation returns the tail. |
## Output schema
```json
{
"success": boolean,
"run": {
"flight_id": string,
"run_number": number,
"flight_version": number,
"status": string, // PENDING | RUNNING | SUCCEEDED | FAILED | CANCELLED
"exit_code": number|null,
"created_at": string,
"started_at": string|null,
"completed_at": string|null
},
"logs": string, // Combined stdout + stderr
"truncated": boolean, // True if max_bytes truncated the log
"error": string
}
```
## Example usage
Read the full logs for run 42:
```json
{ "id": "80000000-...", "run_number": 42 }
```
Read only the last 4 KB:
```json
{ "id": "80000000-...", "run_number": 42, "max_bytes": 4096 }
```
## Related
- [`list_flight_runs`](../list-flight-runs) — Find the `run_number` to read.
- [`MD_FLIGHT_LOGS`](/sql-reference/motherduck-sql-reference/flights/md-flight-logs) — SQL equivalent (logs only).
---
Source: https://motherduck.com/docs/sql-reference/mcp/cancel-flight-run
# cancel_flight_run
> Cancel an in-progress Flight run.
Cancel an in-progress run of a [Flight](/concepts/flights), identified by the Flight UUID and the sequential `run_number` (from [`list_flight_runs`](../list-flight-runs)).
Returns `canceled: true` on a successful transition. Calling on an already-terminal run (`SUCCEEDED`, `FAILED`, `CANCELLED`) or one that doesn't exist returns a tool error.
The SQL equivalent is [`MD_CANCEL_FLIGHT_RUN`](/sql-reference/motherduck-sql-reference/flights/md-cancel-flight-run).
## Input parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | string (UUID) | Yes | The Flight UUID. |
| `run_number` | integer | Yes | Sequential run number to cancel. |
## Output schema
```json
{
"success": boolean,
"canceled": boolean,
"error": string
}
```
## Example usage
```json
{ "id": "80000000-0000-0000-0000-000000000001", "run_number": 42 }
```
## Related
- [`list_flight_runs`](../list-flight-runs) — Find runs that are still in progress.
- [`run_flight`](../run-flight) — Trigger a new run.
- [`MD_CANCEL_FLIGHT_RUN`](/sql-reference/motherduck-sql-reference/flights/md-cancel-flight-run) — SQL equivalent.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/alter-table
# ALTER TABLE
> ALTER TABLE statement for modifying table structure in DuckDB.
The ALTER TABLE command in MotherDuck works the same as in DuckDB. See [ALTER TABLE](https://duckdb.org/docs/stable/sql/statements/alter_table) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/attach-detach
# ATTACH/DETACH
> ATTACH and DETACH statements for connecting to external databases in DuckDB.
The ATTACH and DETACH statements in MotherDuck works the same as in DuckDB. See [ATTACH/DETACH](https://duckdb.org/docs/stable/sql/statements/attach) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/call
# CALL
> CALL statement for executing table functions in DuckDB.
The CALL statement in MotherDuck works the same as in DuckDB. See [CALL](https://duckdb.org/docs/stable/sql/statements/call) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/comment-on
# COMMENT ON
> COMMENT ON statement for adding descriptions to database objects in DuckDB.
The COMMENT ON statement in MotherDuck works the same as in DuckDB. See [COMMENT ON](https://duckdb.org/docs/stable/sql/statements/comment_on) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/copy
# COPY
> COPY statement for importing and exporting data in DuckDB.
The COPY statement in MotherDuck works the same as in DuckDB. See [COPY](https://duckdb.org/docs/stable/sql/statements/copy) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/rest-api/dashboards-create-embed-session
# Create a Dive embed session
> Creates an embed session for the specified Dive.
`POST /v1/dives/{dive_id}/embed-session`
Creates an embed session for the specified Dive.
## Request
---
Source: https://motherduck.com/docs/sql-reference/rest-api/users-create-token
# Create an access token for a user
> Create an access token for a user
`POST /v1/users/{username}/tokens`
Create an access token for a user
:::note
- **Token Creation Scope**: Through the API, you can only create tokens for:
- Your own user account
- Service accounts within your organization
- Admins cannot create tokens for other non-service-account members through the API
- **For service account token creation**, ensure you are using an **Admin token** for authentication. The token generated by this call will be the service account's own token for its operations.
- For detailed guidance on service account token creation and best practices, see [Create and configure service accounts](/docs/key-tasks/service-accounts-guide/create-and-configure-service-accounts/#create-an-access-token).
- If a service account is created through the admin API, connect to that service account with a read/write token before using read scaling tokens.
- Each token is tied to a specific user. Use the exact `username` that was specified during service account creation in the path `/v1/users/:username/tokens`.
- If the optional `ttl` parameter is not specified, the access token will remain valid indefinitely until revoked by an administrator.
:::
## Request
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/create-index
# CREATE INDEX
> Use CREATE INDEX to speed up point lookups and highly selective queries in MotherDuck.
The `CREATE INDEX` statement creates an [Adaptive Radix Tree (ART)](https://duckdb.org/docs/stable/sql/indexes) index on one or more columns. In MotherDuck, indexes speed up point lookups, range queries, and some highly selective joins.
## Syntax
```sql
CREATE [UNIQUE] INDEX [IF NOT EXISTS]
ON ( [, ...]);
```
## When to use indexes
Indexes work best for very selective queries that return a small fraction of the table's rows. For example:
- **Point lookups** -- finding a single row by ID or key
- **Highly selective range queries** -- filtering on a narrow range that matches less than ~0.1% of the data
- **Selective joins** -- joining on indexed columns with high selectivity
For broader analytical queries that scan large portions of a table, MotherDuck's columnar storage and zone maps already provide strong performance without indexes.
## Example
```sql
-- Create a table and an index
CREATE TABLE users (id INTEGER, name VARCHAR);
INSERT INTO users VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');
CREATE INDEX idx_user_id ON users(id);
-- Point lookup uses the index
SELECT * FROM users WHERE id = 1;
```
You can verify that the index is being used with the [EXPLAIN](/sql-reference/motherduck-sql-reference/explain/) statement:
```sql
EXPLAIN SELECT * FROM users WHERE id = 1;
-- Shows INDEX_SCAN when the index is used
```
## Constraints
Indexes are also created automatically when you add a `UNIQUE` or `PRIMARY KEY` constraint. This lets you use features like [`INSERT ... ON CONFLICT`](https://duckdb.org/docs/stable/sql/statements/insert#on-conflict-clause) for upserts and deduplication.
```sql
CREATE TABLE events (
event_id INTEGER PRIMARY KEY,
event_name VARCHAR
);
-- Upsert: insert or update on conflict
INSERT INTO events VALUES (1, 'signup')
ON CONFLICT (event_id) DO UPDATE SET event_name = excluded.event_name;
```
## Trade-offs
Indexes slow down `INSERT`, `UPDATE`, and `DELETE` operations because the index must be updated alongside the table data. If your workload is write-heavy and doesn't benefit from selective lookups, skip the index.
ART indexes also need to fit in memory during creation, so they may not be practical for very large columns.
For more details on DuckDB's index implementation, see the [DuckDB Indexes documentation](https://duckdb.org/docs/stable/sql/indexes).
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/create-macro
# CREATE MACRO
> CREATE MACRO statement for defining reusable SQL expressions in DuckDB.
The CREATE MACRO statement in MotherDuck works the same as in DuckDB. See [CREATE MACRO](https://duckdb.org/docs/stable/sql/statements/create_macro) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/rest-api/users-create-service-account
# Create new user
> Create user is restricted to creating a user with a 'Member' role
::::info
This endpoint is used to create new users / service accounts. For a detailed guide, see [Create and configure service accounts](/key-tasks/service-accounts-guide/create-and-configure-service-accounts/).
::::
`POST /v1/users`
Create user is restricted to creating a user with a `Member` role.
## Request
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/create-table
# CREATE TABLE
> CREATE TABLE statement for defining new tables in DuckDB.
The CREATE TABLE statement in MotherDuck works the same as in DuckDB. See [CREATE TABLE](https://duckdb.org/docs/stable/sql/statements/create_table) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/delete
# DELETE
> DELETE statement for removing rows from DuckDB tables.
The DELETE statement in MotherDuck works the same as in DuckDB. See [DELETE](https://duckdb.org/docs/stable/sql/statements/delete) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/rest-api/users-delete
# Delete a user
> Permanently delete a user and all of their data. THIS CANNOT BE UNDONE
`DELETE /v1/users/{username}`
Permanently delete a user and all of their data. THIS CANNOT BE UNDONE
## Request
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/drop
# DROP
> DROP statement for removing tables, views, and other objects in DuckDB.
The DROP statement in MotherDuck works the same as in DuckDB. See [DROP](https://duckdb.org/docs/stable/sql/statements/drop) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-sql-reference
# DuckDB SQL
> DuckDB SQL Reference
DuckDB provides a rich SQL dialect with powerful analytical capabilities. MotherDuck uses DuckDB's SQL engine, so all standard DuckDB syntax works seamlessly.
This reference covers core SQL statements, data types, functions, window functions, and query syntax. For MotherDuck-specific extensions like cloud database management and sharing, see the [MotherDuck SQL](/sql-reference/motherduck-sql-reference) reference.
:::tip
DuckDB maintains comprehensive documentation at [duckdb.org/docs](https://duckdb.org/docs/stable/). The reference here focuses on the most commonly used features.
:::
## Included pages
- [DuckDB statements](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements): DuckDB SQL statements reference
- [Query syntax](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/query-syntax): DuckDB query syntax including SELECT, FROM, WHERE, GROUP BY, ORDER BY, and other clauses.
- [Data types](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/data-types): Supported data types in DuckDB including numeric, string, date/time, and complex types.
- [Enum data type](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/enum): DuckDB enum data type for defining columns with a fixed set of string values.
- [Expressions](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/expressions): DuckDB expression syntax including operators, CASE, subqueries, and type casts.
- [Functions](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/functions): Built-in scalar functions in DuckDB for string manipulation, math, dates, and more.
- [Aggregate functions](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/aggregate-functions): DuckDB aggregate functions like SUM, COUNT, AVG, and statistical functions.
- [Window functions](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/window-functions): DuckDB window functions for ranking, running totals, and analytical queries.
- [Configurations](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/configurations): DuckDB configuration options for memory, threads, and query behavior.
- [Constraints](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/constraints): Table constraints in DuckDB including PRIMARY KEY, UNIQUE, NOT NULL, and CHECK.
- [Information schema](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/information-schema): DuckDB information_schema views for querying database metadata.
- [Metadata functions](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/metadata-functions): DuckDB functions for querying table and column metadata programmatically.
- [PRAGMA statements](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/pragma-statements): PRAGMA statements for DuckDB configuration and metadata queries.
- [SAMPLE](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/sample): SAMPLE clause for retrieving random subsets of query results in DuckDB.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/duckdb-statements
# DuckDB statements
> DuckDB SQL statements reference
Reference documentation for DuckDB SQL statements. These statements work in both local DuckDB and MotherDuck cloud environments.
**Common operations:**
- **Data manipulation**: `SELECT`, `INSERT`, `UPDATE`, `DELETE`
- **Schema management**: `CREATE TABLE`, `ALTER TABLE`, `DROP`
- **Data loading**: `COPY`, `EXPORT`
- **Advanced queries**: `PIVOT`, `UNPIVOT`
## Included pages
- [ALTER TABLE](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/alter-table): ALTER TABLE statement for modifying table structure in DuckDB.
- [ATTACH/DETACH](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/attach-detach): ATTACH and DETACH statements for connecting to external databases in DuckDB.
- [CALL](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/call): CALL statement for executing table functions in DuckDB.
- [COMMENT ON](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/comment-on): COMMENT ON statement for adding descriptions to database objects in DuckDB.
- [COPY](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/copy): COPY statement for importing and exporting data in DuckDB.
- [CREATE INDEX](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/create-index): Use CREATE INDEX to speed up point lookups and highly selective queries in MotherDuck.
- [CREATE MACRO](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/create-macro): CREATE MACRO statement for defining reusable SQL expressions in DuckDB.
- [CREATE TABLE](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/create-table): CREATE TABLE statement for defining new tables in DuckDB.
- [DELETE](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/delete): DELETE statement for removing rows from DuckDB tables.
- [DROP](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/drop): DROP statement for removing tables, views, and other objects in DuckDB.
- [EXPORT](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/export): EXPORT statement for exporting database contents to files in DuckDB.
- [INSERT](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/insert): INSERT statement for adding rows to tables in DuckDB.
- [PIVOT](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/pivot): PIVOT statement for transforming rows to columns in DuckDB.
- [SELECT](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/select): SELECT statement syntax and options in DuckDB.
- [SET/RESET](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/set-reset): SET and RESET statements for configuring DuckDB session options.
- [UNPIVOT](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/unpivot): UNPIVOT statement for transforming columns to rows in DuckDB.
- [UPDATE](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/update): UPDATE statement for modifying existing rows in DuckDB tables.
- [USE](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/use): USE statement for changing the default database or schema in DuckDB.
- [VACUUM](https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/vacuum): VACUUM statement for optimizing storage in DuckDB.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/export
# EXPORT
> EXPORT statement for exporting database contents to files in DuckDB.
The EXPORT statement in MotherDuck works the same as in DuckDB. See [Export & Import Database](https://duckdb.org/docs/stable/sql/statements/export) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/rest-api/ducklings-get-active-accounts
# Get active accounts
> [Preview] Get active accounts in an organization along with active Ducklings per account. Requires 'Admin' role
`GET /v1/active_accounts`
[Preview] Get active accounts in an organization along with active Ducklings per account. Requires 'Admin' role
---
Source: https://motherduck.com/docs/sql-reference/rest-api/ducklings-get-duckling-config-for-user
# Get user Duckling configuration
> Gets Duckling (instance) configuration for a user. Requires 'Admin' role.
`GET /v1/users/{username}/instances`
Gets Duckling (instance) configuration for a user. Requires 'Admin' role.
## Request
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/insert
# INSERT
> INSERT statement for adding rows to tables in DuckDB.
THe INSERT statement in MotherDuck works the same as in DuckDB. See [INSERT Statement](https://duckdb.org/docs/stable/sql/statements/insert) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/introduction
# Introduction to MD_INFORMATION_SCHEMA
> Introduction to MD_INFORMATION_SCHEMA
The MotherDuck `MD_INFORMATION_SCHEMA` views are read-only, system-defined views that provide metadata information
about your MotherDuck objects.
The following table lists all `MD_INFORMATION_SCHEMA` views that you can query to retrieve metadata information:
| Resource Type | MD_INFORMATION_SCHEMA View |
|-----------------|----------------------------------|
| Database | [DATABASES](databases.md) |
| Database Size | [PRAGMA database_size](database_size.md) |
| Database Shares | [OWNED_SHARES](owned_shares.md) [SHARED_WITH_ME](shared_with_me.md) |
| Database Snapshots | [DATABASE_SNAPSHOTS](database_snapshots.md) |
| Storage | [STORAGE_INFO](storage_info.md) _includes history_ |
| Queries | [RECENT_QUERIES](recent_queries.md) |
| Queries | [QUERY_HISTORY](query_history.md) |
## Example usage
```sql
-- list all databases you created
from md_information_schema.databases;
-- list all shares you created
from md_information_schema.owned_shares;
-- select specific columns
select name, url, access, visibility from md_information_schema.owned_shares;
-- set md_information_schema as the current database
use md_information_schema;
-- list all the views in md_information_schema
show tables;
```
---
Source: https://motherduck.com/docs/sql-reference/rest-api/users-delete-token
# Invalidate a user access token
> Invalidate a user access token
`DELETE /v1/users/{username}/tokens/{token_id}`
Invalidate a user access token
## Request
---
Source: https://motherduck.com/docs/sql-reference/rest-api/users-list-tokens
# List a user's access tokens
> List a user's access tokens
`GET /v1/users/{username}/tokens`
List a user's access tokens
## Request
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-attached-databases
# MD_ATTACHED_DATABASES
> List databases attached to your DuckDB and MotherDuck session.
`MD_ATTACHED_DATABASES()` lists the databases attached in your session, including MotherDuck databases, shares, and local databases.
Use [`SHOW ALL DATABASES`](/sql-reference/motherduck-sql-reference/show-databases) when you also want to see detached MotherDuck databases available to you.
## Syntax
```sql
FROM md_attached_databases();
```
## Output
| Column Name | Data Type | Value |
|-------------|-----------|-------|
| `alias` | VARCHAR | Attached database alias |
| `is_share` | BOOLEAN | Whether the attached database is a share |
| `is_readonly` | BOOLEAN | Whether the database is attached read-only |
| `is_error_catalog` | BOOLEAN | Whether the attachment is an error catalog |
| `error_message` | VARCHAR | Error message for error catalogs, if any |
| `is_ducklake` | BOOLEAN | Whether the attached database is a DuckLake database |
## Example usage
```sql
FROM md_attached_databases();
```
```sql
SELECT alias
FROM md_attached_databases()
WHERE is_share;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-list-buckets-for-secret
# MD_LIST_BUCKETS_FOR_SECRET
> List S3 buckets visible to a named MotherDuck secret.
`MD_LIST_BUCKETS_FOR_SECRET()` lists the S3 buckets visible to the named secret.
:::note
This function takes a **secret name**, not a bucket name. It supports `S3` secrets only.
:::
## Syntax
```sql
FROM md_list_buckets_for_secret('');
```
## Output
| Column Name | Data Type | Value |
|-------------|-----------|-------|
| `name` | VARCHAR | Bucket name |
| `creation_date` | DATE | Bucket creation date |
| `region` | VARCHAR | Bucket region |
| `arn` | VARCHAR | Bucket ARN, when available |
## Example usage
```sql
FROM md_list_buckets_for_secret('__default_s3');
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-list-files
# MD_LIST_FILES
> List files and folders in S3 and Azure storage from SQL.
`MD_LIST_FILES()` lists files and folders at a cloud storage path.
:::note
`MD_LIST_FILES()` supports:
- `s3://`
- `azure://`
- `az://`
It does **not** accept `r2://`, `gcs://`, or `gs://` paths, but MotherDuck can still query those storage providers normally.
:::
## Syntax
```sql
FROM md_list_files('');
```
## Output
| Column Name | Data Type | Value |
|-------------|-----------|-------|
| `name` | VARCHAR | File or folder name relative to the requested prefix |
| `type` | VARCHAR | Entry type, such as `FILE` or `FOLDER` |
| `size` | UBIGINT | File size in bytes; `NULL` for folders |
| `last_modified` | TIMESTAMP WITH TIME ZONE | Last modification time; `NULL` for folders |
## Example usage
```sql
FROM md_list_files('s3://us-prd-motherduck-open-datasets/');
```
```sql
FROM md_list_files('azure://my-container/raw/');
```
## Notes
- For private storage, make sure an appropriate secret is available. See [CREATE SECRET](/sql-reference/motherduck-sql-reference/create-secret).
- For S3 bucket discovery by secret, use [`MD_LIST_BUCKETS_FOR_SECRET()`](/sql-reference/motherduck-sql-reference/md-list-buckets-for-secret).
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-live-duckling-size
# MD_LIVE_DUCKLING_SIZE
> Return the current Duckling instance type for the active MotherDuck connection.
`MD_LIVE_DUCKLING_SIZE()` returns the Duckling instance type for the active MotherDuck connection.
This is useful when you want to inspect which class of execution instance is serving your session.
## Syntax
```sql
FROM md_live_duckling_size();
```
## Output
| Column Name | Data Type | Value |
|-------------|-----------|-------|
| `type` | VARCHAR | Current Duckling instance type, for example `Pulse` |
## Example usage
```sql
FROM md_live_duckling_size();
```
Example result:
```text
type
-----
Pulse
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-user
# MD_USER
> Return the current MotherDuck user name.
`MD_USER()` returns the current MotherDuck user name for the active connection.
In MotherDuck sessions, `USER`, `CURRENT_USER()`, and `SESSION_USER` resolve to the same value.
## Syntax
```sql
SELECT md_user();
-- Equivalent aliases in a MotherDuck session
SELECT user;
SELECT user();
SELECT current_user();
SELECT session_user;
```
::::info
Note that DuckDB and MotherDuck allow you to use niladic (no-argument) functions like `user` also as a column name. This can lead to a silent failure with unexpected values when dropping a `user` column.
::::
## Output
| Column Name | Data Type | Value |
|-------------|-----------|-------|
| `md_user()` | VARCHAR | Current MotherDuck user name |
## Example usage
```sql
SELECT md_user();
```
```sql
SELECT current_user();
```
:::note
If you are not connected to MotherDuck, DuckDB may return its default local user instead.
:::
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-version
# MD_VERSION
> Inspect the loaded MotherDuck extension version and build hash.
MotherDuck exposes `MD_VERSION` both as a scalar function and as a pragma.
Use the scalar function when you only need the version string. Use the pragma when you also want the extension hash.
## Syntax
```sql
SELECT md_version();
PRAGMA md_version;
```
## Output
`SELECT md_version();` returns a single `VARCHAR` value.
`PRAGMA md_version;` returns:
| Column Name | Data Type | Value |
|-------------|-----------|-------|
| `md_extension_version` | VARCHAR | Loaded MotherDuck extension version |
| `md_extension_hash` | VARCHAR | MotherDuck extension build hash |
## Example usage
```sql
SELECT md_version();
```
```sql
PRAGMA md_version;
```
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/motherduck-sql-reference
# MotherDuck SQL
> MotherDuck-specific SQL extensions and cloud database management
MotherDuck extends DuckDB with cloud-native SQL capabilities for managing databases, shares, secrets, and connections. These statements let you work with MotherDuck's serverless infrastructure directly from SQL.
**Key capabilities:**
- **Database management**: Create, copy, attach, and drop cloud databases
- **Data sharing**: Share data with other users and organizations
- **Secrets management**: Store and manage credentials securely
- **AI functions**: Generate embeddings, run prompts, and get SQL assistance
- **Dives**: Create and manage interactive data visualizations
For standard SQL operations, see the [DuckDB Syntax](/sql-reference/duckdb-sql-reference) reference.
## Included pages
- [AI Functions](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/ai-functions): MotherDuck AI SQL functions for text generation, embeddings, and SQL assistance.
- [ALTER DATABASE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/alter-database): Update storage-related settings on a MotherDuck database.
- [ALTER DATABASE SET SNAPSHOT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/alter-database-snapshot): Restore a database from a snapshot using ALTER DATABASE SET SNAPSHOT TO.
- [ALTER SNAPSHOT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/alter-snapshot): Rename or remove names from database snapshots using ALTER SNAPSHOT.
- [ATTACH](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/attach): Attach local databases, MotherDuck databases, or public shares to your session
- [COPY FROM DATABASE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/copy-database): Copy a database from one location to another in MotherDuck
- [COPY FROM DATABASE (OVERWRITE)](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/copy-database-overwrite): Overwrite a database with a zero-copy clone from another database.
- [CREATE DATABASE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/create-database): Create a database, zero-copy clone from an existing database, or import a local DuckDB file into MotherDuck.
- [CREATE SECRET](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/create-secret): Create a secret in MotherDuck
- [CREATE SHARE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/create-share): Create a share from a database to share data with other users
- [CREATE SNAPSHOT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/create-snapshot): Create a snapshot of a MotherDuck database for recovery or read scaling.
- [DESCRIBE SHARE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/describe-share): Get details about a specific share by name or URL.
- [DETACH](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/detach): Detach local, remote, or shared databases from your session
- [DROP DATABASE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/drop-database): Remove a database from MotherDuck.
- [DROP SECRET](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/delete-secret): Delete a secret from MotherDuck or local storage.
- [DROP SHARE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/drop-share): Delete a share and revoke access for all attached users.
- [EXPLAIN](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/explain): Display the physical query plan without executing the query.
- [EXPLAIN ANALYZE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/explain-analyze): Execute a query and display performance metrics for each operator.
- [GRANT READ ON SHARE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/grant-access): Give users access to a restricted share.
- [LIST SECRETS](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/list-secrets): List all secrets stored in memory and MotherDuck.
- [LIST SHARES](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/list-shares): List all shares created by the current user.
- [MD_RUN parameter](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-run-parameter): Control whether table functions run locally or remotely.
- [PRINT_MD_TOKEN pragma](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/print-md-token): Retrieve your MotherDuck authentication token.
- [REFRESH DATABASE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/refresh-database): Sync databases with the latest snapshot or share updates.
- [REVOKE READ ON SHARE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/revoke-access): Remove user access from a restricted share.
- [SHOW ALL DATABASES](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/show-databases): List all MotherDuck, DuckDB, and shared databases.
- [SHUTDOWN](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/shutdown-terminate): Gracefully shut down or force-terminate your Duckling to manage compute costs and recover from stuck queries.
- [TEMPORARY TABLES](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/temporary-tables): Create local temporary tables for session-scoped data.
- [UNDROP DATABASE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/undrop-database): Restore a dropped MotherDuck database within its snapshot retention window.
- [UPDATE SHARE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/update-share): Manually update a share with a new database snapshot.
- [Server Connection Management](https://motherduck.com/docs/category/server-connection-management): Managing MotherDuck server connections
- [Introduction to MD_INFORMATION_SCHEMA](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md_information_schema/introduction): Introduction to MD_INFORMATION_SCHEMA
- [Flights functions](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/flights): SQL table functions for creating, scheduling, running, and inspecting MotherDuck Flights.
- [MD_ATTACHED_DATABASES](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-attached-databases): List databases attached to your DuckDB and MotherDuck session.
- [MD_LIST_BUCKETS_FOR_SECRET](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-list-buckets-for-secret): List S3 buckets visible to a named MotherDuck secret.
- [MD_LIST_FILES](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-list-files): List files and folders in S3 and Azure storage from SQL.
- [MD_LIVE_DUCKLING_SIZE](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-live-duckling-size): Return the current Duckling instance type for the active MotherDuck connection.
- [MD_USER](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-user): Return the current MotherDuck user name.
- [MD_VERSION](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/md-version): Inspect the loaded MotherDuck extension version and build hash.
- [RESULT](https://motherduck.com/docs/sql-reference/motherduck-sql-reference/result): Run a SELECT asynchronously and query its cached results like a table.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/pivot
# PIVOT
> PIVOT statement for transforming rows to columns in DuckDB.
The PIVOT statement in MotherDuck works the same as in DuckDB. See [PIVOT Statement](https://duckdb.org/docs/stable/sql/statements/pivot) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/motherduck-sql-reference/result
# RESULT
> Run a SELECT asynchronously and query its cached results like a table.
The `RESULT` statements let you run a `SELECT` asynchronously, cache rows as they are produced, and query that cached output like a table.
This is most valuable for presenting users in a data application with rows as they come in instead of waiting for the full result. Use the [Results concept page](/concepts/results) for lifecycle behavior and caching details.
## Syntax
```sql
CREATE [ OR REPLACE ] RESULT [ IF NOT EXISTS ] AS ;
FROM [ LIMIT ];
PAUSE RESULT [ IF EXISTS ] ;
RESUME RESULT [ IF EXISTS ] ;
CANCEL RESULT [ IF EXISTS ] ;
DROP RESULT [ IF EXISTS ] ;
SHOW ALL RESULTS;
FROM md_show_results();
```
`RESULT` accepts `SELECT` statements only. The result starts building asynchronously when it is created.
### _OR REPLACE_ clause
`OR REPLACE` drops the existing result and creates a new one with the same name.
### _IF NOT EXISTS_ clause
If a result with that name already exists, `IF NOT EXISTS` suppresses the error and leaves the existing result unchanged.
### Accessing a result
You can query a result like a table:
```sql
FROM ;
FROM LIMIT ;
```
The cached output may be partial while the result is still building. Depending on the query and the current state of the result, MotherDuck may read from the cache, wait for more rows, or re-run the underlying `SELECT`.
### Lifecycle statements
You can manage a result after creation with:
- `PAUSE RESULT`
- `RESUME RESULT`
- `CANCEL RESULT`
- `DROP RESULT`
`CANCEL RESULT` permanently stops the background job. A canceled result cannot be resumed.
### Introspecting results
Use `SHOW ALL RESULTS` to inspect all results in the current session.
If you want to filter, sort, or limit that output, use `md_show_results()`.
## Output
`SHOW ALL RESULTS` and `md_show_results()` return:
| Column Name | Data Type | Value |
|-------------|-----------|-------|
| `name` | VARCHAR | Name of the result |
| `error` | VARCHAR | Error message, if any |
| `status` | VARCHAR | Current status: `BUILDING`, `PAUSED`, or `DONE` |
| `row_count` | BIGINT | Number of cached rows available |
## Example usage
```sql
CREATE RESULT top_urls AS
SELECT url, count(*) AS requests
FROM pypi_downloads
GROUP BY url;
FROM top_urls LIMIT 10;
SHOW ALL RESULTS;
FROM md_show_results()
WHERE name = 'top_urls';
```
## Notes
- Results are stored in memory and are not persisted across client restarts.
- `DROP RESULT` permanently removes the result and its cached rows.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/select
# SELECT
> SELECT statement syntax and options in DuckDB.
The SELECT statement in MotherDuck works the same as in DuckDB. See [SELECT Statement](https://duckdb.org/docs/stable/sql/statements/select) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/rest-api/ducklings-set-duckling-config-for-user
# Set user Duckling configuration
> Sets Duckling (instance) configuration for a user. Requires 'Admin' role
::::info
This endpoint is used to configure user-specific settings, primarily for setting Duckling sizes for service accounts.
For a complete walkthrough of service account management, see [Create and configure service accounts](/docs/key-tasks/service-accounts-guide/create-and-configure-service-accounts/#configure-ducklings).
::::
::::caution[Username Parameter]
When configuring a service account, ensure the `username` in the path (`/v1/users/:username/instances`) is the specific username defined when creating the service account. The endpoint path uses `instances` for legacy reasons but configures Ducklings.
::::
`PUT /v1/users/{username}/instances`
Sets Duckling (instance) configuration for a user. Requires 'Admin' role.
::::note
Authentication for this endpoint requires an Admin token. This endpoint configures Duckling sizes and read scaling pool size. Use the token endpoint to create read scaling tokens.
::::
## Request
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/set-reset
# SET/RESET
> SET and RESET statements for configuring DuckDB session options.
This feature in MotherDuck works the same as in DuckDB. See [SET/RESET](https://duckdb.org/docs/stable/sql/statements/set) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/sql-reference
# SQL reference
> SQL reference for MotherDuck & DuckDB
Complete SQL reference documentation for MotherDuck and DuckDB. This reference covers MotherDuck-specific SQL extensions, DuckDB's comprehensive SQL dialect, the Admin API for programmatic management, and the [remote MCP Server](/sql-reference/mcp/) for AI assistant integrations (and the [local MCP server](/sql-reference/mcp/#local-mcp-server) for self-hosted use).
For practical examples and step-by-step instructions, see our [How-to Guides](/key-tasks/how-to-guides) and [Getting Started](/getting-started/) tutorials.
## Included pages
- [MotherDuck REST API](https://motherduck.com/docs/sql-reference/rest-api/motherduck-rest-api): REST API reference for managing MotherDuck resources including databases, users, and access tokens.
- [DuckDB SQL](https://motherduck.com/docs/sql-reference/duckdb-sql-reference): DuckDB SQL Reference
- [MCP Server](https://motherduck.com/docs/sql-reference/mcp): Connect AI assistants to MotherDuck using the remote (fully managed) or local (fully customizable) MCP server
- [MotherDuck SQL](https://motherduck.com/docs/sql-reference/motherduck-sql-reference): MotherDuck-specific SQL extensions and cloud database management
- [Wasm Client](https://motherduck.com/docs/sql-reference/wasm-client): Connect browser applications to MotherDuck using the DuckDB WebAssembly client and Hybrid Query Execution.
- [Postgres Endpoint](https://motherduck.com/docs/sql-reference/postgres-endpoint): Connection parameters, SSL options, session settings, and limitations for the MotherDuck Postgres wire protocol endpoint
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/unpivot
# UNPIVOT
> UNPIVOT statement for transforming columns to rows in DuckDB.
The UNPIVOT statement in MotherDuck works the same as in DuckDB. See [UNPIVOT Statement](https://duckdb.org/docs/stable/sql/statements/unpivot) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/update
# UPDATE
> UPDATE statement for modifying existing rows in DuckDB tables.
The UPDATE statement in MotherDuck works the same as in DuckDB. See [UPDATE Statement](https://duckdb.org/docs/stable/sql/statements/update) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/use
# USE
> USE statement for changing the default database or schema in DuckDB.
The USE statement in MotherDuck works the same as in DuckDB. See [USE](https://duckdb.org/docs/stable/sql/statements/use) in the DuckDB documentation for complete details.
---
Source: https://motherduck.com/docs/sql-reference/duckdb-sql-reference/duckdb-statements/vacuum
# VACUUM
> VACUUM statement for optimizing storage in DuckDB.
The VACUUM statement in MotherDuck works the same as in DuckDB. See [VACUUM](https://duckdb.org/docs/stable/sql/statements/vacuum) in the DuckDB documentation for complete details.