6

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?

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
Ross
  • 539
  • 1
  • 4
  • 14
  • For the actual length limit on a string field (rather than the longest value), check http://stackoverflow.com/questions/1257658/rails-is-there-a-way-to-check-the-fields-datatype – mwfearnley Sep 28 '16 at 16:22

2 Answers2

7

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

radhika
  • 534
  • 2
  • 7
  • 15
6

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")
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • 1
    Thanks Andrey. However, I was seeking to hand the query off to the sql server to avoid pulling in all of the rows which I think your suggestion will do unless I'm mistaken. – Ross Apr 02 '15 at 10:32
  • 1
    @Ross you are right - accepted solution is more(most) efficient one. – Andrey Deineko Dec 04 '15 at 13:28