Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle a string with mysql/sql

I was wondering, if there is some way to shuffle the letters of a string in mysql/sql, i.e. something like the pseudocode: SELECT SHUFFLE('abcdef')?

Couldn't find any from http://dev.mysql.com/doc/refman/5.0/en/string-functions.html and searching for it just seems to find solutions for shuffling results, not a string.

like image 727
kontur Avatar asked Aug 08 '12 07:08

kontur


People also ask

How do I shuffle in MySQL?

If you need the rows in a random order, grab the required number of rows and then use PHP's shuffle function on the array of rows returned. There can be quite a performance penalty with using ORDER BY RAND() in a query, depending on how many records there are.

How do I shuffle data in SQL?

Whenever we need to sort a given SQL query result set, we have to use the ORDER BY clause. However, to randomize the returned rows, we need the ORDER BY clause to use a function or database object that returns a random value for each row contained in the SQL result set.

How to generate random string in MySQL?

In order to generate a 10 character string, we can use inbuilt functions 'rand()' and 'char()'.

How to generate random string in SQL?

If you need a string of random digits up to 32 characters for test data or just need some junk text to fill a field, SQL Server's NEWID() function makes this simple. NEWID() is used to create a new GUID (globally unique identifier), and we can use that as a base to get a string of random characters.


1 Answers

Here you go:

DELIMITER //

DROP FUNCTION IF EXISTS shuffle //

CREATE FUNCTION shuffle(
    v_chars TEXT
)
RETURNS TEXT
NOT DETERMINISTIC -- multiple RAND()'s
NO SQL
SQL SECURITY INVOKER
COMMENT ''
BEGIN
    DECLARE v_retval TEXT DEFAULT '';
    DECLARE u_pos    INT UNSIGNED;
    DECLARE u        INT UNSIGNED;

    SET u = LENGTH(v_chars);
    WHILE u > 0
    DO
      SET u_pos = 1 + FLOOR(RAND() * u);
      SET v_retval = CONCAT(v_retval, MID(v_chars, u_pos, 1));
      SET v_chars = CONCAT(LEFT(v_chars, u_pos - 1), MID(v_chars, u_pos + 1, u));
      SET u = u - 1;
    END WHILE;

    RETURN v_retval;
END;
//

DELIMITER ;

SELECT shuffle('abcdef');

See sqlfiddle.com for the output.

Tested successfully with mariadb 10.1 (mysql 5.6 equivalent)

like image 163
Ross Smith II Avatar answered Sep 17 '22 20:09

Ross Smith II