SQL to ActiveRecord Examples
Learn how to convert common SQL queries to Rails ActiveRecord with these practical examples. Each example shows the SQL query and its equivalent ActiveRecord code.
Note: Our converter is continuously improving. While it handles most common SQL patterns accurately, complex queries may require manual review. Always test the generated ActiveRecord code in your application.
Basic Queries
Simple SELECT with WHERE
Find all active users
SELECT * FROM users WHERE active = true
User.where(active: true)
SELECT with Multiple Conditions
Find users with specific criteria using modern Ruby range syntax
SELECT * FROM users WHERE age > 18 AND city = 'New York'
User.where(city: New York, age: (19..))
SELECT with IN clause
Find users with specific IDs
SELECT * FROM users WHERE id IN (1, 2, 3, 4, 5)
User.where(id: [1, 2, 3, 4, 5])
Ordering and Limiting
ORDER BY with LIMIT
Get the 10 most recent posts
SELECT * FROM posts ORDER BY created_at DESC LIMIT 10
Post.order(created_at: :desc).limit(10)
OFFSET with LIMIT
Pagination - skip first 20 results
SELECT * FROM products LIMIT 10 OFFSET 20
Product.limit(10).offset(20)
Multiple Column Ordering
Sort by multiple columns
SELECT * FROM users ORDER BY last_name ASC, first_name ASC
User.order(:last_name, :first_name)
Joins and Associations
INNER JOIN with SELECT
Join users with their posts and select specific columns
SELECT users.*, posts.* FROM users JOIN posts ON users.id = posts.user_id
User.joins(:posts).select("users.*, posts.*")
LEFT JOIN with SELECT
Include users even if they have no posts
SELECT users.* FROM users LEFT JOIN posts ON users.id = posts.user_id
User.left_joins(:posts).select("users.*")
JOIN with WHERE
Join with additional conditions
SELECT users.* FROM users JOIN posts ON users.id = posts.user_id WHERE posts.published = true
User.joins(:posts).where(posts: { published: true }).select("users.*")
Aggregations
COUNT
Count total number of users
SELECT COUNT(*) FROM users
User.count
GROUP BY with COUNT
Count posts by user
SELECT user_id, COUNT(*) FROM posts GROUP BY user_id
Post.group(:user_id).count
SUM with GROUP BY
Total order amount by user
SELECT user_id, SUM(amount) FROM orders GROUP BY user_id
Order.group(:user_id).sum(:amount)
Advanced Queries
Range Conditions
Using modern Ruby range syntax for numeric comparisons
SELECT * FROM products WHERE price >= 100
Product.where(price: (100..))
BETWEEN Clause
Find records within a range
SELECT * FROM orders WHERE total BETWEEN 50 AND 200
Order.where('total BETWEEN ? AND ?', 50, 200)
IS NULL Check
Find records with null values
SELECT * FROM users WHERE email IS NULL
User.where(email: nil)
Ready to Convert Your SQL?
Use our free converter to transform any SQL query into ActiveRecord code instantly. Need help getting started? Read our complete guide or learn about SQL patterns.
Start Converting