It sounds like you might want a pair of randomly-selected words from a dictionary. It's kind of hard to tell given the lack of clarity of the question.
RANDOM DICTIONARY WORDS
The best way to pick random dictionary words is probably at the PHP end by using a pass-phrase generator that does it for you.
You can do it in PostgreSQL using a table dictionary
with one word
per row, though:
SELECT word FROM dictionary ORDER BY random() LIMIT 2;
Performance will be truly awful with a large dictionary. It can be done much faster if the dictionary doesn't change and there's a unique word_id
with no gaps in the numbering, allowing you to write:
CREATE OR REPLACE FUNCTION get_random_word() RETURNS text AS $$
SELECT word FROM dictionary
WHERE word_id = (
SELECT width_bucket(random(), 0, 1, (SELECT max(word_id) FROM dictionary))
);
$$ LANGUAGE sql;
SELECT get_random_word() || ' ' || get_random_word();
against a table like this:
CREATE TABLE dictionary(word_id serial primary key, word text UNIQUE NOT NULL);
This will only produce consistent results if there are no gaps in the word numbering and if word_id
is unique or the PRIMARY KEY
. It can produce the same word twice. If you want to avoid that you'll need a recursive CTE or some PL/PgSQL.
RANDOM GIBBERISH
If you actually want truly random strings, that's already well covered here on Stack Overflow. See How do you create a random string that's suitable for a session ID in PostgreSQL? among others; look at this search.
To ensure uniqueness, just add a UNIQUE
constraint. Have your application test to see if a unique_violation was raised when you INSERT
ed the row, and insert it with a new random ID if a violation occurred. If you like you can automate this with a PL/PgSQL helper procedure, though it'll still be subject to races between concurrent inserts in different transactions.