This article is half-done without your Comment! *** Please share your thoughts via Comment ***
One of our PostgreSQL database developers asked one question: What is the performance difference between RETURNS TABLE and OUT parameters?
My simple answer was, no major difference between these two, but RETURNS TABLE is quite faster, easy to write, clear to everyone.
I have prepared two different function one is “plpgsql” and the other is “sql” language.
You can access this demonstration and compare the performance report in your Postgres Environment.
Create a table with sample data:
1 2 3 4 5 6 7 8 9 10 11 |
CREATE TABLE tbl_ItemTransactions ( TranID SERIAL ,TransactionDate TIMESTAMP WITHOUT TIME ZONE ,TransactionName TEXT ); INSERT INTO tbl_ItemTransactions (TransactionDate, TransactionName) SELECT x, 'dbrnd' FROM generate_series('2016-01-01 00:00:00', '2016-12-31 00:00:00','2 seconds'::interval) a(x); |
Create a function to test RETURN TABLE:
1 2 3 4 5 6 7 8 9 10 11 12 |
CREATE OR REPLACE FUNCTION fn_TestReturnTable(InTransactionDate TIMESTAMP WITHOUT TIME ZONE) RETURNS TABLE(OutTranID INTEGER) AS $dbrnd$ BEGIN RETURN QUERY SELECT TranID FROM tbl_ItemTransactions WHERE TransactionDate > InTransactionDate; END; $dbrnd$ LANGUAGE 'plpgsql'; |
Sample Execution:
1 2 |
EXPLAIN ANALYZE SELECT *FROM fn_TestReturnTable ('2016-06-01'); |
Performance Report:
1 2 3 4 5 |
"Function Scan on fn_testreturntable (cost=0.25..10.25 rows=1000 width=4) (actual time=13390.371..31899.698 rows=9201600 loops=1)" "Planning time: 0.047 ms" "Execution time: 43660.453 ms" |
Create a function to test the OUT parameter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
CREATE OR REPLACE FUNCTION fn_TestOutParameter ( InTransactionDate TIMESTAMP WITHOUT TIME ZONE ,OUT OutTranID INTEGER ) RETURNS SETOF INT AS $dbrnd$ SELECT TranID::INTEGER FROM tbl_ItemTransactions WHERE TransactionDate > InTransactionDate; $dbrnd$ LANGUAGE 'sql'; |
Sample Execution:
1 2 |
EXPLAIN ANALYZE SELECT *FROM fn_TestOutParameter ('2016-06-01'); |
Performance Report:
1 2 3 4 5 |
"Function Scan on fn_testoutparameter (cost=0.25..10.25 rows=1000 width=4) (actual time=12698.673..31794.391 rows=9201600 loops=1)" "Planning time: 0.055 ms" "Execution time: 47854.064 ms" |
Leave a Reply