Skip to main content

Convert SQL SELECT to Rails ActiveRecord

Transform any SQL SELECT query into clean Rails ActiveRecord code instantly

Supports WHERE clauses, JOINs, ORDER BY, GROUP BY, and complex conditions • 100% Free • No registration required

Try it now:

Common SELECT to ActiveRecord Conversions

Basic WHERE Clause

SQL SELECT:

SELECT * FROM users WHERE active = true AND age > 18

ActiveRecord:

User.where(active: true).where('age > ?', 18)

INNER JOIN

SQL SELECT:

SELECT users.name, posts.title FROM users INNER JOIN posts ON users.id = posts.user_id

ActiveRecord:

User.joins(:posts).select('users.name, posts.title')

ORDER BY with LIMIT

SQL SELECT:

SELECT * FROM articles ORDER BY created_at DESC LIMIT 10

ActiveRecord:

Article.order(created_at: :desc).limit(10)

GROUP BY with COUNT

SQL SELECT:

SELECT category, COUNT(*) FROM products GROUP BY category

ActiveRecord:

Product.group(:category).count

What SELECT Queries Can You Convert?

Supported Features

  • WHERE clauses with AND, OR conditions
  • INNER JOIN, LEFT JOIN, RIGHT JOIN
  • ORDER BY, GROUP BY, HAVING
  • LIMIT, OFFSET pagination
  • Aggregate functions (COUNT, SUM, AVG)
  • Subqueries and EXISTS conditions

Best Practices Generated

  • Rails-style method chaining
  • Proper association usage
  • SQL injection prevention
  • Optimized query performance
  • Readable and maintainable code

Common SELECT Pitfalls When Converting to ActiveRecord

SELECT * loads all columns — use .select() to limit

ActiveRecord's default scope loads every column, which is expensive for wide tables. The Rails equivalent of SELECT name, email FROM users is User.select(:name, :email). Omitting .select() fetches all columns including large text fields and blobs — an easy performance regression.

DISTINCT behaves differently with JOINs

SELECT DISTINCT user_id FROM posts maps to Post.select(:user_id).distinct. However, if you add a JOIN, ActiveRecord may return duplicate rows that raw SQL wouldn't — because .distinct applies to the full SELECT list, not just one column.

ORDER BY with NULLs is database-specific

SQL's ORDER BY column NULLS LAST is not expressible with plain ActiveRecord chain syntax — you need order(Arel.sql("column NULLS LAST")). PostgreSQL defaults NULLs to last in DESC order; MySQL puts them first. Converting ORDER BY without checking NULL handling is a common source of ordering bugs.

When to use raw SQL for SELECT

Reach for find_by_sql or ActiveRecord::Base.connection.execute when your SELECT uses window functions (ROW_NUMBER(), RANK()), lateral joins, or UNION. ActiveRecord's query builder does not support these natively in Rails 7 or 8 without Arel hacks.

Ready to Convert Your SELECT Queries?

Join thousands of Rails developers who use our tool daily