Skip to content

Instantly share code, notes, and snippets.

@spidgorny
Created June 19, 2018 11:38
Show Gist options
  • Save spidgorny/b174c7a8fc74f6eb6da0a194c106f03a to your computer and use it in GitHub Desktop.
Save spidgorny/b174c7a8fc74f6eb6da0a194c106f03a to your computer and use it in GitHub Desktop.
YouTube like unique ID in PostgreSQL without plugins
-- function returns random string key like: cg8rP, QUdfX, 4veH7
CREATE OR REPLACE FUNCTION you_id()
RETURNS varchar AS $$
DECLARE
num FLOAT;
key TEXT;
bin BYTEA;
BEGIN
num := random() * 2147483647;
key := md5(num::text);
bin := decode(key, 'hex');
key := encode(bin, 'base64');
key := replace(key, '+', '-');
key := replace(key, '/', '_');
key := substring(key from 1 for 5);
RETURN key;
END;
$$
language 'plpgsql';
SELECT you_id();
-- RNfTL
-- inspiration from
-- https://blog.andyet.com/2016/02/23/generating-shortids-in-postgres
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment