Skip to Main Content
  • Questions
  • Query vs Standalone function vs Inline query

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Anvesh.

Asked: January 23, 2017 - 2:28 pm UTC

Last updated: January 23, 2017 - 5:07 pm UTC

Version: 11

Viewed 1000+ times

You Asked

Hi Tom,

Hope you had a great vacation.
This is regd. a suggestion that I came across recently, On a query which fetches the data from a table.

Please go through below example for brief analysis.

Select ail.invoice_id,
(select tax_rate_code from zx_rates_all where tax_rate_id=ail.tax_rate_id) tax_rate_code
from ap_invoice_lines_all ail where ail.invoice_id=:P_INVOICE_ID;

In above query, I can pull tax rate code from an inline query, a standalone function (by writing inline query inside fn. and returning tax rate code).
Assuming the query is executing for bulk number of records (which may have same tax rate id), Can you please let me know which method will you prefer and explaining each method's pros and cons?
Adding to this, is there any difference between (performance wise) standalone function vs creating the same function in a package which will be called from a SQL query inside a concurrent program?

Thanks in Advance


and Chris said...

You should do this all in one query.

Why?

A couple of reasons.

Firstly it's likely to perform better. The database only has to execute one query, so there's less to parse. And the optimizer may be able to come up with transformations not possible if you bury the SQL in a function. And there's no SQL<>PL/SQL context switching.

The second is more insidious but perhaps more important:

You can get unexpected results!

Oracle statements are read consistent to the point in time they start. So you have SQL that starts at T1. This calls PL/SQL which runs another SQL statement. This second statement starts at some time after the original, Tn. So it can have a different view of the data than the original query.

This can lead to incorrect results.

You can read more about this problem at:

https://blogs.oracle.com/sql/entry/the_problem_with_sql_calling

There's no difference in performance between a package and stand-alone procedure.

Is this answer out of date? If it is, please let us know via a Comment

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library