4 ms·
The one thing I like about ORMs (where I control the ORM): I can prevent any SQL query from being run that doesn't have a WHERE statement. Especially when deal
by buro9 12y ago
The one thing I like about ORMs (where I control the ORM): I can prevent any SQL query from being run that doesn't have a WHERE statement.
Especially when dealing with anything that changes data, lack of WHERE is very dangerous.
That said, I write raw SQL. It's the only way to get the performance. As an abstraction it's already great and I don't feel I need another abstraction on top of it.
An example of the kind of query that an ORM is bad at:
SELECT id
,value_from_row_based_functions(some_column) AS foo
FROM bar
WHERE some_column = 'blah'
ORDER BY id DESC
FETCH FIRST 25 ROWS ONLY
It's bad because the ORM will merrily do this even though the row based function may be expensive. Over hundreds of rows this isn't an issue, but over millions or tens of millions it kills your query (if it doesn't timeout it will merrily carry on for hours).
Good SQL always reduces the amount of work involved, you tailor it as you would your regular code to avoid doing work that isn't needed (reading rows you will discard through a filter, etc).
The above could be written as:
SELECT id
,value_from_row_based_functions(some_column) AS foo
FROM (
SELECT id
,some_column
FROM bar
WHERE some_column = 'blah'
ORDER BY id DESC
FETCH FIRST 25 ROWS ONLY
) AS something
And now the row based function is only applied to the 25 rows that are going to be returned.
If you look at the very bottom of this: http://www.postgresql.org/docs/9.2/static/textsearch-controls.html http://www.postgresql.org/docs/9.2/static/textsearch-control... you'll see this is a real-world problem.
ORMs can stitch together your SQL in a certain way that is fairly optimal for most common scenarios... but you will encounter a scenario in which raw SQL is the only way to go.
- Ma8ee 12y agoI'm almost 100% certain that the function will be called only 25 times no matter which way you write the query. Not only is the select statement semantically at the end, but any engine worth anything optimizes this kind of things.
- buro9 12y agoYou are 100% incorrect when it comes to Postgres. Feel free to try it out.
- deleted 12y ago[deleted]