SQL statements that randomly extract a record from the database

Source: Internet
Author: User

We often want to randomly select data from a data table, such as randomly generating test papers.

The newid () method of SQL Server can easily achieve this goal.

 

The newid () method returns a guid, such as the EE95A489-B721-4E8A-8171-3CA8CB6AD9E4

In the Select Table, add a column newid.

SQL statement: Select *, newid () from table

In this way, each record will have a random guid value. We can sort the guid in a descending order to achieve the effect of disorder.

SQL statement: Select *, newid () as random from Table order by random

 

If we want to randomly retrieve 10 pieces of data, we only need to add the top 10:

SQL statement: Select top 10 *, newid () as random from Table order by random

 

Filter unique records

Select * From tablename order by newid ()

 

This method applies only to SQL Server.

 

Select Top 4 * from Table order by RND (ID)

 

This sentence applies to access. For more information, see

 

Select * From table_name order by rand () [limit num];

MySQL random query statement.

 

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/fableking/archive/2009/04/03/4046635.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.