ruk·si

🛤️ Ruby on Rails
PostgreSQL Text Types

Updated at 2015-09-07 00:10

Always use text. In PostgreSQL, there is no performance difference between text or string. They translate to the database as text and varchar, both can be limited by constraints and allow up to 1 GB of data. But using text makes multiple like array operations work without casting to varchar.

There is also the citext (case-insensitive text) data type. It's basically text but all comparisons are done with implicit LOWER(). Emails is an example of a good citext field as it is case-insensitive in use.

rails g migration EnableCitext
class EnableCitext < ActiveRecord::Migration
  def change
    enable_extension 'citext'
  end
end
rails g migration AddUsernameToUser
class AddUsernameToUser < ActiveRecord::Migration
  def change
    add_column :users, :email, :citext
    add_index :users, :email, unique: true
  end
end