> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/check-if-any-records-have-a-null-value.md).

# Check If Any Records Have A Null Value

I like to add missing `not null` constraints where appropriate when they are missing. The [`change_column_null` method](/til/programmy/rails/change-the-nullability-of-a-column.md) is the Rails DSL way of doing this.

But first, you need to be sure that all databases this will be running against don't have any `null` values already present for any records. If there are `null` values present, then the migration will fail.

One way of doing that check is with some SQL and the [`select_values`](https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-select_values) method.

```ruby
ActiveRecord::Base
  .connection
  .select_values("select id from projects where user_id is null")
  .any?
```

This bit of SQL asks for the `id`s of any records in the `projects` table where a specific column (`user_id`) is explicitly `null`.

If this returns `false`, then you are good to migrate. If this returns `true`, then you'll have to do some data massaging first.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/rails/check-if-any-records-have-a-null-value.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
