Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Ross Avatar asked Apr 01 '15 09:04

Ross


2 Answers

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

like image 79
radhika Avatar answered Nov 01 '22 08:11

radhika


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")
like image 38
Andrey Deineko Avatar answered Nov 01 '22 08:11

Andrey Deineko