Categories: Snippets

Generate Slug URL in MySQL

A slug is a short name using human-readable keywords to identify a web page. For example, in the following URL

http://www.example.com/schools/play-school

the slug is play-school. This post shows how to automatically generate slug using SQL in MySQL.

Suppose we have a table schools a field name, and we wish to generate a slug for each school using the name. First, add one field for the slug.

ALTER TABLE schools ADD slug VARCHAR(128) NULL;

Then, generate slugs using school names.

UPDATE schools SET slug = replace(trim(lower(name)), ' ', '-');

Use the following to double-check the slug has only alphabets, numbers or dashes

SELECT * FROM schools WHERE slug NOT RLIKE '^([a-z0-9]+\-)*[a-z0-9]+$';

The following query helps to replace special characters like dots, quotes, etc. Sometimes its necessary to run multiple times to remove dashes.

UPDATE schools SET
    slug = lower(name),
    slug = replace(slug, '.', ' '),
    slug = replace(slug, ',', ' '),
    slug = replace(slug, ';', ' '),
    slug = replace(slug, ':', ' '),
    slug = replace(slug, '?', ' '),
    slug = replace(slug, '%', ' '),
    slug = replace(slug, '&', ' '),
    slug = replace(slug, '#', ' '),
    slug = replace(slug, '*', ' '),
    slug = replace(slug, '!', ' '),
    slug = replace(slug, '_', ' '),
    slug = replace(slug, '@', ' '),
    slug = replace(slug, '+', ' '),
    slug = replace(slug, '(', ' '),
    slug = replace(slug, ')', ' '),
    slug = replace(slug, '[', ' '),
    slug = replace(slug, ']', ' '),
    slug = replace(slug, '/', ' '),
    slug = replace(slug, '-', ' '),
    slug = replace(slug, '\'', ''),
    slug = trim(slug),
    slug = replace(slug, ' ', '-'),
    slug = replace(slug, '--', '-');
UPDATE schools SET
    slug = replace(slug, '--', '-');

Finally, add unique key to the slug field.

ALTER TABLE schools ADD UNIQUE (slug);

 

Recent Posts

How to use SQL LIKE condition with multiple values in PostgreSQL?

[crayon-662d4d3925188191618403/]  

5 years ago

SELECT Null

[crayon-662d4d3925331515938530/]  

5 years ago

ALTER Column SET NOT NULL – pgSQL

[crayon-662d4d39254bd221247904/]  

5 years ago

ADD new Column – pgSQL

[crayon-662d4d392564e215229020/] [crayon-662d4d3925656737034461/]  

5 years ago

WITH RECURSIVE

[crayon-662d4d39257fa126255857/]  

5 years ago