Skip to content

Instantly share code, notes, and snippets.

@statico
Created December 17, 2018 23:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statico/a2c136c02253548e2177f23aeeb2b89d to your computer and use it in GitHub Desktop.
Save statico/a2c136c02253548e2177f23aeeb2b89d to your computer and use it in GitHub Desktop.
PostgreSQL auto-slug / slugification field with trigger
create or replace function update_slug_from_name()
returns trigger as $$
begin
new.slug = regexp_replace(
regexp_replace(
regexp_replace(
lower(new.name),
'''', '', 'g'),
'[^a-z0-9+]+', '-', 'g'),
'^-+|-+$', '');
return new;
end;
$$ language 'plpgsql';
create trigger update_slug before insert or update on things
for each row execute procedure update_slug_from_name();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment