{"course":{"slug":"hugging-face","title":"Hugging Face, End to End","url":"https://addaly.com/learn/hugging-face","level":"intermediate","track":"create"},"lesson":{"slug":"the-viewer-and-sql","title":"Query a dataset with SQL before downloading it","url":"https://addaly.com/learn/hugging-face/the-viewer-and-sql","position":42,"of":75,"minutes":8,"answer":"DuckDB can query the available Hub Parquet files directly. It can read only the columns a query needs and may skip row groups when a filter and file statistics allow it.","keyIdea":"DuckDB can query the available Hub Parquet files directly. It can read only the columns a query needs and may skip row groups when a filter and file statistics allow it."},"body":{"format":"markdown","text":"## The conversion nobody mentions\n\nThe Hub Dataset Viewer provides Parquet files for supported datasets. Its Parquet endpoint lists available files and indicates when conversion is partial. Check the split and whether the listed files cover your question.\n\nDuckDB can query remote Parquet files directly. You can count labels or inspect lengths without manually downloading an entire dataset first.\n\n## DuckDB, which is free and is one pip install\n\n```bash\npip install duckdb requests\n```\n\n```python\nimport duckdb\nimport requests\n\nendpoint = (\n    \"https://datasets-server.huggingface.co/parquet\"\n)\nresponse = requests.get(\n    endpoint,\n    params={\"dataset\": \"stanfordnlp/imdb\"},\n    timeout=20,\n)\nresponse.raise_for_status()\npayload = response.json()\nif payload.get(\"partial\") or payload.get(\"failed\"):\n    raise RuntimeError(\"Parquet files are incomplete\")\nfiles = payload[\"parquet_files\"]\ntrain = [\n    item[\"url\"] for item in files\n    if item[\"split\"] == \"train\"\n    and item[\"config\"] == \"plain_text\"\n]\nif not train:\n    raise RuntimeError(\"No train Parquet files listed\")\nq = \"\"\"\nSELECT label, COUNT(*) AS n\nFROM read_parquet(?)\nGROUP BY label\nORDER BY label\n\"\"\"\nprint(duckdb.execute(q, [train]).fetchall())\n```\n\nParquet stores columns separately within each row group. DuckDB reads the columns needed by the query. A suitable filter can also let it skip row groups when available statistics rule them out. An unfiltered count by label still needs the label data across the selected files. Transfer size depends on the files, compression and query.\n\n> Figure: How a filtered Parquet query reads data. Steps: 1. Read metadata (Column and row-group information); 2. Apply the filter (Skip groups when statistics rule them out); 3. Read needed columns (Fetch the relevant data ranges); 4. Count matching rows (Aggregate the selected files). A filter may rule out row groups using metadata. The query reads the required columns from the remaining groups and calculates the exact result for the selected files.\n\nThe same API response lists the split, URL and size for each file:\n\n```python\nfor f in files[:3]:\n    print(f[\"split\"], f[\"url\"], f[\"size\"])\n```\n\n## Five questions to ask before downloading\n\nThe paths below containing `...` are placeholders. Use URLs from the API for the split you want. To query a split with several files, pass the list of URLs to `read_parquet` as in the example above.\n\n1. **How big is each class?** A dataset described as balanced frequently is not.\n\n   ```sql\n   SELECT label, COUNT(*)\n   FROM 'hf://datasets/.../train-*.parquet'\n   GROUP BY label\n   ```\n\n2. **How long are the texts?** Character counts give a first look. Measure token counts with your intended tokenizer before setting its length limit.\n\n   ```sql\n   SELECT MIN(len), MAX(len), MEDIAN(len),\n          QUANTILE_CONT(len, 0.95) AS p95\n   FROM (SELECT LENGTH(text) AS len FROM '...')\n   ```\n\n3. **How many extra rows repeat a non-null text?**\n\n   ```sql\n   SELECT COUNT(text) - COUNT(DISTINCT text) AS dupes\n   FROM '...'\n   ```\n\n4. **Does the test split overlap the train split?** This counts each matching test row once, even if several training rows share that text:\n\n   ```sql\n   SELECT COUNT(*)\n   FROM 'hf://datasets/.../test-*.parquet' t\n   WHERE EXISTS (\n     SELECT 1 FROM 'hf://datasets/.../train-*.parquet' r\n     WHERE t.text = r.text\n   )\n   ```\n\n5. **What does the rare class actually look like?** Pull twenty rows and read them. Ten minutes of reading beats an hour of aggregate statistics, every time.\n\n## The viewer itself does more than you think\n\nThe dataset page can offer text search, sorting, filters and column statistics. Available features depend on the dataset. Use the viewer for a first look without manually downloading the full dataset.\n\nFor example, look for one language dominating a multilingual corpus or for missing entries in a text column.\n\n## Turning a query into a view of the whole corpus\n\nOne more pattern is worth having. Aggregates answer what is in a dataset; a sample answers what it is like. Combine them:\n\n```sql\nSELECT label, text\nFROM 'hf://datasets/.../train-*.parquet'\nUSING SAMPLE 20 ROWS\n```\n\nThe query returns up to twenty rows for manual inspection. The amount of source data read depends on the sampling method and query plan. Inspecting a sample can reveal formatting, boilerplate and encoding issues that a count alone does not show.\n\n## The limits\n\n- **Public datasets only** by default. Gated and private ones need a token, and very large ones may be only partially converted, which the viewer states.\n- **Some datasets have no viewer at all**: a custom loading script, an unsupported format, or an explicit opt-out. Absence is not a red flag by itself, but it does mean you are back to reading files by hand.\n- **The parquet copy can lag** a very recent update by a short period.\n\n## Querying your own files the same way\n\nDuckDB is not a Hub feature; it is a local database that happens to read remote parquet. Everything above works on a folder of your own files:\n\n```python\nduckdb.sql(\n    (\n        \"SELECT COUNT(*) FROM 'data/\"\n        \"*.parquet' WHERE lang = 'hi'\"\n    )\n)\n```\n\nAnd it goes the other way, straight into the library:\n\n```python\nfrom datasets import Dataset\n\ndf = duckdb.sql(\n    (\n        \"SELECT text, label FROM '...' \"\n        \"WHERE LENGTH(text) BETWEEN 50 AND \"\n        \"2000\"\n    )\n).df()\nds = Dataset.from_pandas(df)\n```\n\nSQL for selection and aggregation, `datasets` for the training path. That combination handles almost everything without Spark, without a cluster, and on hardware you already own.\n\n## Do this now\n\nPick a public dataset with an available Parquet split. Run the relevant queries above using the listed file URLs. Record which split and files you included so another learner can interpret your result."},"check":{"question":"A Parquet file has label, text and image columns. What helps an unfiltered query count rows by label without reading the image data?","options":[{"text":"The Hub caches answers for every possible query.","correct":false,"tempting":"DuckDB computes the requested aggregate from the input data."},{"text":"The reader reads only the label column for this query.","correct":true},{"text":"The reader samples groups and extrapolates the counts.","correct":false,"tempting":"The query asks for exact counts across the selected files."},{"text":"The reader filters out every row group except the first.","correct":false,"tempting":"There is no filter to justify skipping those groups."}]},"prev":{"slug":"map-filter-and-batching","title":"Transforming a million rows without waiting an hour","url":"https://addaly.com/learn/hugging-face/map-filter-and-batching"},"next":{"slug":"building-your-own-dataset","title":"Turning your files into a dataset","url":"https://addaly.com/learn/hugging-face/building-your-own-dataset"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Query a dataset with SQL before downloading it', in Hugging Face, End to End. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/hugging-face/the-viewer-and-sql (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Query a dataset with SQL before downloading it","courseTitle":"Hugging Face, End to End","module":{"index":5,"slug":"datasets-and-the-work-before-the-model","title":"Datasets, and the work that happens before any model"},"answer":null,"keyIdea":"DuckDB can query the available Hub Parquet files directly. It can read only the columns a query needs and may skip row groups when a filter and file statistics allow it.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"type":"flow","title":"How a filtered Parquet query reads data","caption":"A filter may rule out row groups using metadata. The query reads the required columns from the remaining groups and calculates the exact result for the selected files.","steps":[{"label":"Read metadata","detail":"Column and row-group information"},{"label":"Apply the filter","detail":"Skip groups when statistics rule them out"},{"label":"Read needed columns","detail":"Fetch the relevant data ranges"},{"label":"Count matching rows","detail":"Aggregate the selected files"}]},"alt":"Figure: How a filtered Parquet query reads data. Steps: 1. Read metadata (Column and row-group information); 2. Apply the filter (Skip groups when statistics rule them out); 3. Read needed columns (Fetch the relevant data ranges); 4. Count matching rows (Aggregate the selected files). A filter may rule out row groups using metadata. The query reads the required columns from the remaining groups and calculates the exact result for the selected files."}},"blocks":[{"t":"h2","id":"the-conversion-nobody-mentions","runs":[{"text":"The conversion nobody mentions"}]},{"t":"p","runs":[{"text":"The Hub Dataset Viewer provides Parquet files for supported datasets. Its Parquet endpoint lists available files and indicates when conversion is partial. Check the split and whether the listed files cover your question."}]},{"t":"p","runs":[{"text":"DuckDB can query remote Parquet files directly. You can count labels or inspect lengths without manually downloading an entire dataset first."}]},{"t":"h2","id":"duckdb-which-is-free-and-is-one-pip-install","runs":[{"text":"DuckDB, which is free and is one pip install"}]},{"t":"code","lang":"bash","label":"Bash","text":"pip install duckdb requests"},{"t":"code","lang":"python","label":"Python","text":"import duckdb\nimport requests\n\nendpoint = (\n    \"https://datasets-server.huggingface.co/parquet\"\n)\nresponse = requests.get(\n    endpoint,\n    params={\"dataset\": \"stanfordnlp/imdb\"},\n    timeout=20,\n)\nresponse.raise_for_status()\npayload = response.json()\nif payload.get(\"partial\") or payload.get(\"failed\"):\n    raise RuntimeError(\"Parquet files are incomplete\")\nfiles = payload[\"parquet_files\"]\ntrain = [\n    item[\"url\"] for item in files\n    if item[\"split\"] == \"train\"\n    and item[\"config\"] == \"plain_text\"\n]\nif not train:\n    raise RuntimeError(\"No train Parquet files listed\")\nq = \"\"\"\nSELECT label, COUNT(*) AS n\nFROM read_parquet(?)\nGROUP BY label\nORDER BY label\n\"\"\"\nprint(duckdb.execute(q, [train]).fetchall())"},{"t":"p","runs":[{"text":"Parquet stores columns separately within each row group. DuckDB reads the columns needed by the query. A suitable filter can also let it skip row groups when available statistics rule them out. An unfiltered count by label still needs the label data across the selected files. Transfer size depends on the files, compression and query."}]},{"t":"p","runs":[{"text":"The same API response lists the split, URL and size for each file:"}]},{"t":"code","lang":"python","label":"Python","text":"for f in files[:3]:\n    print(f[\"split\"], f[\"url\"], f[\"size\"])"},{"t":"h2","id":"five-questions-to-ask-before-downloading","runs":[{"text":"Five questions to ask before downloading"}]},{"t":"p","runs":[{"text":"The paths below containing "},{"text":"...","code":true},{"text":" are placeholders. Use URLs from the API for the split you want. To query a split with several files, pass the list of URLs to "},{"text":"read_parquet","code":true},{"text":" as in the example above."}]},{"t":"ol","start":1,"items":[[{"text":"How big is each class?","b":true},{"text":" A dataset described as balanced frequently is not."}]]},{"t":"code","lang":"sql","label":"SQL","text":"SELECT label, COUNT(*)\nFROM 'hf://datasets/.../train-*.parquet'\nGROUP BY label"},{"t":"ol","start":2,"items":[[{"text":"How long are the texts?","b":true},{"text":" Character counts give a first look. Measure token counts with your intended tokenizer before setting its length limit."}]]},{"t":"code","lang":"sql","label":"SQL","text":"SELECT MIN(len), MAX(len), MEDIAN(len),\n       QUANTILE_CONT(len, 0.95) AS p95\nFROM (SELECT LENGTH(text) AS len FROM '...')"},{"t":"ol","start":3,"items":[[{"text":"How many extra rows repeat a non-null text?","b":true}]]},{"t":"code","lang":"sql","label":"SQL","text":"SELECT COUNT(text) - COUNT(DISTINCT text) AS dupes\nFROM '...'"},{"t":"ol","start":4,"items":[[{"text":"Does the test split overlap the train split?","b":true},{"text":" This counts each matching test row once, even if several training rows share that text:"}]]},{"t":"code","lang":"sql","label":"SQL","text":"SELECT COUNT(*)\nFROM 'hf://datasets/.../test-*.parquet' t\nWHERE EXISTS (\n  SELECT 1 FROM 'hf://datasets/.../train-*.parquet' r\n  WHERE t.text = r.text\n)"},{"t":"ol","start":5,"items":[[{"text":"What does the rare class actually look like?","b":true},{"text":" Pull twenty rows and read them. Ten minutes of reading beats an hour of aggregate statistics, every time."}]]},{"t":"h2","id":"the-viewer-itself-does-more-than-you-think","runs":[{"text":"The viewer itself does more than you think"}]},{"t":"p","runs":[{"text":"The dataset page can offer text search, sorting, filters and column statistics. Available features depend on the dataset. Use the viewer for a first look without manually downloading the full dataset."}]},{"t":"p","runs":[{"text":"For example, look for one language dominating a multilingual corpus or for missing entries in a text column."}]},{"t":"h2","id":"turning-a-query-into-a-view-of-the-whole-corpus","runs":[{"text":"Turning a query into a view of the whole corpus"}]},{"t":"p","runs":[{"text":"One more pattern is worth having. Aggregates answer what is in a dataset; a sample answers what it is like. Combine them:"}]},{"t":"code","lang":"sql","label":"SQL","text":"SELECT label, text\nFROM 'hf://datasets/.../train-*.parquet'\nUSING SAMPLE 20 ROWS"},{"t":"p","runs":[{"text":"The query returns up to twenty rows for manual inspection. The amount of source data read depends on the sampling method and query plan. Inspecting a sample can reveal formatting, boilerplate and encoding issues that a count alone does not show."}]},{"t":"h2","id":"the-limits","runs":[{"text":"The limits"}],"role":"limit"},{"t":"ul","items":[[{"text":"Public datasets only","b":true},{"text":" by default. Gated and private ones need a token, and very large ones may be only partially converted, which the viewer states."}],[{"text":"Some datasets have no viewer at all","b":true},{"text":": a custom loading script, an unsupported format, or an explicit opt-out. Absence is not a red flag by itself, but it does mean you are back to reading files by hand."}],[{"text":"The parquet copy can lag","b":true},{"text":" a very recent update by a short period."}]]},{"t":"h2","id":"querying-your-own-files-the-same-way","runs":[{"text":"Querying your own files the same way"}]},{"t":"p","runs":[{"text":"DuckDB is not a Hub feature; it is a local database that happens to read remote parquet. Everything above works on a folder of your own files:"}]},{"t":"code","lang":"python","label":"Python","text":"duckdb.sql(\n    (\n        \"SELECT COUNT(*) FROM 'data/\"\n        \"*.parquet' WHERE lang = 'hi'\"\n    )\n)"},{"t":"p","runs":[{"text":"And it goes the other way, straight into the library:"}]},{"t":"code","lang":"python","label":"Python","text":"from datasets import Dataset\n\ndf = duckdb.sql(\n    (\n        \"SELECT text, label FROM '...' \"\n        \"WHERE LENGTH(text) BETWEEN 50 AND \"\n        \"2000\"\n    )\n).df()\nds = Dataset.from_pandas(df)"},{"t":"p","runs":[{"text":"SQL for selection and aggregation, "},{"text":"datasets","code":true},{"text":" for the training path. That combination handles almost everything without Spark, without a cluster, and on hardware you already own."}]},{"t":"h2","id":"do-this-now","runs":[{"text":"Do this now"}],"role":"try"},{"t":"p","runs":[{"text":"Pick a public dataset with an available Parquet split. Run the relevant queries above using the listed file URLs. Record which split and files you included so another learner can interpret your result."}]}],"check":{"question":[{"text":"A Parquet file has label, text and image columns. What helps an unfiltered query count rows by label without reading the image data?"}],"options":[{"text":[{"text":"The Hub caches answers for every possible query."}],"correct":false,"tempting":[{"text":"DuckDB computes the requested aggregate from the input data."}]},{"text":[{"text":"The reader reads only the label column for this query."}],"correct":true,"tempting":null},{"text":[{"text":"The reader samples groups and extrapolates the counts."}],"correct":false,"tempting":[{"text":"The query asks for exact counts across the selected files."}]},{"text":[{"text":"The reader filters out every row group except the first."}],"correct":false,"tempting":[{"text":"There is no filter to justify skipping those groups."}]}],"order":[2,0,3,1],"why":null},"prev":{"slug":"map-filter-and-batching","title":"Transforming a million rows without waiting an hour","minutes":9},"next":{"slug":"building-your-own-dataset","title":"Turning your files into a dataset","minutes":9}}}