How to Use Plain SQL in Rails

Shaqqour
2 min readOct 15, 2020

--

Using plain SQL in Rails helps in boosting your application’s performance. It might be easier to use the built-in ActiveRecord methods, but it is not efficient when it comes to the time that is required to receive a response from the database.

This blog post will teach you how to use plain SQL queries instead of using ActiveRecord methods.

Using Active Record Method

Using ActiveRecord methods is not best practice because there are a few layers to go through to actually reach the database; there is a Rails layer, a Ruby layer until you finally get to the layer that actually communicates to the database.

Here is an example of how to use an ActiveRecord method, all, to scan all the posts and select to retrieve a single post with a specific title:
post = Post.all.select { |post| post.title == title }

Using Plain SQL

Instead, you can use raw SQL to get the same result quicker as follows:
sql = "SELECT * FROM posts WHERE title=#{title}"
record = ActiveRecord::Base.connection.execute(sql)

Here we are defining sql as a string that carries the SQL query and then we run this query directly through the database connection, which is faster than ActiveRecord methods. Also, we are assuming that the ‘title’ is specified beforehand as the title for the post you are looking for. Also, if you aren’t familiar with string interpolation in Ruby, here is a quick recap:
adj = "Awesome"
title = "Rails is #{adj}"

Here the value of ‘title’ is: "Rails is Awesome"

Hope this was clear enough for you to understand the difference between running database queries using the ActiveRecord methods and plain SQL.

Comment below if you would like to add anything to this blog.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shaqqour
Shaqqour

Written by Shaqqour

Full stack software engineer. Passionate about making people’s lives better and easier through programming. LinkedIn.com/in/shaqqour

Responses (2)

Write a response