In language like C or Java, there are things like functions/methods to modularize and abstract stuff.
What is there in SQL, specifically for Oracle?
I've seen people talking about using views to reduce the complexity in various blogs but there is only so much that can be done with a view. (For example, a bind variable cannot be passed as a runtime parameter to a view). In tools like Oracle Reports the query sometimes gets very awkward running several hundreds of lines.
I was wondering what sort of techniques people use to manage the complexity of their SQL? What are the equivalents of functions and methods in SQL to keep SQL from becoming extremely complex?
2 Answers 2
I have found common table expressions (cte's) helpful for both reducing the size and complexity as well as making the query more readable. Temporary results (temp tables and so forth) can be a mixed blessing, as can user defined functions. They can certainly make the code more readable, but may have a performance impact (not that the impact is always negative, but it is something to watch out for).
-
Thanks. FWIW, I found that CTEs are under a different name in Oracle viz., WITH clause.toddlermenot– toddlermenot2011年10月11日 07:49:50 +00:00Commented Oct 11, 2011 at 7:49
PL-SQL supports user defined functions. You can use this to re-use some common logic with queries. However, there are significant performance penalties for doing this, as UDFs hide indexes from the query. Most of the time, you're better off writing out your query logic again.
Another option is to use a computed column. This let's you do some (not all) of the same things as a scalar user defined function, but is more index-friendly.
-
Thanks for the tip about computed column. Haven't heard that one before.toddlermenot– toddlermenot2011年10月11日 07:53:37 +00:00Commented Oct 11, 2011 at 7:53
SELECT
from that view would make available?SELECT
something (e.g.,SELECT a+bound_value, b+bound_value ...
or in aWHERE
clause (e.g.,... WHERE a = bound_value
). Whether you're using plain, indexed or materialized views, the database can't index against an expression that can't be calculated when the index needs to be updated.SELECT
from that view can't.