DEV Community

Guilherme Yamakawa de Oliveira
Guilherme Yamakawa de Oliveira

Posted on

pluck vs. select

pluck

In Rails, we have pluck, which returns an array with the values of the attributes you selected.

Doctor.pluck(:id)
   (0.9ms)  SELECT "doctors"."id" FROM "doctors"
=> [1, 3, 7, 8, 9, 5]
Enter fullscreen mode Exit fullscreen mode

If you pass more than one attribute, the pluck returns an array of multiple attributes.

Doctor.pluck(:id, :updated_at)
   (0.5ms)  SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"
=> [[1, Wed, 23 Jan 2019 11:44:27.924159000 EST -05:00],
 [3, Tue, 29 Jan 2019 15:47:30.056920000 EST -05:00],
 [7, Thu, 28 May 2020 19:30:29.238601000 EDT -04:00],
 [8, Thu, 28 May 2020 19:30:29.251257000 EDT -04:00],
 [9, Sat, 26 Jun 2021 19:56:41.536687000 EDT -04:00],
 [5, Tue, 28 Jun 2022 16:49:45.091360000 EDT -04:00]]
Enter fullscreen mode Exit fullscreen mode

The query is precise to get only the attributes you are asking for.

SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"
Enter fullscreen mode Exit fullscreen mode

select

The select make the same query.

Doctor.select(:id, :updated_at)
  Doctor Load (0.3ms)  SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"

Doctor.pluck(:id, :updated_at)
   (0.3ms)  SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"
Enter fullscreen mode Exit fullscreen mode
Doctor.select(:id, :updated_at)
  Doctor Load (0.6ms)  SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"
=>[#<Doctor:0x0000000111a2ec40 id: 1, updated_at: Wed, 23 Jan 2019 11:44:27.924159000 EST -05:00>,
 #<Doctor:0x0000000111a2eab0 id: 3, updated_at: Tue, 29 Jan 2019 15:47:30.056920000 EST -05:00>,
 #<Doctor:0x0000000111a2e998 id: 7, updated_at: Thu, 28 May 2020 19:30:29.238601000 EDT -04:00>,
 #<Doctor:0x0000000111a2e858 id: 8, updated_at: Thu, 28 May 2020 19:30:29.251257000 EDT -04:00>,
 #<Doctor:0x0000000111a2e4c0 id: 9, updated_at: Sat, 26 Jun 2021 19:56:41.536687000 EDT -04:00>,
 #<Doctor:0x0000000111a2e218 id: 5, updated_at: Tue, 28 Jun 2022 16:49:45.091360000 EDT -04:00>]
Enter fullscreen mode Exit fullscreen mode

But select returns an ActiveRecord_Relation with objects from the model where it was called.

Doctor.select(:id, :updated_at).class
=> Doctor::ActiveRecord_Relation
Enter fullscreen mode Exit fullscreen mode

that's all folks :)

Top comments (0)