Kavita Jadhav
2 min readDec 3, 2020

--

Uniq vs. Uniq (Rails ActiveRecord 3.1)

While using ActiveRecord for data operations it’s very important to write optimal queries to avoid multiple SQL queries or loading unused data in memory which may impact the performance of the application. Let's explore one of the such queries.

https://www.wikitechy.com/tutorials/sql/sql-distinct

Scenario - You have a user table with having column email and you want to list all uniq email addresses from the table. you can achieve this by:

  1. Fetch email ids from the database and take uniq email id with the command below:

2. Fetch uniq email ids from the database with the command below:

Look at the SQL statement generated by each query.

In the first command, we are reading all email addresses in the memory. Query execution time is 2.2ms. But to get all uniq email addresses we perform an array uniq command in memory. So actual execution time is (time taken by SQL command + time taken by array uniq command)

In the second statement, we are reading all distinct email addresses from the database itself. Query execution time is 3.1ms. Here we are not performing any in-memory operations as well.

Here though we are using uniq method to get uniq email addresses, using it at the right place makes a difference!

Happy coding!!!

--

--