SQL undercover
Kevin Gallo
Posted on March 16, 2022
Using Active Record Over SQL
Trying to read and write to a database can be a hassle. SQL can quickly seem overwhelming and complicated as it takes more effort to write simple queries. As developers we are always looking for a way to make code more readable but at the same time more efficient. Come active record an ORM (Object Relational Mapping) which allows a developer to manage their database without having to write raw SQL code. This allows for their code to be abstracted that can still create, read, update, and delete/destroy (CRUD) from their database.
Abstraction Within Active Record
Active record comes with inbuilt methods that allows the developer to query the database in a simple easy to read way. A few methods that come with Active Record are find, destroy, where, update, order, include, create, and etc. These methods convert into SQL code that allows them to query the database. The use of these methods allows the code to be more readable without losing the power that SQL can bring.
In the picture above we have two lines that do the exact same thing. The first line uses active record to query the database to find the matching id put into the find method as a parameter. While the second line does the same thing but instead uses raw SQL code to find the matching id passed through. In both cases will return an instance of that id.
SQL can becomes a hassle to write as queries get more and more complicated. Active record is allowing for a more simple way to do what SQL can do so that the developer can focus on harder task.
SQL Upsides
Although we have seen how active record can be the best choice to query through a database it does not mean SQL in complete obsolete. There are task that active record cannot do faster than raw SQL can do. A major example of this is bulk inserting. Without the help of activerecord-import gem there is currently no way of bulk inserting records into a database. This is where raw SQL will come into play. There are times where raw SQL will be the most effective and efficient way to query a database. In certain cases it can be seen that raw SQL can be around 20 times faster than any other method with the price of having to write long SQL code.
Active record is gift from the coding gods that allows developers to truly bring out their true nature, lazy problem solvers. In most cases active record can get the job done but as projects scale up to large amounts writing raw SQL might be the way to go.
Sources
https://guides.rubyonrails.org/active_record_querying.html
https://blog1.westagilelabs.com/active-record-or-raw-sql-edd55766df49
https://guides.rubyonrails.org/active_record_basics.html
Posted on March 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.