mercredi 25 avril 2018

How to select the first record with a random not null value for a specific column

I was involved with the following problem and finally got the answer. Wanted to share with anyone who may need that.

I needed to select the first record with a random but not null value for id column from my table. The values of id column were not subsequent so I needed to select a random id that existed.

For example for the following table:

CREATE TABLE randomValue
(id int)

INSERT INTO randomValue 
VALUES (generate_series(1, 10))

SELECT * FROM randomValue

DELETE FROM randomValue WHERE id IN 
(SELECT id FROM randomValue WHERE id IN (2, 5, 7))

I needed a query that selected a random record with an existing id value.




Aucun commentaire:

Enregistrer un commentaire