Skip to content

Instantly share code, notes, and snippets.

@MNoorFawi
Created May 29, 2020 22:34
Show Gist options
  • Save MNoorFawi/275cc0a054212eade183515fb811acbf to your computer and use it in GitHub Desktop.
Save MNoorFawi/275cc0a054212eade183515fb811acbf to your computer and use it in GitHub Desktop.
Implementing bit count function in PostgreSQL database
CREATE OR REPLACE FUNCTION bits_count(value bigint) RETURNS integer AS $$
DECLARE i integer;
c integer;
bits BIT(25);
BEGIN
c := 0;
bits := value::BIT(25);
FOR i IN 1..LENGTH(bits) LOOP
IF substring(bits, i, 1) = B'1' THEN
c := c + 1;
END IF;
END LOOP;
RETURN c;
END;
$$ LANGUAGE plpgsql;
-- another one to accept only integer (coming from python calls mainly)
CREATE OR REPLACE FUNCTION bits_count(value integer) RETURNS integer AS $$
DECLARE i integer;
c integer;
bits BIT(25);
BEGIN
c := 0;
bits := value::BIT(25);
FOR i IN 1..LENGTH(bits) LOOP
IF substring(bits, i, 1) = B'1' THEN
c := c + 1;
END IF;
END LOOP;
RETURN c;
END;
$$ LANGUAGE plpgsql;
@pandrewhk
Copy link

select bit_count(123::int::bit(32));
-- works as well with just the built-in functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment