[ActiveRecord] select Vs pluck

BharteeTechRubyOnRails
2 min readSep 13, 2023

--

select:

The select method is used to specify which columns of a database table you want to retrieve in a query.

It allows you to create a custom query and fetch a collection of ActiveRecord objects, each representing a row in the database table.

select returns ActiveRecord::Relation, SQL is issued using the to_a method, etc. and an array of ActiveRecord objects can be obtained.

retrieve all the users from the DB with just the ‘name’, and ‘email’ column and return a relation.

In this example, users is an array of User objects with only the name and email attributes loaded.

I recommend using select it for models with large text fields or lots of fields you don't need to load.

 User.select(:name, :email)
User Load (0.3ms) SELECT "users"."name", "users"."email" FROM "users"
=>
[#<User:0x000056539fa5f818 id: nil, name: "bhartee", email: "bhartee@gmail.com">,
#<User:0x000056539fa5f750 id: nil, name: "User 1", email: "user1@example.com">,
#<User:0x000056539fa5f688 id: nil, name: "User 2", email: "user2@example.com">]

pluck:

The pluck method is used to retrieve specific columns from a database table without loading entire ActiveRecord objects. It returns an array of values from the specified columns.

The result of a pluck query is an array of values, not ActiveRecord objects. It can be useful when you only need certain columns and don't want to incur the overhead of creating full ActiveRecord objects.

retrieve just names from, usersput them in an array as strings (in this case), and give it to you.

In this example, names is an array of strings, each representing the 'name' column value of a user.

User.pluck(:name)
User Pluck (0.1ms) SELECT "users"."name" FROM "users"
=> ["bhartee", "User 1", "User 2"]

In summary,

  • select is used to fetch a collection of ActiveRecord objects with specified columns and is suitable when you need to work with the data as ActiveRecord instances.
  • pluck is used to retrieve specific columns as an array of values, which can be more efficient when you only need certain attributes and don't require full ActiveRecord objects.

Happy Coding! 🚀 Please follow for more updates BharteeTechRoR

--

--