Search code examples
sqlruby-on-railsdatabasepostgresqldatabase-optimization

Is condensing the number of columns in a database beneficial?


Say you want to record three numbers for every Movie record...let's say, :release_year, :box_office, and :budget.

Conventionally, using Rails, you would just add those three attributes to the Movie model and just call @movie.release_year, @movie.box_office, and @movie.budget.

Would it save any database space or provide any other benefits to condense all three numbers into one umbrella column?

So when adding the three numbers, it would go something like:

def update
  ...
  @movie.umbrella = params[:movie_release_year] 
    + "," + params[:movie_box_office] + "," + params[:movie_budget]
end

So the final @movie.umbrella value would be along the lines of "2015,617293,748273".

And then in the controller, to access the three values, it would be something like

@umbrella_array = @movie.umbrella.strip.split(',').map(&:strip)
@release_year = @umbrella_array.first
@box_office = @umbrella_array.second
@budget = @umbrella_array.third

This way, it would be the same amount of data (actually a little more, with the extra commas) but stored only in one column. Would this be better in any way than three columns?


Solution

  • There is no benefit in squeezing such attributes in a single column. In fact, following that path will increase the complexity of your code and will limit your capabilities.

    Here's some of the possible issues you'll face:

    1. You will not be able to add indexes to increase the performance of lookup of records with a specific attribute value or sort the filtering
    2. You will not be able to query a specific attribute value
    3. You will not be able to sort by a specific column value
    4. The values will be stored and represented as Strings, rather than Integers

    ... and I can continue. There are no advantages, only disadvantages.