I have an article table where I want the slug to be unique.
CREATE TABLE article (
title char(50) NOT NULL,
slug char(50) NOT NULL
);
When the user enters a title e.g. News on Apple
, I want to check the database to see if a corresponding slug exists e.g. news-on-apple
. If it does, I'll suffix a numerical value until I find a unique one e.g. news-on-apple-1
. Can that be achieved with a recursive CTE query instead of doing recursion in my ORM. Is there a good ballpark number where I should stop recursing and error out. I can imagine people using the same title a 1000 times which would result in 1000 queries just to create 1 article.
It's possible that my understanding of recursive CTE is incorrect and there's no better way to find a unique slug. Please suggest any alternatives.
Best Answer
First off, you do not want to use
. Usechar(50)
varchar(50)
or justtext
. Read more:Assuming the following rules:
-123
).Note that all of the following methods are subject to a race conditions: concurrent operations might identify the same "free" name for the next slug.
To defend against it, you can impose a UNIQUE constraint on
slug
and be prepared to repeat an INSERT upon duplicate key violation or you to take out a write lock on the table at the start of the transaction.If you glue the suffix to the basic slug name with a dash and allow basic slugs to end in separate numbers, the specification is a tiny bit ambiguous (see comments). I suggest a unique delimiter of your choice instead (which is otherwise disallowed).
Efficient rCTE
Better performance without rCTE
If you worry about thousands of slugs competing for the same slug or generally want to optimize performance, I'd consider a different, faster approach.
If the basic slug isn't taken yet, the more expensive second
SELECT
is never executed - same as above, but much more important here. Check withEXPLAIN ANALYZE
, Postgres is smart that way withLIMIT
queries. Related:Check for the leading string and the suffix separately, so the
LIKE
expression can use a basic btree index withtext_pattern_ops
likeDetailed explanation:
Convert the suffix to integer before you apply
max()
. Numbers in text representation don't work.Optimize performance
To get the optimum, consider storing the suffix separated from the basic slug and concatenate the slug as needed:
concat_ws('-' , slug, suffix::text) AS slug
The query for a new slug then becomes:
Ideally supported with a unique index on
(slug, suffix)
.Query for list of slugs
In any version of Postgres you can provide rows in a
VALUES
expression.You can also use
IN
with a set of row-type expressions Which is shorter:Details under this related question (as commented below):
For long lists, the
JOIN
to aVALUES
expression is typically faster.In Postgres 9.4 (released today!) you can also use the new variant of
unnest()
to unnest multiple arrays in parallel.Given an array of basic slugs and a corresponding array of suffixes (as per comment):