Skip to content

Instantly share code, notes, and snippets.

@tarasglek
Last active January 30, 2025 12:08
Show Gist options
  • Save tarasglek/28e7092002f046bf20684cd6ae23d6d7 to your computer and use it in GitHub Desktop.
Save tarasglek/28e7092002f046bf20684cd6ae23d6d7 to your computer and use it in GitHub Desktop.
duckdb cheatsheet

Duckdb cheatsheet

Use the following to work with duckdb

DESCRIBE command can be used for introspection

-- Create or replace the books table
CREATE OR REPLACE TABLE books (
  id BIGINT PRIMARY KEY,
  title VARCHAR NOT NULL DEFAULT 'Untitled',
  genres_array VARCHAR[] default [],
  publication_date DATE DEFAULT CURRENT_DATE,
  price DECIMAL(10, 2)
);
describe books
column_name column_type null key default extra
id BIGINT NO PRI
title VARCHAR NO 'Untitled'
genres_array VARCHAR[] YES main.list_value()
publication_date DATE YES CURRENT_DATE
price DECIMAL(10,2) YES

create json using struct_pack() and json cast or to_json()

SELECT 
  struct_pack(n:=1, str:='something') as my_struct,
  to_json(struct_pack(n:=1, str:='something')) as to_json_ed,
  struct_pack(n:=1, str:='something')::json as casted_json
my_struct to_json_ed casted_json
{"n": 1, "str": "something"} {"n":1,"str":"something"} {"n":1,"str":"something"}

if you need to do something special cast to json from string

Eg, duckdb syntax does not support empty structs, can use cast string for that

select '{}'::json
CAST('{}' AS "json")
{}

Duckdb has native arrays

use native [] syntax for arrays

select [] as empty, [{'a':1}] as such_nice_array_of_struct, [{'a':1}]::json as wow_json, array_value({'a':1}) array_value_is_verbose, array_agg(1)
empty such_nice_array_of_struct wow_json array_value_is_verbose array_agg_is_verbose
[] [{"a": 1}] [{"a":1}] [{"a": 1}] [1]

Unix time conversions

use epoch_ms, epoch_ns, epoch_us

select current_timestamp, epoch_us(CURRENT_TIMESTAMP)
epoch_ms(CURRENT_TIMESTAMP)
1738238834061
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment