Skip to content

Instantly share code, notes, and snippets.

@pozs
pozs / number_from_base.sql
Last active February 9, 2023 14:33
Base convert functions for PostgreSQL
-- SQL function to convert numbers from custom bases to numeric
-- requires PostgreSQL 9.3+
CREATE OR REPLACE FUNCTION number_from_base(num TEXT, base INTEGER)
RETURNS NUMERIC
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT sum(exp * cn)
@pozs
pozs / json_equals.sql
Last active December 18, 2020 15:29
PostgreSQL function to test if two json values are equal
-- SQL function to test if two json values are equal
-- requires PostgreSQL 9.3+
CREATE OR REPLACE FUNCTION json_equals(json, json)
RETURNS BOOLEAN
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT CASE f1
@pozs
pozs / json_object_agg.sql
Last active May 18, 2020 10:58
Multiple functions to modify json objects in PostgreSQL
-- Aggregate function to aggregate key-value pairs to json object (opposite of json_each())
-- requires PostgreSQL 9.3+ (but < 9.4!)
-- requires function "json_object_set_key"
DROP AGGREGATE IF EXISTS "json_object_agg" (TEXT, anyelement);
CREATE AGGREGATE "json_object_agg" (TEXT, anyelement)
(
STYPE = json,
SFUNC = "json_object_set_key",