0

I have a query that takes all rows out of a table, and joins with another table I am updating. The other table has some items that have been checked (these get a value), and some which are not yet checked. I am trying to implement a way to update all records, but make sure any NULLs get sorted as quickly as possible. I have the following query:

SELECT * FROM posts
LEFT JOIN post_stats
ON post_stats.post_id = posts.id
ORDER BY RANDOM() NULLS FIRST LIMIT 10

However, this is ordering everything randomly. Is there a way to order everything randomly, but any NULLs get shown first?

1
  • 1
    random() will never return a NULL value, so ORDER BY RANDOM() NULLS FIRST doesn't really make sense. Commented Jan 12, 2017 at 11:10

1 Answer 1

1

Note that you don't even specify which column can contain NULLs in your query. This is an indicator that something is going wrong.

The following query (replace with what you need) should do what you want.

SELECT *
FROM posts
LEFT JOIN post_stats ON post_stats.post_id = posts.id
ORDER BY <YOUR_COLUMN> IS NOT NULL, RANDOM()
LIMIT 10;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.