### Setup Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Instructions for installing and loading the spatial extension, and setting a configuration for consistent axis order. ```APIDOC ## Setup ```sql INSTALL spatial; LOAD spatial; SET geometry_always_xy = true; -- ensures lng/lat order for all spatial functions -- For H3 hex binning: INSTALL h3 FROM community; LOAD h3; ``` ``` -------------------------------- ### Install duckdb-skills Plugin Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md Add the repository as a plugin source and install the duckdb-skills plugin. This registers the GitHub repo as a marketplace and installs the plugin. ```bash /plugin marketplace add duckdb/duckdb-skills ``` ```bash /plugin install duckdb-skills@duckdb-skills ``` -------------------------------- ### Install Extensions Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/install-duckdb/SKILL.md Construct and execute SQL statements to install extensions. Handles extensions from core or specified repositories. ```bash "$DUCKDB" :memory: -c "INSTALL ; INSTALL FROM ; ..." ``` -------------------------------- ### Install DuckDB Extensions Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/duckdb-docs/SKILL.md Installs the necessary 'httpfs' and 'fts' extensions for DuckDB. This command should be run in an environment where DuckDB is already installed. ```bash duckdb :memory: -c "INSTALL httpfs; INSTALL fts;" ``` -------------------------------- ### Install and Load H3 Extension for Hex Binning Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/SKILL.md Install the H3 extension from the community repository and load it to perform H3 hex binning for density analysis. ```sql INSTALL h3 FROM community; LOAD h3; ``` -------------------------------- ### Install DuckDB Skills Plugin Source: https://context7.com/duckdb/duckdb-skills/llms.txt Commands to register the GitHub repository as a marketplace source and install the DuckDB Skills plugin into Claude Code. ```bash # Register the GitHub repo as a marketplace source /plugin marketplace add duckdb/duckdb-skills # Install the plugin /plugin install duckdb-skills@duckdb-skills # Update to the latest version later /plugin marketplace update duckdb-skills /plugin update duckdb-skills@duckdb-skills ``` -------------------------------- ### Test Individual Skills Locally Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md Test individual skills directly from the command line after cloning the repository. Ensure DuckDB CLI is installed; otherwise, skills will offer to install it. ```bash /duckdb-skills:read-file some_local_file.parquet ``` ```bash /duckdb-skills:duckdb-docs pivot unpivot ``` ```bash /duckdb-skills:query SELECT 42 ``` -------------------------------- ### Example state.sql Contents Source: https://context7.com/duckdb/duckdb-skills/llms.txt This SQL script demonstrates how to configure a DuckDB session, including attaching databases, loading extensions, creating secrets, and defining macros. ```sql ATTACH IF NOT EXISTS '/home/user/project/analytics.duckdb' AS analytics; USE analytics; LOAD spatial; LOAD httpfs; CREATE SECRET IF NOT EXISTS s3_main (TYPE S3, PROVIDER credential_chain); CREATE OR REPLACE MACRO read_any(file_name) AS TABLE ... ``` -------------------------------- ### Check DuckDB Installation Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md Verifies if the DuckDB command-line interface is installed and accessible in the system's PATH. ```bash command -v duckdb ``` -------------------------------- ### Local Development Setup for DuckDB Skills Source: https://context7.com/duckdb/duckdb-skills/llms.txt Steps to clone the repository, launch Claude Code with local plugins, and test individual skills. ```bash git clone https://github.com/duckdb/duckdb-skills.git cd duckdb-skills # Launch Claude Code loading skills from disk — edits to SKILL.md files take effect immediately claude --plugin-dir . # Test individual skills /duckdb-skills:read-file some_local_file.parquet /duckdb-skills:duckdb-docs pivot unpivot /duckdb-skills:query SELECT 42 ``` -------------------------------- ### Install and Load Spatial Extensions Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Installs and loads the spatial extension for DuckDB. It also sets a configuration option to ensure consistent axis order (longitude, latitude) for spatial functions. The H3 extension is also installed and loaded for hex binning capabilities. ```sql INSTALL spatial; LOAD spatial; SET geometry_always_xy = true; -- ensures lng/lat order for all spatial functions -- For H3 hex binning: INSTALL h3 FROM community; LOAD h3; ``` -------------------------------- ### Install or Update DuckDB Extensions Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md Install or update DuckDB extensions. Supports `name@repo` syntax for community extensions and a `--update` flag that also checks for DuckDB CLI updates. ```bash /duckdb-skills:install-duckdb spatial httpfs ``` ```bash /duckdb-skills:install-duckdb gcs@community ``` ```bash /duckdb-skills:install-duckdb --update ``` -------------------------------- ### DuckDB Extension Loads for Protocols Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/convert-file/SKILL.md Prepend these commands to your DuckDB query when dealing with remote input files. Ensure the necessary extensions are installed and loaded. ```bash LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER credential_chain); ``` ```bash LOAD httpfs; CREATE SECRET (TYPE GCS, PROVIDER credential_chain); ``` ```bash LOAD httpfs; ``` -------------------------------- ### Update All Extensions Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/install-duckdb/SKILL.md Execute the SQL command to update all installed DuckDB extensions. ```bash "$DUCKDB" :memory: -c "UPDATE EXTENSIONS;" ``` -------------------------------- ### Preview remote Parquet file with s3-explore Source: https://context7.com/duckdb/duckdb-skills/llms.txt Use `s3-explore` to preview a specific remote Parquet file and get basic information like row counts. This avoids downloading the entire file. ```bash /duckdb-skills:s3-explore s3://my-bucket/events/2024-01.parquet "how many rows?" ``` -------------------------------- ### Locate DuckDB CLI Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/install-duckdb/SKILL.md Find the path to the DuckDB executable. If not found, instructions are provided to install DuckDB. ```bash DUCKDB=$(command -v duckdb) ``` -------------------------------- ### Writing Spatial Files Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Examples of how to write spatial data from DuckDB to various file formats using the `COPY` command with GDAL drivers. ```APIDOC ## Writing spatial files ```sql COPY (SELECT * FROM ...) TO 'out.geojson' WITH (FORMAT GDAL, DRIVER 'GeoJSON'); COPY (SELECT * FROM ...) TO 'out.gpkg' WITH (FORMAT GDAL, DRIVER 'GPKG'); COPY (SELECT * FROM ...) TO 'out.shp' WITH (FORMAT GDAL, DRIVER 'ESRI Shapefile'); COPY (SELECT * FROM ...) TO 'out.fgb' WITH (FORMAT GDAL, DRIVER 'FlatGeobuf'); ``` Set `geometry_always_xy = true` before writing to avoid axis order issues with KML or WGS84. ``` -------------------------------- ### Query data with predicate pushdown using DuckDB SQL Source: https://context7.com/duckdb/duckdb-skills/llms.txt Efficiently query large remote datasets by pushing predicates down into Parquet files. This example filters sales data by date. Requires `httpfs` and `credential_chain`. ```sql LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER credential_chain); SELECT product_id, sum(quantity) AS total_sold FROM 's3://my-bucket/sales/*.parquet' WHERE sale_date >= '2024-01-01' GROUP BY ALL ORDER BY total_sold DESC LIMIT 10; ``` -------------------------------- ### Convert Shapefile to GeoJSON using spatial skill Source: https://context7.com/duckdb/duckdb-skills/llms.txt Convert geospatial file formats using the `spatial` skill. This example converts a Shapefile to GeoJSON. ```bash /duckdb-skills:spatial roads.shp roads.geojson ``` -------------------------------- ### Connect to Cloudflare R2 using DuckDB SQL Source: https://context7.com/duckdb/duckdb-skills/llms.txt Connect to Cloudflare R2 object storage by creating an R2 secret. This example demonstrates describing data from an R2 bucket. Requires `httpfs` and `credential_chain`. ```sql LOAD httpfs; CREATE SECRET (TYPE R2, PROVIDER credential_chain); DESCRIBE FROM 's3://my-r2-bucket/data.parquet'; ``` -------------------------------- ### Analyze local GeoJSON file using spatial skill Source: https://context7.com/duckdb/duckdb-skills/llms.txt Analyze local geospatial files like GeoJSON using the `spatial` skill. This example queries which neighborhood has the most area. ```bash /duckdb-skills:spatial neighborhoods.geojson "which neighborhood has the most area?" ``` -------------------------------- ### Execute DuckDB Query via Bash Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/SKILL.md Run a DuckDB query from the command line using a single bash call. Include necessary setup and your SQL query. ```bash duckdb -c " LOAD spatial; " ``` -------------------------------- ### Get Bounding Box Coordinates Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Retrieves the minimum and maximum X and Y coordinates of a geometry's bounding box. ```sql ST_XMin(geom) ``` ```sql ST_XMax(geom) ``` ```sql ST_YMin(geom) ``` ```sql ST_YMax(geom) ``` -------------------------------- ### Get WKT Representation Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Converts a geometry object to its Well-Known Text (WKT) representation. ```sql ST_AsText(geom) ``` -------------------------------- ### Load Spatial Extension and Set Geometry Format Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/SKILL.md Always start DuckDB spatial queries with these commands. `SET geometry_always_xy = true` ensures correct interpretation of longitude/latitude coordinates. ```sql LOAD spatial; SET geometry_always_xy = true; ``` -------------------------------- ### Get Geometry Type Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Returns the type name of a geometry (e.g., POINT, POLYGON). ```sql ST_GeometryType(geom) ``` -------------------------------- ### Add HTTPFS Extension for Remote Data Access Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/SKILL.md Use this setup to access remote data sources like Overture Maps on S3. Ensure your AWS credentials are configured. ```sql LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER config, REGION 'us-west-2'); ``` -------------------------------- ### H3 hex density binning using DuckDB spatial extension Source: https://context7.com/duckdb/duckdb-skills/llms.txt Perform H3 hex density binning to aggregate events into hexagonal cells. Requires the `h3` community extension. This example counts events per H3 cell. ```sql INSTALL h3 FROM community; LOAD h3; LOAD spatial; SET geometry_always_xy = true; SELECT h3_latlng_to_cell(latitude, longitude, 9) AS h3_cell, count() AS events FROM read_csv('events.csv') GROUP BY ALL ORDER BY events DESC LIMIT 20; ``` -------------------------------- ### Spatial join using DuckDB spatial extension Source: https://context7.com/duckdb/duckdb-skills/llms.txt Perform a spatial join to determine which points fall inside which polygons. This example joins points with regions based on spatial containment. ```sql LOAD spatial; SET geometry_always_xy = true; SELECT p.name, r.region_name FROM read_parquet('points.parquet') p JOIN read_parquet('regions.parquet') r ON ST_Contains(r.geometry, ST_Point(p.longitude, p.latitude)) ``` -------------------------------- ### Get Parquet file stats from metadata using DuckDB SQL Source: https://context7.com/duckdb/duckdb-skills/llms.txt Retrieve statistics for Parquet files, such as total rows and compressed size in MB, directly from metadata without downloading data. Requires `httpfs` and `credential_chain`. ```sql LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER credential_chain); SELECT file_name, sum(row_group_num_rows) AS total_rows, (sum(row_group_compressed_bytes) / 1024 / 1024)::DECIMAL(10,1) AS compressed_mb FROM parquet_metadata('s3://my-bucket/events/2024-01.parquet') GROUP BY file_name; ``` -------------------------------- ### Verify State File Initialization Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md Tests the `state.sql` file by initializing a DuckDB session with it and listing all tables. This confirms the state file is correctly configured. ```bash duckdb -init "$STATE_DIR/state.sql" -c "SHOW TABLES;" ``` -------------------------------- ### Clone and Launch Local Development Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md Clone the repository and launch Claude Code with the local plugin directory to test skills locally. Edits to `skills/*/SKILL.md` take effect immediately. ```bash git clone https://github.com/duckdb/duckdb-skills.git cd duckdb-skills claude --plugin-dir . ``` -------------------------------- ### Create User Home State Directory Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md Sets the state directory to a user-specific path within the home directory, scoped by the project's root path, and creates the directory if it doesn't exist. ```bash PROJECT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || echo \"$PWD\")" PROJECT_ID="$(echo \"$PROJECT_ROOT\" | tr '/' '-')" STATE_DIR="$HOME/.duckdb-skills/$PROJECT_ID" mkdir -p "$STATE_DIR" ``` -------------------------------- ### Get GeoJSON Representation Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Converts a geometry object to its GeoJSON representation. ```sql ST_AsGeoJSON(geom) ``` -------------------------------- ### Get Latitude from Point Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Extracts the latitude (Y coordinate) from a point geometry. ```sql ST_Y(point) ``` -------------------------------- ### Create Project Directory State Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md Sets the state directory to the project's local `.duckdb-skills` folder and creates the directory if it doesn't exist. Optionally adds it to `.gitignore`. ```bash STATE_DIR=".duckdb-skills" mkdir -p "$STATE_DIR" ``` ```bash echo '.duckdb-skills/' >> .gitignore ``` -------------------------------- ### Get Longitude from Point Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Extracts the longitude (X coordinate) from a point geometry. ```sql ST_X(point) ``` -------------------------------- ### Initialize DuckDB Session with State Source: https://context7.com/duckdb/duckdb-skills/llms.txt Use this command to initialize a DuckDB session with a specific state file and execute a query. The state file can contain ATTACH, USE, LOAD, and CREATE statements. ```bash duckdb -init .duckdb-skills/state.sql -c "FROM sales LIMIT 10;" ``` ```bash duckdb -init .duckdb-skills/state.sql -csv -c "SUMMARIZE customers;" ``` -------------------------------- ### List S3 bucket contents with s3-explore Source: https://context7.com/duckdb/duckdb-skills/llms.txt Use the `s3-explore` command to list the contents of an S3 bucket. This command does not download data. ```bash /duckdb-skills:s3-explore s3://my-bucket/data/ ``` -------------------------------- ### Convert Data Files with `convert-file` Source: https://context7.com/duckdb/duckdb-skills/llms.txt Use the `convert-file` skill to convert data between various formats like Parquet, CSV, JSON, and Excel. Supports remote inputs and advanced options like partitioning and compression. ```bash /duckdb-skills:convert-file data.csv ``` ```bash /duckdb-skills:convert-file data.csv output.xlsx ``` ```bash /duckdb-skills:convert-file s3://bucket/data.parquet local_output.csv ``` ```sql COPY (FROM 'data.csv') TO 'data.parquet'; ``` ```sql COPY (FROM 'data.parquet') TO 'data.csv' (FORMAT csv, HEADER); ``` ```sql INSTALL excel; LOAD excel; COPY (FROM 'data.csv') TO 'output.xlsx' (FORMAT xlsx); ``` ```sql LOAD spatial; COPY (FROM 'data.gpkg') TO 'output.geojson' (FORMAT GDAL, DRIVER 'GeoJSON'); ``` ```sql COPY (FROM 'data.csv') TO 'output/' (FORMAT parquet, CODEC 'zstd', PARTITION_BY (year, region)); ``` ```sql LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER credential_chain); COPY (FROM 's3://bucket/data.parquet') TO 'output.json' (FORMAT json, ARRAY true); ``` -------------------------------- ### Load necessary extensions and set up S3 access Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/overture.md Before querying Overture Maps data, load the httpfs and spatial extensions. Then, create a secret for S3 access, specifying the provider and region. ```sql LOAD httpfs; LOAD spatial; CREATE SECRET (TYPE S3, PROVIDER config, REGION 'us-west-2'); ``` -------------------------------- ### DuckDB state file location options Source: https://context7.com/duckdb/duckdb-skills/llms.txt Illustrates the two common locations for the `state.sql` file, which stores session state like ATTACH statements and secrets for DuckDB skills. ```bash # State file location options: # Option 1 (project-local): .duckdb-skills/state.sql # Option 2 (home directory, scoped by project root): ~/.duckdb-skills//state.sql ``` -------------------------------- ### Fetch DuckDB Documentation Index Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/duckdb-docs/SKILL.md Downloads the latest DuckDB documentation index from a remote URL and saves it to the local cache. This command requires the httpfs and fts extensions to be loaded. ```bash duckdb -c " LOAD httpfs; LOAD fts; ATTACH 'REMOTE_URL' AS remote (READ_ONLY); ATTACH '$HOME/.duckdb/docs/CACHE_FILENAME.tmp' AS tmp; COPY FROM DATABASE remote TO tmp; " && mv "$HOME/.duckdb/docs/CACHE_FILENAME.tmp" "$HOME/.duckdb/docs/CACHE_FILENAME" ``` -------------------------------- ### Read and Explore Data Files Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md Read and explore various data file formats locally or from remote storage. Auto-detects format by file extension using `read_any` table macro and suggests `query` for further exploration. ```bash /duckdb-skills:read-file variants.parquet what columns does it have? ``` ```bash /duckdb-skills:read-file s3://my-bucket/data.parquet describe the schema ``` ```bash /duckdb-skills:read-file https://example.com/data.csv how many rows? ``` -------------------------------- ### Read Any Data File with `read-file` Source: https://context7.com/duckdb/duckdb-skills/llms.txt Use the `read-file` skill to read and profile local or remote data files. The `read_any` macro auto-detects file formats and supports various protocols like S3, GCS, and HTTPS. ```bash /duckdb-skills:read-file variants.parquet "what columns does it have?" ``` ```bash /duckdb-skills:read-file s3://my-bucket/data.parquet "describe the schema" ``` ```bash /duckdb-skills:read-file https://example.com/sales.csv "how many rows?" ``` ```bash /duckdb-skills:read-file analysis.ipynb "what does this notebook do?" ``` ```sql CREATE OR REPLACE MACRO read_any(file_name) AS TABLE WITH json_case AS (FROM read_json_auto(file_name)) , csv_case AS (FROM read_csv(file_name)) , parquet_case AS (FROM read_parquet(file_name)) , avro_case AS (FROM read_avro(file_name)) , excel_case AS (FROM read_xlsx(file_name)) , spatial_case AS (FROM st_read(file_name)) , sqlite_case AS (FROM sqlite_scan(file_name, (SELECT name FROM sqlite_master(file_name) LIMIT 1))) , ipynb_case AS ( WITH nb AS (FROM read_json_auto(file_name)) SELECT cell_idx, cell.cell_type, array_to_string(cell.source, '') AS source, cell.execution_count FROM nb, UNNEST(cells) WITH ORDINALITY AS t(cell, cell_idx) ORDER BY cell_idx ) FROM query_table( CASE WHEN file_name ILIKE '%.json' OR file_name ILIKE '%.jsonl' THEN 'json_case' WHEN file_name ILIKE '%.csv' OR file_name ILIKE '%.tsv' THEN 'csv_case' WHEN file_name ILIKE '%.parquet' OR file_name ILIKE '%.pq' THEN 'parquet_case' WHEN file_name ILIKE '%.avro' THEN 'avro_case' WHEN file_name ILIKE '%.xlsx' OR file_name ILIKE '%.xls' THEN 'excel_case' WHEN file_name ILIKE '%.shp' OR file_name ILIKE '%.gpkg' THEN 'spatial_case' WHEN file_name ILIKE '%.ipynb' THEN 'ipynb_case' WHEN file_name ILIKE '%.db' OR file_name ILIKE '%.sqlite' THEN 'sqlite_case' ELSE 'blob_case' END ); DESCRIBE FROM read_any('/path/to/variants.parquet'); SELECT count(*) AS row_count FROM read_any('/path/to/variants.parquet'); FROM read_any('/path/to/variants.parquet') LIMIT 20; ``` ```sql LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER credential_chain); DESCRIBE FROM read_any('s3://my-bucket/data.parquet'); FROM read_any('s3://my-bucket/data.parquet') LIMIT 20; ``` -------------------------------- ### Get Parquet Metadata from S3 Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/s3-explore/SKILL.md Extract row counts and compressed sizes from Parquet file metadata stored on S3. This operation is efficient as it does not require downloading the file data. ```bash duckdb -c " LOAD httpfs; SELECT file_name, sum(row_group_num_rows) AS total_rows, (sum(row_group_compressed_bytes) / 1024 / 1024)::DECIMAL(10,1) AS compressed_mb FROM parquet_metadata('') GROUP BY file_name; " ``` -------------------------------- ### Create Line from Points Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Constructs a line geometry by collecting an array of points. ```sql ST_MakeLine(geom_array) ``` -------------------------------- ### Create DuckDB Docs Cache Directory Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/duckdb-docs/SKILL.md Ensures the directory structure for storing DuckDB documentation cache files exists. Creates parent directories if they do not exist. ```bash mkdir -p "$HOME/.duckdb/docs" ``` -------------------------------- ### Preview File Contents and Schema on S3 Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/s3-explore/SKILL.md Preview the schema, count rows, and view the first 20 rows of a specific file or glob pattern on S3. This is useful for understanding the structure and content of remote datasets. ```bash duckdb -c " LOAD httpfs; DESCRIBE FROM ''; SELECT count(*) AS row_count FROM ''; FROM '' LIMIT 20; " ``` -------------------------------- ### DuckDB Conversion Command Structure Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/convert-file/SKILL.md This is the general structure for a DuckDB conversion command. Replace placeholders like , , , and with specific values based on your conversion needs. ```bash duckdb -c " COPY (FROM '') TO '' ; " ``` -------------------------------- ### Create Point Geometry Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Constructs a point geometry from longitude and latitude coordinates. ```sql ST_Point(x, y) ``` -------------------------------- ### Create Buffer Geometry Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Expands a geometry by a specified distance, creating a buffer zone. ```sql ST_Buffer(geom, dist) ``` -------------------------------- ### Define and Use read_any Macro in DuckDB Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/read-file/SKILL.md This snippet defines a versatile `read_any` macro in DuckDB that automatically detects and reads various file formats. It includes commands to describe the schema, count rows, and preview the first 20 rows of the data. For remote files, ensure necessary `LOAD` and `CREATE SECRET` commands are prepended based on the protocol. ```bash duckdb -csv -c " CREATE OR REPLACE MACRO read_any(file_name) AS TABLE WITH json_case AS (FROM read_json_auto(file_name)) , csv_case AS (FROM read_csv(file_name)) , parquet_case AS (FROM read_parquet(file_name)) , avro_case AS (FROM read_avro(file_name)) , blob_case AS (FROM read_blob(file_name)) , spatial_case AS (FROM st_read(file_name)) , excel_case AS (FROM read_xlsx(file_name)) , sqlite_case AS (FROM sqlite_scan(file_name, (SELECT name FROM sqlite_master(file_name) LIMIT 1))) , ipynb_case AS ( WITH nb AS (FROM read_json_auto(file_name)) SELECT cell_idx, cell.cell_type, array_to_string(cell.source, '') AS source, cell.execution_count FROM nb, UNNEST(cells) WITH ORDINALITY AS t(cell, cell_idx) ORDER BY cell_idx ) FROM query_table( CASE WHEN file_name ILIKE '%.json' OR file_name ILIKE '%.jsonl' OR file_name ILIKE '%.ndjson' OR file_name ILIKE '%.geojson' OR file_name ILIKE '%.geojsonl' OR file_name ILIKE '%.har' THEN 'json_case' WHEN file_name ILIKE '%.csv' OR file_name ILIKE '%.tsv' OR file_name ILIKE '%.tab' OR file_name ILIKE '%.txt' THEN 'csv_case' WHEN file_name ILIKE '%.parquet' OR file_name ILIKE '%.pq' THEN 'parquet_case' WHEN file_name ILIKE '%.avro' THEN 'avro_case' WHEN file_name ILIKE '%.xlsx' OR file_name ILIKE '%.xls' THEN 'excel_case' WHEN file_name ILIKE '%.shp' OR file_name ILIKE '%.gpkg' OR file_name ILIKE '%.fgb' OR file_name ILIKE '%.kml' THEN 'spatial_case' WHEN file_name ILIKE '%.ipynb' THEN 'ipynb_case' WHEN file_name ILIKE '%.db' OR file_name ILIKE '%.sqlite' OR file_name ILIKE '%.sqlite3' THEN 'sqlite_case' ELSE 'blob_case' END ); DESCRIBE FROM read_any('RESOLVED_PATH'); SELECT count(*) AS row_count FROM read_any('RESOLVED_PATH'); FROM read_any('RESOLVED_PATH') LIMIT 20; " ``` -------------------------------- ### Describe Table Schema and Row Count Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md For a given table, retrieves its column definitions (schema) and the total number of rows. This is done for each table discovered. ```bash duckdb "$RESOLVED_PATH" -csv -c " DESCRIBE ; SELECT count() AS row_count FROM ; " ``` -------------------------------- ### Search DuckDB Documentation Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md Search DuckDB and DuckLake documentation and blog posts using full-text search against hosted search indexes. Queries run over HTTPS by default, with an option to cache the index locally. ```bash /duckdb-skills:duckdb-docs window functions ``` ```bash /duckdb-skills:duckdb-docs "how do I read a CSV with custom delimiters?" ``` -------------------------------- ### Read Spatial Files with ST_Read Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Demonstrates reading spatial data from various file formats using the ST_Read function. Note that GeoParquet is read natively using the FROM clause, and OSM PBF files can be read with ST_ReadOSM. ```sql SELECT *, ST_Point(lng, lat) AS geom FROM 'file.csv' ``` ```sql FROM 'file.geoparquet' ``` ```sql ST_ReadOSM('region.osm.pbf') (multithreaded, tags as MAP column) ``` -------------------------------- ### Query Past Session Logs with DuckDB Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/read-memories/SKILL.md Use this bash command to query past session logs. Replace `` with the appropriate path and `` with your search term. The `--here` flag scopes the search to the current project. ```bash duckdb :memory: -c " SELECT regexp_extract(filename, 'projects/([^/]+)/', 1) AS project, strftime(timestamp::TIMESTAMPTZ, '%Y-%m-%d %H:%M') AS ts, message.role AS role, left(message.content::VARCHAR, 500) AS content FROM read_ndjson('', auto_detect=true, ignore_errors=true, filename=true) WHERE message::VARCHAR ILIKE '%%' AND message.role IS NOT NULL ORDER BY timestamp LIMIT 40; " ``` -------------------------------- ### Create Bounding Box Geometry Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Creates a rectangular bounding box geometry given the minimum and maximum coordinates. ```sql ST_MakeEnvelope(xmin, ymin, xmax, ymax) ``` -------------------------------- ### Query Data with SQL or Natural Language Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md Run SQL queries against attached databases or ad-hoc against files using DuckDB's Friendly SQL dialect. Automatically picks up session state from `attach-db`. ```bash /duckdb-skills:query FROM sales LIMIT 10 ``` ```bash /duckdb-skills:query "what are the top 5 customers by revenue?" ``` ```bash /duckdb-skills:query FROM 'exports.csv' WHERE amount > 100 ``` -------------------------------- ### Resolve State Directory Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md Determines the appropriate directory to store the DuckDB session state file (`state.sql`). It checks project-specific and user-specific locations. ```bash # Option 1: in the project directory test -f .duckdb-skills/state.sql && STATE_DIR=".duckdb-skills" ``` ```bash # Option 2: in the home directory, scoped by project root path PROJECT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || echo \"$PWD\")" PROJECT_ID="$(echo \"$PROJECT_ROOT\" | tr '/' '-')" test -f "$HOME/.duckdb-skills/$PROJECT_ID/state.sql" && STATE_DIR="$HOME/.duckdb-skills/$PROJECT_ID" ``` -------------------------------- ### Query Attached Databases or Files Source: https://context7.com/duckdb/duckdb-skills/llms.txt Executes SQL queries against attached databases using session mode or directly against files in ad-hoc mode. Supports natural language to SQL translation and estimates result sizes. ```bash # Session mode — query an attached database by table name /duckdb-skills:query FROM sales WHERE amount > 100 ORDER BY amount DESC LIMIT 10 # Natural language → SQL (uses schema context from attached DB) /duckdb-skills:query "what are the top 5 customers by total revenue?" # Ad-hoc mode — query a file directly (sandboxed) /duckdb-skills:query FROM 'exports.csv' WHERE status = 'completed' # DuckDB Friendly SQL idioms used internally: # FROM-first (implicit SELECT *): FROM table WHERE x > 10 # GROUP BY ALL: SELECT region, sum(sales) FROM t GROUP BY ALL # SELECT * EXCLUDE: SELECT * EXCLUDE (internal_id, audit_col) # count() shorthand: SELECT count() FROM t (no * needed) # Lateral column aliases: SELECT amount * 0.1 AS tax, tax * 2 AS doubled_tax # SUMMARIZE for profiling: SUMMARIZE sales # PIVOT reshape: PIVOT sales ON quarter USING sum(revenue) # Session mode execution (internal): duckdb -init .duckdb-skills/state.sql -csv -c " SELECT customer_id, sum(amount) AS total_revenue FROM sales GROUP BY ALL ORDER BY total_revenue DESC LIMIT 5; " ``` -------------------------------- ### List Directory Contents on S3 Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/s3-explore/SKILL.md Use this command to list files in a directory or bucket on S3-compatible storage. It shows filename, size in MB, and last modified date. Avoid selecting 'content' to prevent downloading files. ```bash duckdb -c " LOAD httpfs; SELECT filename, (size / 1024 / 1024)::DECIMAL(10,1) AS size_mb, last_modified FROM read_blob('/*') ORDER BY filename LIMIT 50; " ``` -------------------------------- ### Write Spatial Files with COPY Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Shows how to write spatial data to different file formats using the COPY statement with the GDAL driver. Ensure geometry_always_xy is set to true before writing to avoid axis order issues. ```sql COPY (SELECT * FROM ...) TO 'out.geojson' WITH (FORMAT GDAL, DRIVER 'GeoJSON') ``` ```sql COPY (SELECT * FROM ...) TO 'out.gpkg' WITH (FORMAT GDAL, DRIVER 'GPKG') ``` ```sql COPY (SELECT * FROM ...) TO 'out.shp' WITH (FORMAT GDAL, DRIVER 'ESRI Shapefile') ``` ```sql COPY (SELECT * FROM ...) TO 'out.fgb' WITH (FORMAT GDAL, DRIVER 'FlatGeobuf') ``` -------------------------------- ### Update duckdb-skills Plugin Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md To pull the latest version, update the marketplace first and then the plugin. This ensures you have the most recent features and bug fixes. ```bash /plugin marketplace update duckdb-skills ``` ```bash /plugin update duckdb-skills@duckdb-skills ``` -------------------------------- ### Query data on GCS with s3-explore Source: https://context7.com/duckdb/duckdb-skills/llms.txt Query data stored on Google Cloud Storage (GCS) using the `s3-explore` command. It supports natural language queries. ```bash /duckdb-skills:s3-explore gs://my-gcs-bucket/sales/ "what are the top 10 products?" ``` -------------------------------- ### Format Search Results Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/duckdb-docs/SKILL.md This format is used to present each retrieved documentation chunk, including its section, page title, URL, and relevant text. It helps in organizing and displaying search findings. ```markdown ### {section} — {page_title} {url} {text} --- ``` -------------------------------- ### List bucket contents using DuckDB SQL Source: https://context7.com/duckdb/duckdb-skills/llms.txt This SQL query lists bucket contents, including file size in MB and last modified date, by reading blob metadata. It requires the `httpfs` extension and `credential_chain` for authentication. ```sql LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER credential_chain); SELECT filename, (size / 1024 / 1024)::DECIMAL(10,1) AS size_mb, last_modified FROM read_blob('s3://my-bucket/data/*') ORDER BY filename LIMIT 50; ``` -------------------------------- ### Execute Ad-hoc Query with File Access Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/query/SKILL.md Executes a SQL query in ad-hoc mode, sandboxed to only access the specified file paths. Uses a heredoc for safe handling of multi-line queries. ```bash duckdb :memory: -csv <<'SQL' SET allowed_paths=['FILE_PATH']; SET enable_external_access=false; SET allow_persistent_secrets=false; SET lock_configuration=true; ; SQL ``` -------------------------------- ### Describe Table Schema in Session Mode Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/query/SKILL.md Retrieves the schema (column names and types) for a specific table in session mode. This is used to provide context for natural language to SQL conversion. ```bash duckdb -init "$STATE_DIR/state.sql" -csv -c "DESCRIBE ;" ``` -------------------------------- ### Reading Spatial Files Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Demonstrates how to read various spatial file formats into DuckDB using the `ST_Read` function or native support. ```APIDOC ## Reading spatial files | Format | Read method | |---|---| | GeoJSON | `ST_Read('file.geojson')` | | Shapefile | `ST_Read('file.shp')` | | GeoPackage | `ST_Read('file.gpkg')` | | FlatGeobuf | `ST_Read('file.fgb')` | | KML | `ST_Read('file.kml')` | | GPX | `ST_Read('file.gpx')` | | GeoParquet | `FROM 'file.geoparquet'` (native, no ST_Read needed) | | OSM PBF | `ST_ReadOSM('region.osm.pbf')` (multithreaded, tags as MAP column) | | CSV with lat/lng | `SELECT *, ST_Point(lng, lat) AS geom FROM 'file.csv'` | `ST_Read` uses GDAL internally and supports 50+ formats. ``` -------------------------------- ### List Tables in DuckDB Database Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md Retrieves a list of all tables within a DuckDB database along with their estimated sizes. Useful for initial schema exploration. ```bash duckdb "$RESOLVED_PATH" -csv -c " SELECT table_name, estimated_size FROM duckdb_tables() ORDER BY table_name; " ``` -------------------------------- ### Check DuckDB CLI Version Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/install-duckdb/SKILL.md Retrieve the current and latest stable versions of the DuckDB CLI to determine if an upgrade is needed. ```bash CURRENT=$(duckdb --version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+') LATEST=$(curl -fsSL https://duckdb.org/data/latest_stable_version.txt) ``` -------------------------------- ### Append ATTACH Statement to State File Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md Appends a new ATTACH statement for the database to the `state.sql` file if it doesn't already exist. It also sets the default schema to use. ```bash cat >> "$STATE_DIR/state.sql" <<'STATESQL' ATTACH IF NOT EXISTS 'RESOLVED_PATH' AS my_data; USE my_data; STATESQL ``` -------------------------------- ### Find coffee shops near a location using spatial skill Source: https://context7.com/duckdb/duckdb-skills/llms.txt Use the `spatial` skill to find points of interest, such as coffee shops, within a specified radius of a given location. It leverages Overture Maps data. ```bash /duckdb-skills:spatial "find coffee shops within 500m of Times Square, NYC" ``` -------------------------------- ### Verify DuckDB State File Accessibility Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/query/SKILL.md Checks if the databases referenced in the DuckDB state file are accessible by running a 'SHOW DATABASES;' command. ```bash duckdb -init "$STATE_DIR/state.sql" -c "SHOW DATABASES;" ``` -------------------------------- ### Search DuckDB Documentation Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/duckdb-docs/SKILL.md Performs a full-text search against the local DuckDB documentation index using the BM25 algorithm. Results are returned in JSON format. ```bash duckdb "$HOME/.duckdb/docs/CACHE_FILENAME" -readonly -json -c " LOAD fts; SELECT chunk_id, page_title, section, breadcrumb, url, version, text, fts_main_docs_chunks.match_bm25(chunk_id, 'SEARCH_QUERY') AS score FROM docs_chunks WHERE score IS NOT NULL AND version = 'VERSION' ORDER BY score DESC LIMIT 8; " ``` -------------------------------- ### DuckDB Format Clauses for Geo Package and Shapefile Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/convert-file/SKILL.md Use these format clauses for Geo Package and ESRI Shapefile output. Both require the 'spatial' extension to be loaded. ```sql (FORMAT GDAL, DRIVER 'GPKG') ``` ```sql (FORMAT GDAL, DRIVER 'ESRI Shapefile') ``` -------------------------------- ### Count buildings in a bounding box using spatial skill Source: https://context7.com/duckdb/duckdb-skills/llms.txt Use the `spatial` skill to count features, such as buildings, within a specified geographic bounding box. ```bash /duckdb-skills:spatial "how many buildings are in downtown Chicago?" ``` -------------------------------- ### Add DuckDB Skills Directory to Gitignore Source: https://context7.com/duckdb/duckdb-skills/llms.txt Add the DuckDB Skills directory to your .gitignore file to prevent it from being tracked by Git. ```bash echo '.duckdb-skills/' >> .gitignore ``` -------------------------------- ### Search Past Session Logs with read-memories Source: https://context7.com/duckdb/duckdb-skills/llms.txt Searches Claude Code's JSONL session logs using DuckDB to recover context from prior conversations. Results are internalized to enrich the current response. The `--here` flag scopes the search to the current project. ```bash # Search all projects for past sessions mentioning "duckdb" /duckdb-skills:read-memories duckdb # Scope to the current project only /duckdb-skills:read-memories authentication --here ``` ```sql # All projects: duckdb :memory: -c " SELECT regexp_extract(filename, 'projects/([^/]+)/', 1) AS project, strftime(timestamp::TIMESTAMPTZ, '%Y-%m-%d %H:%M') AS ts, message.role AS role, left(message.content::VARCHAR, 500) AS content FROM read_ndjson('\$HOME/.claude/projects/*/*.jsonl', auto_detect=true, ignore_errors=true, filename=true) WHERE message::VARCHAR ILIKE '%duckdb%' AND message.role IS NOT NULL ORDER BY timestamp LIMIT 40; " ``` ```sql # Current project only (--here): duckdb :memory: -c " SELECT regexp_extract(filename, 'projects/([^/]+)/', 1) AS project, strftime(timestamp::TIMESTAMPTZ, '%Y-%m-%d %H:%M') AS ts, message.role AS role, left(message.content::VARCHAR, 500) AS content FROM read_ndjson('\$HOME/.claude/projects/$(echo $PWD | sed 's|[/_]|-|g')/*.jsonl', auto_detect=true, ignore_errors=true, filename=true) WHERE message::VARCHAR ILIKE '%authentication%' AND message.role IS NOT NULL ORDER BY timestamp LIMIT 40; " ``` -------------------------------- ### Attach DuckDB Database Source: https://github.com/duckdb/duckdb-skills/blob/main/README.md Attach a DuckDB database file for interactive querying. This skill explores the schema and writes a SQL state file for session restoration. ```bash /duckdb-skills:attach-db my_analytics.duckdb ``` -------------------------------- ### DuckDB Partitioning Clause Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/convert-file/SKILL.md Add this clause to the format options when converting to Parquet or CSV if the user requests partitioning. Replace 'col' with the actual column name(s) to partition by. ```sql PARTITION_BY (col) ``` -------------------------------- ### Query places with bounding box filtering Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/overture.md Efficiently query Overture Maps 'places' data by filtering on bounding box coordinates first. This avoids downloading unnecessary data. ```sql FROM read_parquet('s3://overturemaps-us-west-2/release/2026-03-18.0/theme=places/type=place/*') WHERE bbox.xmin > -74.00 AND bbox.xmax < -73.97 AND bbox.ymin > 40.74 AND bbox.ymax < 40.76 ``` -------------------------------- ### Resolve Database Path Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/attach-db/SKILL.md Resolves a relative or absolute path to a database file to an absolute path. Ensures the file exists before proceeding. ```bash RESOLVED_PATH="$(cd "$(dirname \"$0\")" 2>/dev/null && pwd)/$(basename \"$0\")" ``` ```bash test -f "$RESOLVED_PATH" ``` -------------------------------- ### Search DuckDB Documentation with BM25 Source: https://context7.com/duckdb/duckdb-skills/llms.txt Performs full-text BM25 search against cached DuckDB documentation. Automatically manages a local cache. Supports natural language questions and keyword lookups. Defaults to LTS version. ```bash # Search for a function or feature /duckdb-skills:duckdb-docs window functions # Ask a natural language question /duckdb-skills:duckdb-docs "how do I read a CSV with custom delimiters?" # Search DuckLake docs specifically /duckdb-skills:duckdb-docs "how do DuckLake catalogs work?" ``` ```sql # Step 1: Ensure cache is fresh (≤2 days old); fetch if stale duckdb -c " LOAD httpfs; LOAD fts; ATTACH 'https://duckdb.org/data/docs-search.duckdb' AS remote (READ_ONLY); ATTACH '$HOME/.duckdb/docs/duckdb-docs.duckdb.tmp' AS tmp; COPY FROM DATABASE remote TO tmp; " && mv ~/.duckdb/docs/duckdb-docs.duckdb.tmp ~/.duckdb/docs/duckdb-docs.duckdb ``` ```sql # Step 2: BM25 search (natural language "how do I read CSV with custom delimiters" # → extracted terms: "read CSV custom delimiters") duckdb ~/.duckdb/docs/duckdb-docs.duckdb -readonly -json -c " LOAD fts; SELECT chunk_id, page_title, section, breadcrumb, url, version, text, fts_main_docs_chunks.match_bm25(chunk_id, 'read CSV custom delimiters') AS score FROM docs_chunks WHERE score IS NOT NULL AND version = 'lts' ORDER BY score DESC LIMIT 8; " ``` -------------------------------- ### Attach DuckDB Database to State Source: https://context7.com/duckdb/duckdb-skills/llms.txt Attaches a local DuckDB database file, validates it, explores its schema, and appends an ATTACH statement to the shared `state.sql` file for subsequent queries. ```bash # Attach a local DuckDB file /duckdb-skills:attach-db my_analytics.duckdb # What happens internally: # 1. Resolves to absolute path, e.g. /home/user/project/my_analytics.duckdb # 2. Validates: duckdb my_analytics.duckdb -c "PRAGMA version;" # 3. Lists all tables and describes each one: # duckdb my_analytics.duckdb -csv -c " # SELECT table_name, estimated_size FROM duckdb_tables() ORDER BY table_name; # " # duckdb my_analytics.duckdb -csv -c "DESCRIBE sales; SELECT count() AS row_count FROM sales;" # 4. Asks where to store state (project dir or home dir), then appends: # ATTACH IF NOT EXISTS '/home/user/project/my_analytics.duckdb' AS my_analytics; # USE my_analytics; # → written to .duckdb-skills/state.sql # 5. Verifies: duckdb -init .duckdb-skills/state.sql -c "SHOW TABLES;" # # Output summary: # Database path: /home/user/project/my_analytics.duckdb # Alias: my_analytics # State file: .duckdb-skills/state.sql # Tables: sales (12 columns, 1.2M rows), customers (8 columns, 45K rows) ``` -------------------------------- ### Create Point from Longitude and Latitude Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/SKILL.md When working with CSV data containing latitude and longitude, use `ST_Point` with longitude first to create spatial points. ```sql ST_Point(longitude, latitude) ``` -------------------------------- ### Update Specific Extensions Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/install-duckdb/SKILL.md Execute the SQL command to update a specified list of DuckDB extensions. ```bash "$DUCKDB" :memory: -c "UPDATE EXTENSIONS (, , ...);" ``` -------------------------------- ### Find places by category near a point Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/overture.md This query finds coffee shops within a specified bounding box and calculates their distance from a given point, ordering results by proximity. Ensure the 'places' data is loaded and S3 access is configured. ```sql SELECT names.primary, categories.primary, confidence, ST_Distance_Spheroid( ST_Point(ST_X(geometry), ST_Y(geometry))::POINT_2D, ST_Point(-73.985, 40.748)::POINT_2D ) AS dist_m FROM read_parquet('s3://overturemaps-us-west-2/release/2026-03-18.0/theme=places/type=place/*') WHERE bbox.xmin BETWEEN -74.01 AND -73.96 AND bbox.ymin BETWEEN 40.72 AND 40.77 AND categories.primary = 'coffee_shop' ORDER BY dist_m LIMIT 10; ``` -------------------------------- ### Execute Multi-line Query in Session Mode Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/query/SKILL.md Executes a multi-line SQL query in session mode using a heredoc to prevent shell quoting issues. This ensures complex queries are passed correctly to DuckDB. ```bash duckdb -init "$STATE_DIR/state.sql" -csv <<'SQL' ; SQL ``` -------------------------------- ### Retrieve Table Names for Session Mode Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/query/SKILL.md In session mode, retrieves a list of table names from the DuckDB database to inform SQL query generation. Assumes a state file is present and accessible. ```bash duckdb -init "$STATE_DIR/state.sql" -csv -c " SELECT table_name FROM duckdb_tables() ORDER BY table_name; " ``` -------------------------------- ### Ad-hoc Mode Execution Source: https://context7.com/duckdb/duckdb-skills/llms.txt Execute SQL queries directly in ad-hoc mode. Ensure to set allowed paths and disable external access/persistent secrets for sandboxed execution. ```bash duckdb :memory: -csv <<'SQL' SET allowed_paths=['exports.csv']; SET enable_external_access=false; SET allow_persistent_secrets=false; SET lock_configuration=true; FROM 'exports.csv' WHERE status = 'completed'; SQL ``` -------------------------------- ### Export Spatial Data to GeoJSON Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/SKILL.md Use the `COPY TO` command with the GDAL driver to export query results to a GeoJSON file for visualization. ```sql COPY TO 'result.geojson' WITH (FORMAT GDAL, DRIVER 'GeoJSON') ``` -------------------------------- ### Nearest Neighbor Search (Top-K) Source: https://github.com/duckdb/duckdb-skills/blob/main/skills/spatial/references/functions.md Finds the top K nearest neighbors for each point in a set ('locations') from another set ('targets'). Uses a lateral join for efficiency. ```sql SELECT a.name, b.name AS nearest, ST_Distance_Spheroid(a.geom, b.geom) AS dist_m FROM locations a CROSS JOIN LATERAL ( SELECT name, geom FROM targets b ORDER BY ST_Distance_Spheroid(a.geom, b.geom) LIMIT 3 ) b; ```