I'm using the following query to generate a unique new user:
INSERT INTO `users`
SET `display_name` = CONCAT(
'user',
(
IF(
EXISTS(
SELECT COUNT(`id`) FROM (
SELECT `id` FROM `users`
) AS `A`),
(SELECT COUNT(`id`) + 1 FROM (
SELECT `id` FROM `users`
) AS `A`),
1
)
)
);
The column id
is an INT and a AUTO_INCREMENT PRIMARY KEY. The column display_name
is a VARCHAR and is NOT NULL. This query inserts a new user with sequential display names, such as user1, user2, user3, user4, ...
DESCRIBE returned this:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY NULL NULL NULL NULL NULL NULL NULL No tables used
2 SUBQUERY NULL NULL NULL NULL NULL NULL NULL Select tables optimized away
3 DERIVED users index NULL UNIQUE 302 NULL NULL Using index
4 SUBQUERY NULL NULL NULL NULL NULL NULL NULL Select tables optimized away
5 DERIVED users index NULL UNIQUE 302 NULL NULL Using index
Is this query efficient? If not, what is a more efficient method?