I’ve been always wondering how mutiple rows are selected from the database and one or more of their columns are updated on-the-fly. let’s take a search engine for example, where thousands of results are grabbed and a view count is updated (using a single query).
Is that possible? do they use special SQL features in order to achieve that?
P.S.: If this question has been asked before please refer me cause I haven’t found an identical one, and if it’s lame, I know.
If you consider, for example, how Google does it, they use Bigtable (see this question for discussion) I don’t know anything about how it works internally, so can’t comment.
As for your question, it is not possible to do a
selectand anupdatein one go – in pure SQL, that is. It is, however, possible to do this with a stored function. Consider the following function (pseudo-code)Then in the application, you can make one database call:
This way, there is only one “hit” from the application (i.e. you are only executing one query from the application against the database connection), however internally view count is updated and the data is returned.
Specifics, of course, will depend on the database engine and your particular needs, but I do use this technique in my web site quite extensively.