fixes to SQL ordering bugs