Skip to content

Instantly share code, notes, and snippets.

@woodRock
Last active June 3, 2023 09:26
Show Gist options
  • Save woodRock/439a4192ad006280abad9fabe643d8b3 to your computer and use it in GitHub Desktop.
Save woodRock/439a4192ad006280abad9fabe643d8b3 to your computer and use it in GitHub Desktop.
Postgres function to give first n prime numbers in SQL.
create or replace function primes(n int)
returns setof int as $$
declare
i integer := 2;
p integer := 0;
j integer := 0;
begin
while i <= n loop
j := floor(sqrt(i));
p := 1;
while j > 1 loop
if i % j = 0 then
p := 0
exit;
end if;
j := j-1;
end loop;
if p = 1 then
return next i;
end if;
i = i+1;
end loop;
end;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment