0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【MySQL】RAND()関数でランダムにデータを取得する方法(SQLクエリ)

Posted at

概要

  • SQLでランダムにレコードを取得する方法を記載ます。
    • ①ランダムにソートして取得するクエリ
    • ②ランダム10件だけソートして取得するクエリ

①ランダムにソートして取得するクエリ

  • 以下のSQLでテーブルsample_tableからランダムにソートすることができます。
SELECT * 
FROM sample_table
ORDER BY RAND();

②ランダム10件だけソートして取得するクエリ

  • 以下のSQLでは、テーブルsample_tableからレコードをランダムに並び替え、結果を10行に制限して取得します。
SELECT *
FROM sample_table
ORDER BY RAND()
LIMIT 10;
  • もしくは以下でも可能です。
SELECT *
FROM sample_table
ORDER BY (SELECT RAND())
LIMIT 10;

MySQLではRANDOM()関数だとエラーになる

  • ちなみに、MySQLではRANDOM()関数を使うと以下のエラーになりました。
SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '() LIMIT 10' at line 3 Error position: line: 2
#1064 - SQL構文エラーです。バージョンに対応するマニュアルを参照して正しい構文を確認してください。 : '()
LIMIT 10' 付近 3 行目
  • RANDOM()関数は、PostgreSQLなどの一部のデータベースシステムで使用される関数ですね。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?