Simplify SQL queries

Some simplifications in the SQL.