Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improve: SQL examples (#2527)

Akshay Agrawalf95333a40595
diff --git a/docs/guides/sql.md b/docs/guides/sql.md
index 4202027276..6505e9e589 100644
--- a/docs/guides/sql.md
+++ b/docs/guides/sql.md
@@ -11,6 +11,14 @@ including [duckdb](https://duckdb.org/):
pip install marimo[sql]
```
+```{admonition} Examples
+:class: tip
+
+For example notebooks, check out
+[`examples/sql/` on GitHub](https://github.com/marimo-team/marimo/tree/main/examples/sql/).
+```
+
+
## Example
In this example notebook, we have a Pandas dataframe and a SQL cell
diff --git a/examples/sql/README.md b/examples/sql/README.md
index a6736fa413..fa9b804e32 100644
--- a/examples/sql/README.md
+++ b/examples/sql/README.md
@@ -1,12 +1,25 @@
# SQL 🛢️
These examples show how to use marimo's built-in support for SQL, which
-is powered by [duckdb](https://duckdb.org).
+is powered by [duckdb](https://duckdb.org/), a fast in-process
+analytical database.
+
+- `querying_dataframes.py` shows hows to query Pandas or Polars dataframes
+- `paremetrizing_queries.py` shows hows to parametrize queries with Python values
+- `read_csv.py` shows hows to read CSV data into duckdb
+- `read_json.py` shows hows to read JSON data into duckdb
+- `read_parquet.py` shows hows to read parquet data into duckdb
+- `connect_to_sqlite.py` shows hows to connect to a SQLite database
+- `connect_to_postgres.py` shows hows to connect to a PostgreSQL database
+- `connect_to_motherduck.py` shows hows to connect to [motherduck](https://motherduck.com)
+- [`misc/`](misc/) contains illustrative examples
> [!TIP]
-> Submit a
-> [pull request](https://github.com/marimo-team/marimo/pulls) to add an example!
+> For a broad overview of using SQL in marimo, run `marimo tutorial sql` at the
+> command-line.
+Consult the [duckdb documentation](https://duckdb.org/docs/index) for a
+comprehensive guide on duckdb.
## Running examples
diff --git a/examples/sql/motherduck.py b/examples/sql/connect_to_motherduck.py
similarity index 100%
rename from examples/sql/motherduck.py
rename to examples/sql/connect_to_motherduck.py
diff --git a/examples/sql/connect_to_postgres.py b/examples/sql/connect_to_postgres.py
new file mode 100644
index 0000000000..13520413a5
--- /dev/null
+++ b/examples/sql/connect_to_postgres.py
@@ -0,0 +1,184 @@
+# /// script
+# requires-python = ">=3.9"
+# dependencies = [
+# "duckdb==1.1.1",
+# "marimo",
+# "pandas==2.2.3",
+# "requests==2.32.3",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.9.1"
+app = marimo.App(width="medium")
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Connect to Postgres
+
+ You can use marimo's SQL cells to read from and write to Postgres databases.
+
+ The first step is to attach a Postgres database, which we do below.
+
+ For advanced usage, see [duckdb's documentation](https://duckdb.org/docs/extensions/postgres).
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __():
+ import marimo as mo
+
+
+ def download_sample_data():
+ import os
+ import requests
+
+ url = "https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite"
+ filename = "Chinook_Sqlite.sqlite"
+ if not os.path.exists(filename):
+ print("Downloading the Chinook database ...")
+ response = requests.get(url)
+ with open(filename, "wb") as f:
+ f.write(response.content)
+
+
+ download_sample_data()
+ return download_sample_data, mo
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: Creating SQL Cells": mo.md(
+ f"""
+ Create a SQL cell in one of two ways:
+
+ 1. Click the {mo.icon("lucide:database")} `SQL` button at the **bottom of your notebook**
+ 2. **Right-click** the {mo.icon("lucide:circle-plus")} button to the **left of a cell**, and choose `SQL`.
+
+ In the SQL cell, you can query dataframes in your notebook as if
+ they were tables — just reference them by name.
+ """
+ )
+ }
+ )
+ return
+
+
+def __():
+ import os
+
+ PASSWORD = os.getenv("PGPASSWORD", "mysecretpassword")
+ return PASSWORD, os
+
+
+def __(PASSWORD, mo):
+ _df = mo.sql(
+ f"""
+ -- Boilerplate: detach the database so this cell works when you re-run it
+ DETACH DATABASE IF EXISTS db;
+
+ -- Attach the database; omit READ_ONLY if you want to write to the database.
+ -- The ATTACH command accepts either a libpq connection string (as below) or a PostgreSQL URI.
+ -- You can filter to specific schemas, as we do below.
+ ATTACH 'dbname=postgres user=postgres host=127.0.0.1 password={PASSWORD}' as db (
+ TYPE POSTGRES, READ_ONLY, SCHEMA 'public'
+ );
+
+ -- View tables in the public schema
+ SHOW ALL TABLES;
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ Once the database is attached, you can query it with SQL. Note that this involves copying data from Postgres SQL and
+ executing it in duckdb. See later sections of this example on how to execute queries directly in Postgres.
+ """
+ )
+ return
+
+
+def __(db, mo, test_table):
+ _df = mo.sql(
+ f"""
+ -- Query your tables! This assumes a database with schema public and a sample table called test_table.
+ SELECT * FROM db.public.test_table;
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ f"""
+ You can explore the schemas of all your tables at a glance in the **data sources panel**: click
+ the {mo.icon("lucide:database")} icon in the left sidebar to open it.
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ ## Copy data from Postgres to duckdb
+
+ To prevent duckdb from continuously re-reading tables from PostgresSQL, you can copy the PostgresSQL databases into DuckDB. Note that this will consume your system's RAM.
+ """
+ )
+ return
+
+
+def __(db, duckdb_table, mo, test_table):
+ _df = mo.sql(
+ f"""
+ CREATE OR REPlACE TABLE duckdb_table AS FROM db.public.test_table;
+
+ SELECT * FROM duckdb_table;
+ """
+ )
+ return (duckdb_table,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ ## Execute queries directly in PostgresSQL
+
+ Run queries directly in PostgresSQL using duckdb's `postgres_query` function. In some cases this may be faster than executing queries in duckdb.
+ """
+ )
+ return
+
+
+def __(mo):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM postgres_query('db', 'SELECT * FROM test_table');
+ """
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/sql/sqlite.py b/examples/sql/connect_to_sqlite.py
similarity index 54%
rename from examples/sql/sqlite.py
rename to examples/sql/connect_to_sqlite.py
index c8fea9cc43..5e20883d6e 100644
--- a/examples/sql/sqlite.py
+++ b/examples/sql/connect_to_sqlite.py
@@ -1,12 +1,16 @@
# /// script
# requires-python = ">=3.9"
# dependencies = [
+# "duckdb==1.1.1",
# "marimo",
+# "pandas==2.2.3",
+# "requests==2.32.3",
# ]
# ///
+
import marimo
-__generated_with = "0.7.18"
+__generated_with = "0.9.1"
app = marimo.App(width="medium")
@@ -14,29 +18,75 @@ app = marimo.App(width="medium")
def __(mo):
mo.md(
r"""
- # SQLite!
+ # Connect to SQLite
- You can use marimo's SQL cells to read from (and write to) SQLite databases.
+ You can use marimo's SQL cells to read from and write to SQLite databases.
The first step is to attach a SQLite database. We attach to a sample database in a read-only mode below.
+
+ For advanced usage, see [duckdb's documentation](https://duckdb.org/docs/extensions/sqlite).
"""
)
return
[email protected](hide_code=True)
+def __():
+ import marimo as mo
+
+
+ def download_sample_data():
+ import os
+ import requests
+
+ url = "https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite"
+ filename = "Chinook_Sqlite.sqlite"
+ if not os.path.exists(filename):
+ print("Downloading the Chinook database ...")
+ response = requests.get(url)
+ with open(filename, "wb") as f:
+ f.write(response.content)
+
+
+ download_sample_data()
+ return download_sample_data, mo
+
+
[email protected](hide_code=True)
def __(mo):
+ mo.accordion(
+ {
+ "Tip: Creating SQL Cells": mo.md(
+ f"""
+ Create a SQL cell in one of two ways:
+
+ 1. Click the {mo.icon("lucide:database")} `SQL` button at the **bottom of your notebook**
+ 2. **Right-click** the {mo.icon("lucide:circle-plus")} button to the **left of a cell**, and choose `SQL`.
+
+ In the SQL cell, you can query dataframes in your notebook as if
+ they were tables — just reference them by name.
+ """
+ )
+ }
+ )
+ return
+
+
+def __(INFORMATION_SCHEMA, mo):
_df = mo.sql(
f"""
- -- boilerplate: detach the database so this cell works when you re-run it
+ -- Boilerplate: detach the database so this cell works when you re-run it
DETACH DATABASE IF EXISTS chinook;
- -- attach the database; omit READ_ONLY if you want to write to the database.
+
+ -- Attach the database; omit READ_ONLY if you want to write to the database.
ATTACH 'Chinook_Sqlite.sqlite' as chinook (TYPE SQLITE, READ_ONLY);
+ -- This query lists all the tables in the Chinook database
SELECT table_name FROM INFORMATION_SCHEMA.TABLES where table_catalog == 'chinook';
"""
)
- return
+ return (chinook,)
@app.cell(hide_code=True)
@@ -46,7 +96,7 @@ def __(mo):
@app.cell
-def __(mo, track):
+def __(chinook, mo, track):
_df = mo.sql(
f"""
SELECT composer, MEAN(Milliseconds) as avg_track_ms from chinook.track GROUP BY composer ORDER BY avg_track_ms DESC;
@@ -56,27 +106,14 @@ def __(mo, track):
@app.cell(hide_code=True)
-def __():
- import marimo as mo
-
-
- def download_sample_data():
- import os
- import requests
-
- url = "https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite"
- filename = "Chinook_Sqlite.sqlite"
- if not os.path.exists(filename):
- print("Downloading the Chinook database ...")
- response = requests.get(url)
- with open(filename, "wb") as f:
- f.write(response.content)
- else:
- print("Using cached database.")
-
-
- download_sample_data()
- return download_sample_data, mo
+def __(mo):
+ mo.md(
+ f"""
+ You can explore the schemas of all your tables at a glance in the **data sources panel**: click
+ the {mo.icon("lucide:database")} icon in the left sidebar to open it.
+ """
+ )
+ return
if __name__ == "__main__":
diff --git a/examples/sql/misc/README.md b/examples/sql/misc/README.md
new file mode 100644
index 0000000000..84f6461d22
--- /dev/null
+++ b/examples/sql/misc/README.md
@@ -0,0 +1,23 @@
+# Misc. SQL examples 🛢️
+
+This folder contains illustrative examples of using SQL in marimo.
+
+> [!TIP]
+> For a broad overview of using SQL in marimo, run `marimo tutorial sql` at the
+> command-line.
+
+## Running examples
+
+The requirements of each notebook are serialized in them as a top-level
+comment. Here are the steps to open an example notebook:
+
+1. [Install marimo](https://docs.marimo.io/getting_started/index.html#installation)
+2. [Install `uv`](https://github.com/astral-sh/uv/?tab=readme-ov-file#installation)
+3. Open an example with `marimo edit --sandbox <notebook.py>`.
+
+> [!TIP]
+> The [`--sandbox` flag](https://docs.marimo.io/guides/editor_features/package_management.html) opens the notebook in an isolated virtual environment,
+> automatically installing the notebook's dependencies 📦
+
+You can also open notebooks without `uv`, with just `marimo edit <notebook.py>`;
+however, you'll need to install the requirements yourself.
diff --git a/examples/sql/duckdb_connections.py b/examples/sql/misc/database_explorer.py
similarity index 89%
rename from examples/sql/duckdb_connections.py
rename to examples/sql/misc/database_explorer.py
index c7a6fe1ad9..a2bd409f7c 100644
--- a/examples/sql/duckdb_connections.py
+++ b/examples/sql/misc/database_explorer.py
@@ -3,25 +3,34 @@
# dependencies = [
# "duckdb==1.1.1",
# "marimo",
+# "pandas==2.2.3",
# ]
# ///
import marimo
-__generated_with = "0.8.19"
+__generated_with = "0.9.1"
app = marimo.App(width="full")
@app.cell
def __():
- import marimo as mo
import os
- return mo, os
+
+ import duckdb
+ import marimo as mo
+ return duckdb, mo, os
@app.cell(hide_code=True)
def __(mo):
- mo.md(r"""## Create a connection""")
+ mo.md(
+ r"""
+ # Database explorer
+
+ This notebook lets you explore the contents of a database. Start by providing a database URL.
+ """
+ )
return
@@ -36,7 +45,7 @@ def __(mo, os):
return (database_url,)
[email protected](hide_code=True)
def __(database_url):
import duckdb
@@ -50,7 +59,7 @@ def __(database_url):
ATTACH DATABASE '{database_url.value}' AS my_db (TYPE postgres, READ_ONLY);
"""
)
- return (duckdb,)
+ return duckdb, my_db
@app.cell
@@ -59,7 +68,7 @@ def __(duckdb):
return
[email protected](hide_code=True)
def __(mo):
mo.md(r"""## Tables""")
return
@@ -75,19 +84,7 @@ def __(mo):
return
-def __(duckdb):
- # Create another table, if wanted
- if False:
- duckdb.execute(
- """
- CREATE TABLE IF NOT EXISTS penguins AS SELECT * FROM read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv', AUTO_DETECT=TRUE);
- """
- )
- return
-
-
[email protected](hide_code=True)
def __(mo):
mo.md(r"""## Other meta table functions""")
return
@@ -137,14 +134,14 @@ def __(_, function, mo):
return
[email protected](hide_code=True)
def __(mo):
mo.md(r"""## Interact with your tables""")
return
@app.cell
-def __(duckdb, mo):
+def __(duckdb, duckdb_tables, mo):
tables = duckdb.execute(
"""
SELECT table_name FROM duckdb_tables() WHERE internal = False;
diff --git a/examples/sql/electric_vehicles.py b/examples/sql/misc/electric_vehicles.py
similarity index 100%
rename from examples/sql/electric_vehicles.py
rename to examples/sql/misc/electric_vehicles.py
diff --git a/examples/sql/sql_cars.py b/examples/sql/misc/sql_cars.py
similarity index 100%
rename from examples/sql/sql_cars.py
rename to examples/sql/misc/sql_cars.py
diff --git a/examples/sql/parametrizing_sql_queries.py b/examples/sql/parametrizing_sql_queries.py
new file mode 100644
index 0000000000..130b6669bf
--- /dev/null
+++ b/examples/sql/parametrizing_sql_queries.py
@@ -0,0 +1,126 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "duckdb==1.1.1",
+# "marimo",
+# "pandas==2.2.3",
+# "vega-datasets==0.9.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.9.1"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ """
+ # Parametrizing SQL Queries
+
+ This notebook shows parametrize SQL queries with Python values, using Python f-string interpolation.
+
+ First, we create a dataframe called `df`.
+ """
+ )
+ return
+
+
+def __():
+ from vega_datasets import data
+
+ df = data.iris()
+ df
+ return data, df
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(r"""Next, we create a dropdown that selects the iris species.""")
+ return
+
+
+def __(mo):
+ species_dropdown = mo.ui.dropdown(["setosa", "versicolor", "virginica"], value="setosa")
+ species_dropdown
+ return (species_dropdown,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ """
+ Next, we **create a SQL cell** that filters the table to the selected species.
+
+ Notice that we can reference the Python variable `species_dropdown` in our query
+ using **curly braces**. This is because marimo represents SQL queries as Python
+ f-strings.
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: Creating SQL Cells": mo.md(
+ f"""
+ Create a SQL cell in one of two ways:
+
+ 1. Click the {mo.icon("lucide:database")} `SQL` button at the **bottom of your notebook**
+ 2. **Right-click** the {mo.icon("lucide:circle-plus")} button to the **left of a cell**, and choose `SQL`.
+
+ In the SQL cell, you can query dataframes in your notebook as if
+ they were tables — just reference them by name.
+ """
+ )
+ }
+ )
+ return
+
+
+def __(df, mo, species_dropdown):
+ result = mo.sql(
+ f"""
+ SELECT * FROM df where species == '{species_dropdown.value}'
+ """, output=False
+ )
+ return (result,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ The query output is returned to Python as a dataframe (Polars if you have it installed, Pandas otherwise).
+
+ Choose the dataframe name via the **output variable** input in the bottom-left
+ of the cell. If the name starts with an underscore, it won't be made available
+ to other cells. In this case, we've named the output `result`.
+
+ Try changing the selected species in the `species_dropdown`, and watch how the query result changes.
+ """
+ )
+ return
+
+
+def __(result):
+ result
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/sql/querying_dataframes.py b/examples/sql/querying_dataframes.py
new file mode 100644
index 0000000000..e60055ba31
--- /dev/null
+++ b/examples/sql/querying_dataframes.py
@@ -0,0 +1,94 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "duckdb==1.1.1",
+# "marimo",
+# "pandas==2.2.3",
+# "vega-datasets==0.9.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.9.1"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ """
+ # Querying dataframes
+
+ This notebook shows how to use SQL to query Python dataframes.
+
+ First, we create a dataframe called `df`.
+ """
+ )
+ return
+
+
+def __():
+ from vega_datasets import data
+
+ df = data.iris()
+ df.head()
+ return data, df
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ f"""
+ Next, we **create a SQL cell**.
+
+ Create a SQL cell in one of two ways:
+
+ 1. Click the {mo.icon("lucide:database")} `SQL` button at the **bottom of your notebook**
+ 2. **Right-click** the {mo.icon("lucide:circle-plus")} button to the **left of a cell**, and choose `SQL`.
+
+ In the SQL cell, you can query dataframes in your notebook as if they were tables — just reference them by name.
+ """
+ )
+ return
+
+
+def __(df, mo):
+ result = mo.sql(
+ f"""
+ SELECT species, mean(petalLength) as meanPetalLength FROM df GROUP BY species ORDER BY meanPetalLength
+ """, output=False
+ )
+ return (result,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ The query output is returned to Python as a dataframe (Polars if you have it installed, Pandas otherwise).
+
+ Choose the dataframe name via the **output variable** input in the bottom-left of the cell. If the name starts with an underscore, it won't be made available to other cells.
+
+ In this case, we've named the output `result`.
+ """
+ )
+ return
+
+
+def __(result):
+ result
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/sql/read_csv.py b/examples/sql/read_csv.py
new file mode 100644
index 0000000000..4a81854645
--- /dev/null
+++ b/examples/sql/read_csv.py
@@ -0,0 +1,145 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "duckdb==1.1.1",
+# "marimo",
+# "pandas==2.2.3",
+# "vega-datasets==0.9.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.9.1"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ """
+ # Read CSV
+
+ This notebook shows how to read a CSV file from a local file or a URL into an in-memory table.
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __():
+ import marimo as mo
+ import pandas as pd
+
+ pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]}).to_csv("data.csv")
+ return mo, pd
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md("""Reading from a local CSV is as easy as `SELECT * from "data.csv"`, where `data.csv` is the path to your local file (or a URL to a CSV file).""")
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: Creating SQL Cells": mo.md(
+ f"""
+ Create a SQL cell in one of two ways:
+
+ 1. Click the {mo.icon("lucide:database")} `SQL` button at the **bottom of your notebook**
+ 2. **Right-click** the {mo.icon("lucide:circle-plus")} button to the **left of a cell**, and choose `SQL`.
+
+ In the SQL cell, you can query dataframes in your notebook as if
+ they were tables — just reference them by name.
+ """
+ )
+ }
+ )
+ return
+
+
+def __(data, mo):
+ result = mo.sql(
+ f"""
+ -- Tip: you can also specify the data files using a glob, such as '/path/to/*.csv'
+ -- or '/path/**/to/*.csv'
+ SELECT * FROM "data.csv"
+ """, output=False
+ )
+ return (result,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: Query output": mo.md(
+ r"""
+ The query output is returned to Python as a dataframe (Polars if you have it installed, Pandas otherwise).
+
+ Choose the dataframe name via the **output variable** input in the bottom-left
+ of the cell. If the name starts with an underscore, it won't be made available
+ to other cells. In this case, we've named the output `result`.
+ """
+ )
+ }
+ )
+ return
+
+
+def __(result):
+ result
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ ## Create an in-memory table from a CSV file
+
+ You can also create a table from a CSV file, so you can easily query it in subsequent cells. This table will appear in marimo's data sources panel.
+ """
+ )
+ return
+
+
+def __(data, mo):
+ _df = mo.sql(
+ f"""
+ CREATE TABLE myTable AS SELECT * FROM "data.csv"
+ """
+ )
+ return (myTable,)
+
+
+def __(mo, myTable):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM myTable
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(r"""## Advanced usage""")
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(r"""To customize how your CSV is read, including specifying the delimiter type, use [duckdb's `read_csv` function](https://duckdb.org/docs/data/csv/overview.html).""")
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/sql/read_json.py b/examples/sql/read_json.py
new file mode 100644
index 0000000000..13f7be1377
--- /dev/null
+++ b/examples/sql/read_json.py
@@ -0,0 +1,156 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "duckdb==1.1.1",
+# "marimo",
+# "pandas==2.2.3",
+# "pyarrow==17.0.0",
+# "vega-datasets==0.9.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.9.1"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ """
+ # Read JSON
+
+ This notebook shows how to read a JSON file from a local file or a URL into an in-memory table.
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __():
+ import marimo as mo
+ import pandas as pd
+
+ pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]}).to_json("data.json", orient="records")
+ return mo, pd
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ """
+ Reading from a JSON file is as easy as
+
+ ```sql
+ SELECT * from 'data.json'
+ ```
+
+ where `data.json` is the path or URL to your json file.
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: Creating SQL Cells": mo.md(
+ f"""
+ Create a SQL cell in one of two ways:
+
+ 1. Click the {mo.icon("lucide:database")} `SQL` button at the **bottom of your notebook**
+ 2. **Right-click** the {mo.icon("lucide:circle-plus")} button to the **left of a cell**, and choose `SQL`.
+
+ In the SQL cell, you can query dataframes in your notebook as if
+ they were tables — just reference them by name.
+ """
+ )
+ }
+ )
+ return
+
+
+def __(data, mo):
+ result = mo.sql(
+ f"""
+ -- Tip: you can also specify the data files using a glob, such as '/path/to/*.json'
+ -- or '/path/**/to/*.json'
+ SELECT * FROM 'data.json'
+ """, output=False
+ )
+ return (result,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: Query output": mo.md(
+ r"""
+ The query output is returned to Python as a dataframe (Polars if you have it installed, Pandas otherwise).
+
+ Choose the dataframe name via the **output variable** input in the bottom-left
+ of the cell. If the name starts with an underscore, it won't be made available
+ to other cells. In this case, we've named the output `result`.
+ """
+ )
+ }
+ )
+ return
+
+
+def __(result):
+ result
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ ## Create an in-memory table from a JSON file
+
+ You can also create a table from a JSON file, so you can easily query it in subsequent cells. This table will appear in marimo's data sources panel.
+ """
+ )
+ return
+
+
+def __(data, mo):
+ _df = mo.sql(
+ f"""
+ CREATE OR REPLACE TABLE myTable AS SELECT * FROM 'data.json'
+ """
+ )
+ return (myTable,)
+
+
+def __(mo, myTable):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM myTable
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(r"""## Advanced usage""")
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(r"""To customize how your json file is read, use [duckdb's `read_json` function](https://duckdb.org/docs/data/json/overview.html).""")
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/sql/read_parquet.py b/examples/sql/read_parquet.py
new file mode 100644
index 0000000000..a39cb211d5
--- /dev/null
+++ b/examples/sql/read_parquet.py
@@ -0,0 +1,146 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "duckdb==1.1.1",
+# "marimo",
+# "pandas==2.2.3",
+# "pyarrow==17.0.0",
+# "vega-datasets==0.9.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.9.1"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ """
+ # Read Parquet
+
+ This notebook shows how to read a Parquet file from a local file or a URL into an in-memory table.
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __():
+ import marimo as mo
+ import pandas as pd
+
+ pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]}).to_parquet("data.parquet")
+ return mo, pd
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md("""Reading from a Parquet file is as easy as `SELECT * from "data.parquet"`, where `data.parquet` is the path or URL to your parquet file.""")
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: Creating SQL Cells": mo.md(
+ f"""
+ Create a SQL cell in one of two ways:
+
+ 1. Click the {mo.icon("lucide:database")} `SQL` button at the **bottom of your notebook**
+ 2. **Right-click** the {mo.icon("lucide:circle-plus")} button to the **left of a cell**, and choose `SQL`.
+
+ In the SQL cell, you can query dataframes in your notebook as if
+ they were tables — just reference them by name.
+ """
+ )
+ }
+ )
+ return
+
+
+def __(data, mo):
+ result = mo.sql(
+ f"""
+ -- Tip: you can also specify the data files using a glob, such as '/path/to/*.parquet'
+ -- or '/path/**/to/*.parquet'
+ SELECT * FROM 'data.parquet'
+ """, output=False
+ )
+ return (result,)
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.accordion(
+ {
+ "Tip: Query output": mo.md(
+ r"""
+ The query output is returned to Python as a dataframe (Polars if you have it installed, Pandas otherwise).
+
+ Choose the dataframe name via the **output variable** input in the bottom-left
+ of the cell. If the name starts with an underscore, it won't be made available
+ to other cells. In this case, we've named the output `result`.
+ """
+ )
+ }
+ )
+ return
+
+
+def __(result):
+ result
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(
+ r"""
+ ## Create an in-memory table from a Parquet file
+
+ You can also create a table from a Parquet file, so you can easily query it in subsequent cells. This table will appear in marimo's data sources panel.
+ """
+ )
+ return
+
+
+def __(data, mo):
+ _df = mo.sql(
+ f"""
+ CREATE OR REPLACE TABLE myTable AS SELECT * FROM 'data.parquet'
+ """
+ )
+ return (myTable,)
+
+
+def __(mo, myTable):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM myTable
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(r"""## Advanced usage""")
+ return
+
+
[email protected](hide_code=True)
+def __(mo):
+ mo.md(r"""To customize how your parquet file is read, use [duckdb's `read_parquet` function](https://duckdb.org/docs/data/parquet/overview.html).""")
+ return
+
+
+if __name__ == "__main__":
+ app.run()