Are you certain that this works on all databases? I suspect the stock-contents tables aren't ordered, so in MySQL (maybe?) and PostgreSQL (definitely) this will fail.