<p>How can I request a random row (or as close to truly random as is possible) in pure SQL?</p>

[{'answer_id': 19414, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 6, 'selected': False, 'text': "<p>I don't know how efficient this is, but I've used it before:</p>\n\n<pre><code>SELECT TOP 1 * FROM MyTable ORDER BY newid()\n</code></pre>\n\n<p>Because GUIDs are pretty random, the ordering means you get a random row.</p>\n"}, {'answer_id': 19415, 'author': 'Paige Ruten', 'author_id': 813, 'author_profile': 'https://Stackoverflow.com/users/813', 'pm_score': 1, 'selected': False, 'text': '<pre><code> SELECT * FROM table ORDER BY RAND() LIMIT 1\n</code></pre>\n'}, {'answer_id': 19416, 'author': 'Jon Galloway', 'author_id': 5, 'author_profile': 'https://Stackoverflow.com/users/5', 'pm_score': 4, 'selected': False, 'text': "<p>You didn't say which server you're using. In older versions of SQL Server, you can use this:</p>\n\n<pre><code>select top 1 * from mytable order by newid()\n</code></pre>\n\n<p>In SQL Server 2005 and up, you can use <code>TABLESAMPLE</code> to get a random sample that's repeatable:</p>\n\n<pre><code>SELECT FirstName, LastName\nFROM Contact \nTABLESAMPLE (1 ROWS) ;\n</code></pre>\n"}, {'answer_id': 19419, 'author': 'Yaakov Ellis', 'author_id': 51, 'author_profile': 'https://Stackoverflow.com/users/51', 'pm_score': 11, 'selected': True, 'text': '<p>See this post: <a href="http://www.petefreitag.com/item/466.cfm" rel="noreferrer">SQL to Select a random row from a database table</a>. It goes through methods for doing this in MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle (the following is copied from that link):</p>\n\n<p>Select a random row with MySQL:</p>\n\n<pre><code>SELECT column FROM table\nORDER BY RAND()\nLIMIT 1\n</code></pre>\n\n<p>Select a random row with PostgreSQL:</p>\n\n<pre><code>SELECT column FROM table\nORDER BY RANDOM()\nLIMIT 1\n</code></pre>\n\n<p>Select a random row with Microsoft SQL Server:</p>\n\n<pre><code>SELECT TOP 1 column FROM table\nORDER BY NEWID()\n</code></pre>\n\n<p>Select a random row with IBM DB2</p>\n\n<pre><code>SELECT column, RAND() as IDX \nFROM table \nORDER BY IDX FETCH FIRST 1 ROWS ONLY\n</code></pre>\n\n<p>Select a random record with Oracle:</p>\n\n<pre><code>SELECT column FROM\n( SELECT column FROM table\nORDER BY dbms_random.value )\nWHERE rownum = 1\n</code></pre>\n'}, {'answer_id': 19421, 'author': 'Ishmaeel', 'author_id': 227, 'author_profile': 'https://Stackoverflow.com/users/227', 'pm_score': 2, 'selected': False, 'text': '<p>Best way is putting a random value in a new column just for that purpose, and using something like this (pseude code + SQL):</p>\n\n<pre><code>randomNo = random()\nexecSql("SELECT TOP 1 * FROM MyTable WHERE MyTable.Randomness &gt; $randomNo")\n</code></pre>\n\n<p>This is the solution employed by the MediaWiki code. Of course, there is some bias against smaller values, but they found that it was sufficient to wrap the random value around to zero when no rows are fetched.</p>\n\n<p>newid() solution may require a full table scan so that each row can be assigned a new guid, which will be much less performant.</p>\n\n<p>rand() solution may not work at all (i.e. with MSSQL) because the function will be evaluated just once, and <em>every</em> row will be assigned the same "random" number.</p>\n'}, {'answer_id': 19422, 'author': 'Grey Panther', 'author_id': 1265, 'author_profile': 'https://Stackoverflow.com/users/1265', 'pm_score': 8, 'selected': False, 'text': '<p>Solutions like Jeremies:</p>\n\n<pre><code>SELECT * FROM table ORDER BY RAND() LIMIT 1\n</code></pre>\n\n<p>work, but they need a sequential scan of all the table (because the random value associated with each row needs to be calculated - so that the smallest one can be determined), which can be quite slow for even medium sized tables. My recommendation would be to use some kind of indexed numeric column (many tables have these as their primary keys), and then write something like:</p>\n\n<pre><code>SELECT * FROM table WHERE num_value &gt;= RAND() * \n    ( SELECT MAX (num_value ) FROM table ) \nORDER BY num_value LIMIT 1\n</code></pre>\n\n<p>This works in logarithmic time, regardless of the table size, if <code>num_value</code> is indexed. One caveat: this assumes that <code>num_value</code> is equally distributed in the range <code>0..MAX(num_value)</code>. If your dataset strongly deviates from this assumption, you will get skewed results (some rows will appear more often than others).</p>\n'}, {'answer_id': 19440, 'author': 'BlaM', 'author_id': 999, 'author_profile': 'https://Stackoverflow.com/users/999', 'pm_score': 0, 'selected': False, 'text': '<p>I have to agree with CD-MaN: Using "ORDER BY RAND()" will work nicely for small tables or when you do your SELECT only a few times.</p>\n\n<p>I also use the "num_value >= RAND() * ..." technique, and if I really want to have random results I have a special "random" column in the table that I update once a day or so. That single UPDATE run will take some time (especially because you\'ll have to have an index on that column), but it\'s much faster than creating random numbers for every row each time the select is run.</p>\n'}, {'answer_id': 182584, 'author': 'Santiago Cepas', 'author_id': 6547, 'author_profile': 'https://Stackoverflow.com/users/6547', 'pm_score': 2, 'selected': False, 'text': '<p>For SQL Server 2005 and 2008, if we want a random sample of individual rows (from <a href="http://msdn.microsoft.com/en-us/library/ms189108.aspx" rel="nofollow noreferrer">Books Online</a>):</p>\n\n<pre><code>SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 &gt;= CAST(CHECKSUM(NEWID(), SalesOrderID) &amp; 0x7fffffff AS float)\n/ CAST (0x7fffffff AS int)\n</code></pre>\n'}, {'answer_id': 855844, 'author': 'Sean Turner', 'author_id': 96894, 'author_profile': 'https://Stackoverflow.com/users/96894', 'pm_score': 0, 'selected': False, 'text': '<p>Be careful because TableSample doesn\'t actually return a random sample of rows. It directs your query to look at a random sample of the 8KB pages that make up your row. Then, your query is executed against the data contained in these pages. Because of how data may be grouped on these pages (insertion order, etc), this could lead to data that isn\'t actually a random sample. </p>\n\n<p>See: <a href="http://www.mssqltips.com/tip.asp?tip=1308" rel="nofollow noreferrer">http://www.mssqltips.com/tip.asp?tip=1308</a></p>\n\n<p>This MSDN page for TableSample includes an example of how to generate an actualy random sample of data.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms189108.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms189108.aspx</a>  </p>\n'}, {'answer_id': 922443, 'author': 'Rob Boek', 'author_id': 27179, 'author_profile': 'https://Stackoverflow.com/users/27179', 'pm_score': 4, 'selected': False, 'text': '<p>For SQL Server</p>\n\n<p>newid()/order by will work, but will be very expensive for large result sets because it has to generate an id for every row, and then sort them.</p>\n\n<p>TABLESAMPLE() is good from a performance standpoint, but you will get clumping of results (all rows on a page will be returned).</p>\n\n<p>For a better performing true random sample, the best way is to filter out rows randomly. I found the following code sample in the SQL Server Books Online article <em><a href="http://msdn.microsoft.com/en-us/library/ms189108.aspx" rel="noreferrer">Limiting Results Sets by Using TABLESAMPLE</a></em>:</p>\n\n<blockquote>\n  <p>If you really want a random sample of\n  individual rows, modify your query to\n  filter out rows randomly, instead of\n  using TABLESAMPLE. For example, the\n  following query uses the NEWID\n  function to return approximately one\n  percent of the rows of the\n  Sales.SalesOrderDetail table:</p>\n\n<pre><code>SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 &gt;= CAST(CHECKSUM(NEWID(),SalesOrderID) &amp; 0x7fffffff AS float)\n              / CAST (0x7fffffff AS int)\n</code></pre>\n  \n  <p>The SalesOrderID column is included in\n  the CHECKSUM expression so that\n  NEWID() evaluates once per row to\n  achieve sampling on a per-row basis.\n  The expression CAST(CHECKSUM(NEWID(),\n  SalesOrderID) &amp; 0x7fffffff AS float /\n  CAST (0x7fffffff AS int) evaluates to\n  a random float value between 0 and 1.</p>\n</blockquote>\n\n<p>When run against a table with 1,000,000 rows, here are my results:</p>\n\n<pre><code>SET STATISTICS TIME ON\nSET STATISTICS IO ON\n\n/* newid()\n   rows returned: 10000\n   logical reads: 3359\n   CPU time: 3312 ms\n   elapsed time = 3359 ms\n*/\nSELECT TOP 1 PERCENT Number\nFROM Numbers\nORDER BY newid()\n\n/* TABLESAMPLE\n   rows returned: 9269 (varies)\n   logical reads: 32\n   CPU time: 0 ms\n   elapsed time: 5 ms\n*/\nSELECT Number\nFROM Numbers\nTABLESAMPLE (1 PERCENT)\n\n/* Filter\n   rows returned: 9994 (varies)\n   logical reads: 3359\n   CPU time: 641 ms\n   elapsed time: 627 ms\n*/    \nSELECT Number\nFROM Numbers\nWHERE 0.01 &gt;= CAST(CHECKSUM(NEWID(), Number) &amp; 0x7fffffff AS float) \n              / CAST (0x7fffffff AS int)\n\nSET STATISTICS IO OFF\nSET STATISTICS TIME OFF\n</code></pre>\n\n<p>If you can get away with using TABLESAMPLE, it will give you the best performance. Otherwise use the newid()/filter method. newid()/order by should be last resort if you have a large result set.</p>\n'}, {'answer_id': 1074261, 'author': 'hegemon', 'author_id': 113083, 'author_profile': 'https://Stackoverflow.com/users/113083', 'pm_score': 1, 'selected': False, 'text': "<p>Most of the solutions here aim to avoid sorting, but they still need to make a sequential scan over a table.</p>\n\n<p>There is also a way to avoid the sequential scan by switching to index scan. If you know the index value of your random row you can get the result almost instantially. The problem is - how to guess an index value.</p>\n\n<p>The following solution works on PostgreSQL 8.4:</p>\n\n<pre><code>explain analyze select * from cms_refs where rec_id in \n  (select (random()*(select last_value from cms_refs_rec_id_seq))::bigint \n   from generate_series(1,10))\n  limit 1;\n</code></pre>\n\n<p>I above solution you guess 10 various random index values from range 0 .. [last value of id]. </p>\n\n<p>The number 10 is arbitrary - you may use 100 or 1000 as it (amazingly) doesn't have a big impact on the response time. </p>\n\n<p>There is also one problem - if you have sparse ids <strong>you might miss</strong>. The solution is to <strong>have a backup plan</strong> :) In this case an pure old order by random() query. When combined id looks like this:</p>\n\n<pre><code>explain analyze select * from cms_refs where rec_id in \n    (select (random()*(select last_value from cms_refs_rec_id_seq))::bigint \n     from generate_series(1,10))\n    union all (select * from cms_refs order by random() limit 1)\n    limit 1;\n</code></pre>\n\n<p>Not the <strong>union</strong> <strong>ALL</strong> clause. In this case if the first part returns any data the second one is NEVER executed!</p>\n"}, {'answer_id': 3286484, 'author': 'alphadogg', 'author_id': 59494, 'author_profile': 'https://Stackoverflow.com/users/59494', 'pm_score': 2, 'selected': False, 'text': '<p>In late, but got here via Google, so for the sake of posterity, I\'ll add an alternative solution. </p>\n\n<p>Another approach is to use TOP twice, with alternating orders. I don\'t know if it is "pure SQL", because it uses a variable in the TOP, but it works in SQL Server 2008. Here\'s an example I use against a table of dictionary words, if I want a random word.</p>\n\n<pre><code>SELECT TOP 1\n  word\nFROM (\n  SELECT TOP(@idx)\n    word \n  FROM\n    dbo.DictionaryAbridged WITH(NOLOCK)\n  ORDER BY\n    word DESC\n) AS D\nORDER BY\n  word ASC\n</code></pre>\n\n<p>Of course, @idx is some randomly-generated integer that ranges from 1 to COUNT(*) on the target table, inclusively. If your column is indexed, you\'ll benefit from it too. Another advantage is that you can use it in a function, since NEWID() is disallowed.</p>\n\n<p>Lastly, the above query runs in about 1/10 of the exec time of a NEWID()-type of query on the same table. YYMV.</p>\n'}, {'answer_id': 4497240, 'author': 'Neel', 'author_id': 549625, 'author_profile': 'https://Stackoverflow.com/users/549625', 'pm_score': 5, 'selected': False, 'text': '<pre><code>ORDER BY NEWID()\n</code></pre>\n\n<p>takes <code>7.4 milliseconds</code></p>\n\n<pre><code>WHERE num_value &gt;= RAND() * (SELECT MAX(num_value) FROM table)\n</code></pre>\n\n<p>takes <code>0.0065 milliseconds</code>!</p>\n\n<p>I will definitely go with latter method.</p>\n'}, {'answer_id': 4638036, 'author': 'ldrut', 'author_id': 568604, 'author_profile': 'https://Stackoverflow.com/users/568604', 'pm_score': 2, 'selected': False, 'text': '<p>If possible, use stored statements to avoid the inefficiency of both indexes on RND() and creating a record number field.</p>\n\n<pre>\nPREPARE RandomRecord FROM "SELECT * FROM table LIMIT ?,1";\nSET @n=FLOOR(RAND()*(SELECT COUNT(*) FROM table));\nEXECUTE RandomRecord USING @n;\n</pre>\n'}, {'answer_id': 4856912, 'author': 'DAVID ', 'author_id': 597598, 'author_profile': 'https://Stackoverflow.com/users/597598', 'pm_score': 0, 'selected': False, 'text': '<p>It seems that many of the ideas listed still use ordering</p>\n\n<p>However, if you use a temporary table, you are able to assign a random index (like many of the solutions have suggested), and then grab the first one that is greater than an arbitrary number between 0 and 1.</p>\n\n<p>For example (for DB2):</p>\n\n<pre><code>WITH TEMP AS (\nSELECT COMLUMN, RAND() AS IDX FROM TABLE)\nSELECT COLUMN FROM TABLE WHERE IDX &gt; .5\nFETCH FIRST 1 ROW ONLY\n</code></pre>\n'}, {'answer_id': 6729183, 'author': 'Jai - gotaninterviewcall', 'author_id': 849458, 'author_profile': 'https://Stackoverflow.com/users/849458', 'pm_score': 1, 'selected': False, 'text': '<p>You may also try using <code>new id()</code> function.</p>\n\n<p>Just write a your query and use order by <code>new id()</code> function. It quite random.</p>\n'}, {'answer_id': 12852040, 'author': 'karmakaze', 'author_id': 720030, 'author_profile': 'https://Stackoverflow.com/users/720030', 'pm_score': 2, 'selected': False, 'text': "<p>As pointed out in @BillKarwin's comment on @cnu's answer...</p>\n\n<p>When combining with a LIMIT, I've found that it performs much better (at least with PostgreSQL 9.1) to JOIN with a random ordering rather than to directly order the actual rows: e.g.\n<code><pre>\nSELECT * FROM tbl_post AS t\nJOIN ...\nJOIN ( SELECT id, CAST(-2147483648 * RANDOM() AS integer) AS rand\n       FROM tbl_post\n       WHERE create_time >= 1349928000\n     ) r ON r.id = t.id\nWHERE create_time >= 1349928000 AND ...\nORDER BY r.rand\nLIMIT 100\n</pre></code></p>\n\n<p>Just make sure that the 'r' generates a 'rand' value for every possible key value in the complex query which is joined with it but still limit the number of rows of 'r' where possible.</p>\n\n<p>The CAST as Integer is especially helpful for PostgreSQL 9.2 which has specific sort optimisation for integer and single precision floating types.</p>\n"}, {'answer_id': 17768021, 'author': 'Sophy', 'author_id': 833394, 'author_profile': 'https://Stackoverflow.com/users/833394', 'pm_score': 2, 'selected': False, 'text': '<p>For MySQL to get random record</p>\n\n<pre><code> SELECT name\n  FROM random AS r1 JOIN\n       (SELECT (RAND() *\n                     (SELECT MAX(id)\n                        FROM random)) AS id)\n        AS r2\n WHERE r1.id &gt;= r2.id\n ORDER BY r1.id ASC\n LIMIT 1\n</code></pre>\n\n<p>More detail <a href="http://jan.kneschke.de/projects/mysql/order-by-rand/" rel="nofollow">http://jan.kneschke.de/projects/mysql/order-by-rand/</a></p>\n'}, {'answer_id': 20661166, 'author': 'Mmmh mmh', 'author_id': 1582182, 'author_profile': 'https://Stackoverflow.com/users/1582182', 'pm_score': 0, 'selected': False, 'text': '<p>A simple and efficient way from <a href="http://akinas.com/pages/en/blog/mysql_random_row/" rel="nofollow">http://akinas.com/pages/en/blog/mysql_random_row/</a></p>\n\n<pre><code>SET @i = (SELECT FLOOR(RAND() * COUNT(*)) FROM table); PREPARE get_stmt FROM \'SELECT * FROM table LIMIT ?, 1\'; EXECUTE get_stmt USING @i;\n</code></pre>\n'}, {'answer_id': 25021581, 'author': 'klyd', 'author_id': 471810, 'author_profile': 'https://Stackoverflow.com/users/471810', 'pm_score': 1, 'selected': False, 'text': "<p>Didn't quite see this variation in the answers yet. I had an additional constraint where I needed, given an initial seed, to select the same set of rows each time.</p>\n\n<p>For MS SQL:</p>\n\n<p>Minimum example:</p>\n\n<pre><code>select top 10 percent *\nfrom table_name\norder by rand(checksum(*))\n</code></pre>\n\n<p>Normalized execution time: 1.00</p>\n\n<p>NewId() example:</p>\n\n<pre><code>select top 10 percent *\nfrom table_name\norder by newid()\n</code></pre>\n\n<p>Normalized execution time: 1.02</p>\n\n<p><code>NewId()</code> is insignificantly slower than <code>rand(checksum(*))</code>, so you may not want to use it against large record sets.</p>\n\n<p>Selection with Initial Seed:</p>\n\n<pre><code>declare @seed int\nset @seed = Year(getdate()) * month(getdate()) /* any other initial seed here */\n\nselect top 10 percent *\nfrom table_name\norder by rand(checksum(*) % seed) /* any other math function here */\n</code></pre>\n\n<p>If you need to select the same set given a seed, this seems to work.</p>\n"}, {'answer_id': 25642622, 'author': 'sev3ryn', 'author_id': 1167502, 'author_profile': 'https://Stackoverflow.com/users/1167502', 'pm_score': 0, 'selected': False, 'text': '<p>There is better solution for Oracle instead of using dbms_random.value, while it requires full scan to order rows by dbms_random.value and it is quite slow for large tables.</p>\n\n<p>Use this instead:</p>\n\n<pre><code>SELECT *\nFROM employee sample(1)\nWHERE rownum=1\n</code></pre>\n'}, {'answer_id': 29676451, 'author': 'David Knight', 'author_id': 161332, 'author_profile': 'https://Stackoverflow.com/users/161332', 'pm_score': 1, 'selected': False, 'text': '<p>In MSSQL (tested on 11.0.5569) using </p>\n\n<pre><code>SELECT TOP 100 * FROM employee ORDER BY CRYPT_GEN_RANDOM(10)\n</code></pre>\n\n<p>is significantly faster than</p>\n\n<pre><code>SELECT TOP 100 * FROM employee ORDER BY NEWID()\n</code></pre>\n'}, {'answer_id': 40839843, 'author': 'Luigi04', 'author_id': 1964666, 'author_profile': 'https://Stackoverflow.com/users/1964666', 'pm_score': 1, 'selected': False, 'text': '<p>For Firebird:</p>\n\n<pre><code>Select FIRST 1 column from table ORDER BY RAND()\n</code></pre>\n'}, {'answer_id': 42723045, 'author': 'forsberg', 'author_id': 1624397, 'author_profile': 'https://Stackoverflow.com/users/1624397', 'pm_score': 2, 'selected': False, 'text': '<p>Insted of <a href="http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/" rel="nofollow noreferrer">using RAND(), as it is not encouraged</a>, you may simply get max ID (=Max):</p>\n\n<pre><code>SELECT MAX(ID) FROM TABLE;\n</code></pre>\n\n<p>get a random between 1..Max (=My_Generated_Random)</p>\n\n<pre><code>My_Generated_Random = rand_in_your_programming_lang_function(1..Max);\n</code></pre>\n\n<p>and then run this SQL:</p>\n\n<pre><code>SELECT ID FROM TABLE WHERE ID &gt;= My_Generated_Random ORDER BY ID LIMIT 1\n</code></pre>\n\n<p>Note that it will check for any rows which Ids are EQUAL or HIGHER than chosen value.\nIt\'s also possible to hunt for the row down in the table, and get an equal or lower ID than the My_Generated_Random, then modify the query like this:</p>\n\n<pre><code>SELECT ID FROM TABLE WHERE ID &lt;= My_Generated_Random ORDER BY ID DESC LIMIT 1\n</code></pre>\n'}, {'answer_id': 43461850, 'author': 'Chris Arbogast', 'author_id': 5361251, 'author_profile': 'https://Stackoverflow.com/users/5361251', 'pm_score': 1, 'selected': False, 'text': '<p>In SQL Server you can combine TABLESAMPLE with NEWID() to get pretty good randomness and still have speed.  This is especially useful if you really only want 1, or a small number, of rows.</p>\n\n<pre><code>SELECT TOP 1 * FROM [table] \nTABLESAMPLE (500 ROWS) \nORDER BY NEWID()\n</code></pre>\n'}, {'answer_id': 49542866, 'author': 'gbjbaanb', 'author_id': 13744, 'author_profile': 'https://Stackoverflow.com/users/13744', 'pm_score': 2, 'selected': False, 'text': '<p>With SQL Server 2012+ you can use the <a href="https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx" rel="nofollow noreferrer">OFFSET FETCH query</a> to do this for a single random row</p>\n\n<pre><code>select  * from MyTable ORDER BY id OFFSET n ROW FETCH NEXT 1 ROWS ONLY\n</code></pre>\n\n<p>where id is an identity column, and n is the row you want - calculated as a random number between 0 and count()-1 of the table (offset 0 is the first row after all)</p>\n\n<p>This works with holes in the table data, as long as you have an index to work with for the ORDER BY clause. Its also very good for the randomness - as you work that out yourself to pass in but the niggles in other methods are not present. In addition the performance is pretty good, on a smaller dataset it holds up well, though I\'ve not tried serious performance tests against several million rows.</p>\n'}, {'answer_id': 50562274, 'author': 'Endri', 'author_id': 4699575, 'author_profile': 'https://Stackoverflow.com/users/4699575', 'pm_score': 0, 'selected': False, 'text': "<p>For SQL Server 2005 and above, extending @GreyPanther's answer for the cases when <code>num_value</code> has not continuous values. This works too for cases when we have not evenly distributed datasets and when <code>num_value</code> is not a number but a unique identifier.</p>\n\n<pre><code>WITH CTE_Table (SelRow, num_value) \nAS \n(\n    SELECT ROW_NUMBER() OVER(ORDER BY ID) AS SelRow, num_value FROM table\n) \n\nSELECT * FROM table Where num_value = ( \n    SELECT TOP 1 num_value FROM CTE_Table  WHERE SelRow &gt;= RAND() * (SELECT MAX(SelRow) FROM CTE_Table)\n)\n</code></pre>\n"}, {'answer_id': 51205622, 'author': 'Nitin', 'author_id': 2669383, 'author_profile': 'https://Stackoverflow.com/users/2669383', 'pm_score': 1, 'selected': False, 'text': '<p>Random function from the sql could help. Also if you would like to limit to just one row, just add that in the end.</p>\n\n<pre><code>SELECT column FROM table\nORDER BY RAND()\nLIMIT 1\n</code></pre>\n'}, {'answer_id': 64543769, 'author': 'Kuks', 'author_id': 14219455, 'author_profile': 'https://Stackoverflow.com/users/14219455', 'pm_score': 0, 'selected': False, 'text': '<pre><code>select r.id, r.name from table AS r\nINNER JOIN(select CEIL(RAND() * (select MAX(id) from table)) as id) as r1\nON r.id &gt;= r1.id ORDER BY r.id ASC LIMIT 1\n</code></pre>\n<p>This will require a lesser computation time</p>\n'}, {'answer_id': 66179699, 'author': 'user2864740', 'author_id': 2864740, 'author_profile': 'https://Stackoverflow.com/users/2864740', 'pm_score': 2, 'selected': False, 'text': '<p><em><strong>For SQL Server and needing &quot;a single random row&quot;..</strong></em></p>\n<p>If not needing a true sampling, generate a random value <code>[0, max_rows)</code> and use the <a href="https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql" rel="nofollow noreferrer">ORDER BY..OFFSET..FETCH from SQL Server 2012+</a>.</p>\n<p>This is <em>very fast</em> if the <code>COUNT</code> and <code>ORDER BY</code> are over appropriate indexes - such that the data is \'already sorted\' along the query lines. If these operations are covered it\'s a quick request and does not suffer from the <em>horrid scalability</em> of using <code>ORDER BY NEWID()</code> or similar. Obviously, this approach won\'t scale well on a non-indexed HEAP table.</p>\n<pre><code>declare @rows int\nselect @rows = count(1) from t\n\n-- Other issues if row counts in the bigint range..\n-- This is also not \'true random\', although such is likely not required.\ndeclare @skip int = convert(int, @rows * rand())\n\nselect t.*\nfrom t\norder by t.id -- Make sure this is clustered PK or IX/UCL axis!\noffset (@skip) rows\nfetch first 1 row only\n</code></pre>\n<p>Make sure that the appropriate transaction isolation levels are used and/or account for 0 results.</p>\n<hr />\n<p><em><strong>For SQL Server and needing a &quot;general row sample&quot; approach..</strong></em></p>\n<p>Note: This is an adaptation of the answer as found <a href="https://stackoverflow.com/a/66179188/2864740">on a SQL Server specific question about fetching a sample of rows</a>. <em>It has been tailored for context.</em></p>\n<p>While a general sampling approach should be used with caution here, it\'s still potentially useful information in context of other answers (and the repetitious suggestions of non-scaling and/or questionable implementations). Such a sampling approach is less efficient than the first code shown and is error-prone if the goal is to find a &quot;single random row&quot;.</p>\n<hr />\n<p>Here is <em>an updated and improved form of <strong>sampling a percentage of rows</strong></em>. It is based on the same concept of some other answers that use CHECKSUM / BINARY_CHECKSUM and modulus.</p>\n<ul>\n<li><p><strong>It is <em>relatively fast over huge data sets</em></strong> and <strong>can be efficiently used in/with derived queries</strong>. Millions of pre-filtered rows can be sampled in seconds <em>with no tempdb usage</em> and, if aligned with the rest of the query, the overhead is often minimal.</p>\n</li>\n<li><p><strong><em>Does not suffer from <code>CHECKSUM(*)</code> / <code>BINARY_CHECKSUM(*)</code> issues with runs of data.</em> When using the <code>CHECKSUM(*)</code> approach, the rows can be selected in &quot;chunks&quot; and not &quot;random&quot; at all! This is because <em>CHECKSUM prefers speed over distribution</em>.</strong></p>\n</li>\n<li><p><strong>Results in a <em>stable/repeatable</em> row selection</strong> and can be trivially changed to produce different rows on subsequent query executions. Approaches that use <code>NEWID()</code> can never be stable/repeatable.</p>\n</li>\n<li><p><strong>Does not use <code>ORDER BY NEWID()</code> <em>of the entire input set</em>, as <em>ordering can become a significant bottleneck</em> with large input sets.</strong> Avoiding <em>unnecessary</em> sorting also <em>reduces memory and tempdb usage</em>.</p>\n</li>\n<li><p><strong>Does not use <code>TABLESAMPLE</code> and thus works with a <code>WHERE</code> pre-filter.</strong></p>\n</li>\n</ul>\n<p>Here is the gist. <a href="https://stackoverflow.com/a/66179188/2864740">See this answer for additional details and notes</a>.</p>\n<p>Naïve try:</p>\n<pre><code>declare @sample_percent decimal(7, 4)\n-- Looking at this value should be an indicator of why a\n-- general sampling approach can be error-prone to select 1 row.\nselect @sample_percent = 100.0 / count(1) from t\n\n-- BAD!\n-- When choosing appropriate sample percent of &quot;approximately 1 row&quot;\n-- it is very reasonable to expect 0 rows, which definitely fails the ask!\n-- If choosing a larger sample size the distribution is heavily skewed forward,\n-- and is very much NOT \'true random\'.\nselect top 1\n    t.*\nfrom t\nwhere 1=1\n    and ( -- sample\n        @sample_percent = 100\n        or abs(\n            convert(bigint, hashbytes(\'SHA1\', convert(varbinary(32), t.rowguid)))\n        ) % (1000 * 100) &lt; (1000 * @sample_percent)\n    )\n</code></pre>\n<p>This can be largely remedied by a hybrid query, by mixing sampling and <code>ORDER BY</code> selection from the <em>much smaller sample set</em>. This limits the sorting operation to the sample size, not the size of the original table.</p>\n<pre><code>-- Sample &quot;approximately 1000 rows&quot; from the table,\n-- dealing with some edge-cases.\ndeclare @rows int\nselect @rows = count(1) from t\n\ndeclare @sample_size int = 1000\ndeclare @sample_percent decimal(7, 4) = case\n    when @rows &lt;= 1000 then 100                              -- not enough rows\n    when (100.0 * @sample_size / @rows) &lt; 0.0001 then 0.0001 -- min sample percent\n    else 100.0 * @sample_size / @rows                        -- everything else\n    end\n\n-- There is a statistical &quot;guarantee&quot; of having sampled a limited-yet-non-zero number of rows.\n-- The limited rows are then sorted randomly before the first is selected.\nselect top 1\n    t.*\nfrom t\nwhere 1=1\n    and ( -- sample\n        @sample_percent = 100\n        or abs(\n            convert(bigint, hashbytes(\'SHA1\', convert(varbinary(32), t.rowguid)))\n        ) % (1000 * 100) &lt; (1000 * @sample_percent)\n    )\n-- ONLY the sampled rows are ordered, which improves scalability.\norder by newid()\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/19412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/473/']