2

How would I recreate the following query in Rails speak so that it returns the amount of rows processed?

self.connection.execute('DELETE FROM `cd_artist`
LEFT JOIN `cdpedia` ON cd_artist.id = cdpedia.`artistId`
WHERE artistId IS NULL;')

I realize I should use something like Artist.find_by_sql for it to return something, but that gives me an error.

Perhaps there is a more elegant way of doing this?

I want to avoid the Rails way of first searching the database, then grabbing the IDs and deleting the entries with Object.destroy or even Object.delete(id) since a SQL call is so much faster (if you have the right indexes), but I'm curious as to what the "proper" way to do it is.

1
  • Your query seems to be wrong. Have you already tested it directly on your database? Commented Jan 13, 2012 at 13:13

1 Answer 1

3

You just have to replace execute by delete, and it will return the number of rows affected.

self.connection.delete('DELETE FROM `cd_artist`
LEFT JOIN `cdpedia` ON cd_artist.id = cdpedia.`artistId`
WHERE artistId IS NULL;')

There is maybe a more elegant way to do this with ActiveRecord, but I doubt it will be as efficient as a raw SQL query.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. So just use delete and also include the DELETE inside the query? I'm guessing connection.delete simply returns the number of rows affected (regardless of the actual query) and execute does not?
@kakubei Yes you have to include the keyword DELETE, because the query won't be analyzed. So if you put an UPDATE statement, delete() won't see any difference (as you said). execute() however will return a result for select statements and nil for insert/update/delete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.