Don't be afraid to create intermediate results. When I started writing my first database queries, I tried to put everything into A SINGLE statement with lots of subqueries. For the sake of your own sanity, do not do that. Instead, create intermediate result tables and use them as input for the next query so that every query does only one thing. When a query does only one thing, it's much easier for the internal optimizer of the SQL engine to find an efficient execution strategy. If storage space is a concern for you, make sure to delete every one of these temporary intermediate tables as soon as you don't need it anymore. A positive side effect of this method is the ability to check the data in the intermediate table for errors or incorrect results. When your result seems wrong, you can execute your script query by query and, at each stage, check if something went wrong. This will also help you to modularize your code, making it easier to maintain.