Search code examples
mysqlsql-limit

Is it possible to do ORDER BY RAND() LIMIT but include the header?


Is it possible to return a random selection of rows from user table and include the header as the first row? The SQL I have at the moment just returns 5 random rows (not necessarily the header)

SELECT
    'id',
    'name'
UNION ALL SELECT
    id,
    name

INTO OUTFILE 'example.txt'
    FIELDS TERMINATED BY ' , ' ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\r\n'

FROM
    users

ORDER BY RAND() LIMIT 5

Solution

  • Try this

    
    SELECT 'id','name'
    UNION ALL 
    Select a.* from(
        SELECT id, name
        FROM  users
        ORDER BY RAND() LIMIT 5
     )a
    INTO OUTFILE 'example.txt'  FIELDS TERMINATED BY ','  ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\r\n';