Migrated to queries

SQL migrated partially.