Is there a way to modularize SQL code so that is more readable and testable?
My SQL code often becomes a long complicated series of nested joins, inner joins, etc. that are hard to write and hard to debug. By contrast, in a procedural language like Javascript or Java, one would pinch off discrete elements as separate functions you would call by name.
Yes, one could write each as entirely separate queries, stored in the database, or as stored procedures, but often I don't want to change/clutter the database, just query it is fine, especially if the DBA doesn't wish to grant write permissions to all users.
For instance, conceptually a complex query might be easily described in pseudocode like this:
(getCustomerProfile)
left join
(getSummarizedCustomerTransactionHistory)
using (customerId)
left join
(getGeographicalSummaries)
using (region, vendor)
...
I realize that a lot is written on the topic from a theoretical vantage (a few links below), but I'm just looking for a way to make the code easier to write correctly, and easier to read once written. Perhaps just syntactic sugar to abstract the complexity from sight, if not from execution, that compiles down in the literal SQL I'm trying to not look at. By analogy...
- Stylus: CSS ::
- CoffeeScript : Javascript ::
- SAS Macro language: SAS language ::
- ? : SQL
And if the specific SQL flavor matters, most of my work is in PostgresQL.
http://lambda-the-ultimate.org/node/2440