Back to Code Snippets
@alex-1
Boxplot quantiles all at onceSQL
Editor's note: with a variety of supported statistical functions, including things like sampling and producing quantiles, DuckDB provides great analytical capabilities not always present in other databases.
Execute this SQL
select unnest([.1,.25,.5,.75,.9]) as quantile, unnest(quantile_cont(i, [.1,.25,.5,.75,.9])) as value from range(101) t(i); /* This returns: | quantile | value | | 0.10 | 10 | | 0.25 | 25 | | 0.50 | 50 | | 0.75 | 75 | | 0.90 | 90 | */
Copy code
Expand
Share link
Dynamic SQL in DuckDB CLISQL
Editor's note: this gets a little recursive for all those SQL nerds out there. It shows you how to use SQL to generate SQL. It also shows you some of the dot commands for interacting with the DuckDB CLI: changing the output format and writing SQL to a file which is then read in for execution.
Execute this SQL
-- Use SQL to generate SQL statements. -- Write them to a file, then execute that file. -- This uses DuckDB CLI-specific features, so it only works in the CLI. .mode list .header off .once my_dynamic_sql.sql select 'CREATE TABLE t' || i || ' AS SELECT ' || i || ' AS my_column;' from generate_series(5) x(i); .read my_dynamic_sql.sql select table_name from duckdb_tables(); -- Check our work!
Copy code
Expand
Share link
Unnest JSON Array into Rows (pseudo-json_each)SQL
Editor's note: as APIs and applications increasingly represent tabular data in JSON format, we sometimes want the comfort of seeing it as rows, queryable in SQL. DuckDB has a great extension for parsing JSON, including the ability to convert into a DuckDB list which can then be unnested into rows.
Execute this SQL
select -- Split DuckDB list into multiple rows unnest( -- Convert JSON array into DuckDB list of JSON elements from_json( json('[{"col1":1, "col2":2}, {"col1":10, "col2":20}]'), '["JSON"]' ) ); /* Returns: {"col1":1,"col2":2} {"col1":10,"col2":20} */
Copy code
Expand
Share link