Search code examples
ruby-on-railsdatabasepostgresqlsqldatatypesruby-on-rails-7

How to use Postgresql's "real" (float4) type in Rails 7.0, instead of the "double precision"?


I've got a Rails 7.0 app connected to a Postgres Database.

I've got tables with several millions of rows, and each row storing more than 10 columns as float types.

The default way of storing numbers with decimals in Rails is the float type, which corresponds to the float8 type in Postgres (also known as double precision), meaning each value stored as this type is 8bytes of data.

I could save a lot of space by telling Rails, to tell Postgres, to use float4 (real) instead of float8.

Basically cutting in half the size of the biggest table of my database.

The only thing is that i really don't know how to and i don't seem to find any clue about it.

Has someone ever tried to do this ?

Also if that's the case, i take any recommendation regarding the migration itself as i need to switch the existing entries to float4 as well.

Best!


Solution

  • Found the answer by messing around with migrations.

    It's as simple as adding a 4 to the float type like so:

      def change
        add_column :my_table, :my_column, :float4
      end
    

    This results in a 'real' column when checking through psql.