Monther
Monther

Reputation: 31

Selecting a random record in SQLite from records that have a specific value to a column

I am making an application in Android, and I am using SQLite database.

Is it possible for me to select a random record in a table from the records that have a specific value to one of the columns?

Let’s say I have a table called T, which has a set of columns: a, b, c. Can I select a random record from this table, but ONLY from the records with no null value for the “c” column?

Upvotes: 1

Views: 50

Answers (2)

MikeT
MikeT

Reputation: 57083

Yes it is possible, you could use something like :-

SELECT * FROM t WHERE c IS NOT NULL ORDER BY random() LIMIT 1;
  • This utilises the random function to ORDER the result set using the ORDER BY clause and then selects just 1 row via the LIMIT clause.

P.S. a, b and c are generally called columns rather than attributes

Upvotes: 0

Patrick Vollebregt
Patrick Vollebregt

Reputation: 41

Not sure if you mean columns when you say attributes. If so, do you mean something like this:

SELECT * FROM T WHERE c IS NOT NULL ORDER BY RANDOM() LIMIT 1;

Upvotes: 2

Related Questions