This is an SqlPattern. ---- '''Context''' If you need to generate a complex report from relational data, you often don't know where to start. SQL seems inappropriate to generate what you need, and you are tempted to write iterative code to achieve it - SqlMyopia prevents you from seeing a solution. A method is needed to help. ---- '''Solution''' SQL is a declarative language that allows expressing relational computation and specifying constraints. ThinkSqlAsConstraintSatisfaction. 1 Write a query that will produce the rows you need in the result 1 Filter out what you don't need by specifying your constraints on the data. ---- '''Example''' A classic example is the way to implement the ''select top'' clause of Microsoft SQL Server (''select first'' with Informix, Oracle uses a special column named ''rownum'') in a database-independent way. You have the query: select * from company order by earnings desc but are interesting in getting only the top 10. You can get it like this: select * from company c1 order by earnings desc where 10 > (select count(*) from company c2 where c1.earnings>c2.earnings) The statement literally says "give me all companies, for which there are less than 10 with bigger earnings". A variant using SelfJoin instead of CorrelatedSubquery is something like: select c1.* from company c1, company c2 order by c1.earnings desc where c1.earnings