Ross
Ross

Reputation: 947

Rails 4 how to find the maximum length of a string column

To find the maximum length of string column in SQL is:

select max(length(<column>)) from <table>

Can anyone show how to do the same in Rails 4 activerecord or even squeel?

Upvotes: 6

Views: 5363

Answers (2)

Andrey Deineko
Andrey Deineko

Reputation: 52367

Something like this?

Model.pluck(:column).max_by(&:length)

#=> will return the longest string

Another option would be to just execute a query in SQL:

Model.connection.execute("SELECT MAX(LENGTH(column)) FROM my_table")

Upvotes: 6

radhika
radhika

Reputation: 534

You can use Model.pluck("max(length(column))"), which won't load everything into memory.

Upvotes: 7

Related Questions