Oracle SYS_REFCURSOR Example: Return Result Sets From PL/SQL

Oracle SYS_REFCURSOR Example: Return Result Sets From PL/SQL
In this article
  1. What is SYS_REFCURSOR in Oracle?
  2. Sample setup: an orders table
  3. Example 1: open, fetch and close a SYS_REFCURSOR
  4. Example 2: a function that returns SYS_REFCURSOR
  5. Example 3: a procedure with an OUT SYS_REFCURSOR parameter
  6. Example 4: dynamic SQL with OPEN FOR and bind variables
  7. Example 5: fetch a SYS_REFCURSOR in batches with BULK COLLECT
  8. Example 6: implicit result sets with DBMS_SQL.RETURN_RESULT
  9. Common mistakes with SYS_REFCURSOR
  10. Performance tips and best practices
  11. Frequently asked questions
  12. Summary

A SYS_REFCURSOR is Oracle's built-in cursor variable type. You use it to open a query in PL/SQL and hand the result set to someone else: another procedure, a function caller, or a client program written in Java, Python or .NET. The basic pattern is three statements: OPEN cur FOR SELECT ..., FETCH cur INTO ... in a loop, and CLOSE cur.

This tutorial builds every common SYS_REFCURSOR example on one small orders table: a loop in an anonymous block, a function that returns a cursor, a procedure with an OUT cursor parameter, a dynamic query with bind variables, bulk fetching, and Oracle's implicit result sets. Each example shows the expected output and what it means, followed by the mistakes that cause INVALID_CURSOR, ROWTYPE_MISMATCH and ORA-01000.

What is SYS_REFCURSOR in Oracle?

A normal explicit cursor (CURSOR c IS SELECT ...) is fixed to one query at compile time. A cursor variable is different. It is a pointer to a SQL work area, so you can open it for any query at run time, assign it to another variable, and pass it as a parameter. The Oracle documentation calls these cursor variables, and people often call them REF CURSORs.

There are two ways to get one. You can define your own type with TYPE my_cur_t IS REF CURSOR, or you can use the predefined type SYS_REFCURSOR, which saves you the type declaration. SYS_REFCURSOR is a weak type: it has no RETURN clause, so it can point to any query with any columns.

FeatureExplicit cursorSYS_REFCURSOR (cursor variable)
Query fixed at compile timeYesNo, chosen at OPEN time
Can be a parameter or function return valueNoYes
Can be returned to a client programNoYes
Accepts cursor parametersYesNo, but the query can use variables
Works in a cursor FOR loopYesNo
Column check at compile timeYesNo (weak type), checked at fetch time

The trade-off is in that last row. Because a SYS_REFCURSOR can point to any query, PL/SQL cannot check at compile time that your FETCH ... INTO variables match the columns. If they do not match, you find out at run time.

Strong vs weak REF CURSOR

If you add a RETURN clause, the type becomes strong, and PL/SQL checks every query you open against it when the code compiles. (This block uses the orders table created in the next section.)

DECLARE
  TYPE order_cur_t IS REF CURSOR RETURN orders%ROWTYPE;  -- strong
  c_strong order_cur_t;
  c_weak   SYS_REFCURSOR;                                -- weak
BEGIN
  OPEN c_strong FOR SELECT * FROM orders;  -- must return orders%ROWTYPE
  OPEN c_weak   FOR SELECT city, COUNT(*) FROM orders GROUP BY city;  -- any query
  CLOSE c_strong;
  CLOSE c_weak;
END;
/
A strong REF CURSOR type next to a weak SYS_REFCURSOR

Use a strong type inside a package when the shape of the result never changes and you want the compiler to catch mistakes. Use SYS_REFCURSOR when the query varies, or when the cursor goes to a client program, which is the most common case.

Sample setup: an orders table

Run this once. Every example below uses these six rows.

CREATE TABLE orders (
  order_id      NUMBER PRIMARY KEY,
  customer_name VARCHAR2(50) NOT NULL,
  city          VARCHAR2(30) NOT NULL,
  amount        NUMBER(10,2) NOT NULL,
  status        VARCHAR2(10) NOT NULL,
  order_date    DATE         NOT NULL
);

INSERT INTO orders VALUES (101, 'Asha Rao',    'Pune',   2500, 'SHIPPED',   DATE '2026-10-01');
INSERT INTO orders VALUES (102, 'Vikram Shah', 'Mumbai', 1200, 'PENDING',   DATE '2026-10-03');
INSERT INTO orders VALUES (103, 'Meera Iyer',  'Pune',   4800, 'SHIPPED',   DATE '2026-10-05');
INSERT INTO orders VALUES (104, 'Rahul Verma', 'Delhi',   750, 'CANCELLED', DATE '2026-10-06');
INSERT INTO orders VALUES (105, 'Kiran Patel', 'Pune',   3100, 'PENDING',   DATE '2026-10-08');
INSERT INTO orders VALUES (106, 'Sneha Nair',  'Mumbai', 5600, 'SHIPPED',   DATE '2026-10-09');
COMMIT;
Sample table and data

In SQL*Plus or SQL Developer, run SET SERVEROUTPUT ON first so you can see the DBMS_OUTPUT lines in the examples.

Example 1: open, fetch and close a SYS_REFCURSOR

Start with the simplest case: declare the cursor variable, open it for a query, fetch rows one at a time, then close it.

DECLARE
  c_orders  SYS_REFCURSOR;
  v_id      orders.order_id%TYPE;
  v_name    orders.customer_name%TYPE;
  v_amount  orders.amount%TYPE;
BEGIN
  OPEN c_orders FOR
    SELECT order_id, customer_name, amount
      FROM orders
     WHERE city = 'Pune'
     ORDER BY order_id;

  LOOP
    FETCH c_orders INTO v_id, v_name, v_amount;
    EXIT WHEN c_orders%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_id || '  ' || RPAD(v_name, 12) || v_amount);
  END LOOP;

  DBMS_OUTPUT.PUT_LINE('Rows fetched: ' || c_orders%ROWCOUNT);
  CLOSE c_orders;
END;
/
Basic SYS_REFCURSOR loop
101  Asha Rao    2500
103  Meera Iyer  4800
105  Kiran Patel 3100
Rows fetched: 3
Output (expected output)

Here is what each step does. OPEN ... FOR runs the query, identifies the result set and positions the cursor before the first row. Each FETCH moves one row into the variables. When there are no more rows, %NOTFOUND becomes TRUE and the loop exits. %ROWCOUNT is the number of rows fetched so far, which is 3 at the end.

The EXIT WHEN line must come straight after the FETCH. If you put it after the PUT_LINE, the last row prints twice, because the variables still hold the previous row when the final fetch finds nothing.

You can also reuse the same variable for a different query. You do not need to close it before opening it again; the old query is simply dropped. Close it once at the end.

Example 2: a function that returns SYS_REFCURSOR

The main reason SYS_REFCURSOR exists is to return a result set from a stored program. A function is the cleanest way to do that.

CREATE OR REPLACE FUNCTION get_orders_by_city (
  p_city IN orders.city%TYPE
) RETURN SYS_REFCURSOR
IS
  c_result SYS_REFCURSOR;
BEGIN
  OPEN c_result FOR
    SELECT order_id, customer_name, amount
      FROM orders
     WHERE city = p_city
     ORDER BY order_id;
  RETURN c_result;   -- do NOT close it here
END get_orders_by_city;
/
Function returning an open cursor

Notice that the function opens the cursor and returns it open. The caller fetches the rows and the caller closes it. If you close it inside the function, the caller receives a closed cursor and the first fetch fails with INVALID_CURSOR.

Calling it from SQL*Plus or SQL Developer

SQL*Plus has a bind variable type for cursors, REFCURSOR, and PRINT fetches and displays all its rows. In SQL Developer, run these lines as a script (F5).

VARIABLE rc REFCURSOR
EXEC :rc := get_orders_by_city('Mumbai');
PRINT rc
Print the returned cursor in SQL*Plus

Output (expected output):

ORDER_IDCUSTOMER_NAMEAMOUNT
102Vikram Shah1200
106Sneha Nair5600

SQL*Plus closes the cursor after PRINT. If you want to print it again, run the EXEC line again first.

Calling it from PL/SQL

DECLARE
  c        SYS_REFCURSOR;
  v_id     orders.order_id%TYPE;
  v_name   orders.customer_name%TYPE;
  v_amount orders.amount%TYPE;
BEGIN
  c := get_orders_by_city('Delhi');
  LOOP
    FETCH c INTO v_id, v_name, v_amount;
    EXIT WHEN c%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_id || ' ' || v_name || ' ' || v_amount);
  END LOOP;
  CLOSE c;
END;
/
Fetching from the function result
104 Rahul Verma 750
Output (expected output)

Example 3: a procedure with an OUT SYS_REFCURSOR parameter

Many application teams prefer procedures with OUT parameters, because a procedure can return a cursor and other values in one call. This is the form Java, .NET and Python drivers usually call to get a result set.

CREATE OR REPLACE PROCEDURE get_orders_by_status (
  p_status IN  orders.status%TYPE,
  p_total  OUT NUMBER,
  p_result OUT SYS_REFCURSOR
)
IS
BEGIN
  SELECT NVL(SUM(amount), 0)
    INTO p_total
    FROM orders
   WHERE status = p_status;

  OPEN p_result FOR
    SELECT order_id, customer_name, city, amount
      FROM orders
     WHERE status = p_status
     ORDER BY amount DESC;
END get_orders_by_status;
/
Procedure with an OUT cursor parameter
VARIABLE total NUMBER
VARIABLE rc REFCURSOR
EXEC get_orders_by_status('SHIPPED', :total, :rc);
PRINT total
PRINT rc
Call it with SQL*Plus bind variables

Output (expected output): PRINT total shows 12900 (2500 + 4800 + 5600), and PRINT rc shows the three shipped orders, largest first:

ORDER_IDCUSTOMER_NAMECITYAMOUNT
106Sneha NairMumbai5600
103Meera IyerPune4800
101Asha RaoPune2500

In a client program the idea is the same: register the third parameter as a cursor type, execute the call, and read the parameter as a normal result set. Close that result set when you are done.

Example 4: dynamic SQL with OPEN FOR and bind variables

A cursor variable can also be opened for a query held in a string. This is how you build search screens where the sort order or the filters change at run time. Put values in the USING clause as bind variables, never concatenate them into the string.

CREATE OR REPLACE FUNCTION search_orders (
  p_city       IN VARCHAR2,
  p_min_amount IN NUMBER,
  p_sort       IN VARCHAR2   -- 'AMOUNT' or 'ID'
) RETURN SYS_REFCURSOR
IS
  c_result SYS_REFCURSOR;
  v_sql    VARCHAR2(500);
BEGIN
  v_sql := 'SELECT order_id, customer_name, amount
              FROM orders
             WHERE city = :city
               AND amount >= :min_amt
             ORDER BY '
           || CASE p_sort
                WHEN 'AMOUNT' THEN 'amount DESC'
                ELSE 'order_id'
              END;

  OPEN c_result FOR v_sql USING p_city, p_min_amount;
  RETURN c_result;
END search_orders;
/
Dynamic query with binds and a whitelisted sort column
VARIABLE rc REFCURSOR
EXEC :rc := search_orders('Pune', 3000, 'AMOUNT');
PRINT rc
Pune orders of 3000 or more, biggest first

Output (expected output):

ORDER_IDCUSTOMER_NAMEAMOUNT
103Meera Iyer4800
105Kiran Patel3100

Two things make this safe. The city and amount are bind variables (:city, :min_amt), so a value like Pune' OR '1'='1 is treated as plain text, not SQL. And the ORDER BY column cannot be a bind variable, so the CASE expression picks from a fixed list instead of pasting the user's input into the query.

Binds also help the shared pool. Each sort option produces one fixed SQL text, whatever city and amount are passed, so Oracle can reuse the parsed statement instead of hard parsing a new one for each city and amount.

Example 5: fetch a SYS_REFCURSOR in batches with BULK COLLECT

Fetching one row at a time is fine for a handful of rows. For thousands of rows, fetch in batches with BULK COLLECT ... LIMIT. It works on cursor variables exactly as it does on explicit cursors.

DECLARE
  TYPE t_ids  IS TABLE OF orders.order_id%TYPE;
  TYPE t_amts IS TABLE OF orders.amount%TYPE;
  c      SYS_REFCURSOR;
  l_ids  t_ids;
  l_amts t_amts;
BEGIN
  OPEN c FOR SELECT order_id, amount FROM orders ORDER BY order_id;
  LOOP
    FETCH c BULK COLLECT INTO l_ids, l_amts LIMIT 4;
    EXIT WHEN l_ids.COUNT = 0;
    DBMS_OUTPUT.PUT_LINE('Batch of ' || l_ids.COUNT ||
                         ' rows, first id ' || l_ids(1));
  END LOOP;
  CLOSE c;
END;
/
Batch fetch from a cursor variable
Batch of 4 rows, first id 101
Batch of 2 rows, first id 105
Output (expected output)

Note the exit test. With BULK COLLECT, check l_ids.COUNT = 0, not %NOTFOUND. On the second fetch only 2 of the requested 4 rows come back, so %NOTFOUND is already TRUE, and exiting on it would skip those 2 rows. In real code use a LIMIT of a few hundred; 4 is only to show two batches. The BULK COLLECT LIMIT tutorial covers this pattern with FORALL.

Example 6: implicit result sets with DBMS_SQL.RETURN_RESULT

From Oracle Database 12c Release 1, a procedure can send result sets straight to the client without any OUT parameter, using DBMS_SQL.RETURN_RESULT. This is handy for report procedures and for code migrated from SQL Server or Sybase, where procedures return results this way.

CREATE OR REPLACE PROCEDURE order_summary
IS
  rc1 SYS_REFCURSOR;
  rc2 SYS_REFCURSOR;
BEGIN
  OPEN rc1 FOR
    SELECT status, COUNT(*) AS orders
      FROM orders GROUP BY status ORDER BY status;
  DBMS_SQL.RETURN_RESULT(rc1);

  OPEN rc2 FOR
    SELECT city, SUM(amount) AS total_amount
      FROM orders GROUP BY city ORDER BY city;
  DBMS_SQL.RETURN_RESULT(rc2);
END order_summary;
/

EXEC order_summary
Two implicit result sets from one procedure

Output (expected output), first result set:

STATUSORDERS
CANCELLED1
PENDING2
SHIPPED3

Second result set:

CITYTOTAL_AMOUNT
Delhi750
Mumbai6800
Pune10400

After RETURN_RESULT, the cursor belongs to the client, so do not fetch from it or close it in the procedure. The client must support implicit results; SQL*Plus and SQL Developer from 12c onward display them. The docs also note that implicit results cannot be returned over remote procedure calls.

Common mistakes with SYS_REFCURSOR

1. Using a cursor FOR loop

FOR r IN c_orders LOOP works for explicit cursors only. The documentation lists this as a restriction on cursor variables, and the code will not compile. Use the OPEN, FETCH, EXIT WHEN, CLOSE loop from Example 1, or BULK COLLECT.

2. Closing the cursor before the caller uses it

If a function closes the cursor before returning it, or a caller fetches after closing, PL/SQL raises the predefined exception INVALID_CURSOR (ORA-01001). The same happens if you read any attribute other than %ISOPEN on a cursor that is not open.

DECLARE
  c    SYS_REFCURSOR;
  v_id NUMBER;
BEGIN
  OPEN c FOR SELECT order_id FROM orders;
  CLOSE c;
  FETCH c INTO v_id;   -- cursor is already closed
END;
/
Fetching from a closed cursor
ORA-01001: invalid cursor
Error (expected output)

3. FETCH INTO variables that do not match the query

With a weak cursor, the column check happens at run time. If the query returns three columns and you fetch into two variables, or into variables of incompatible types, PL/SQL raises ROWTYPE_MISMATCH (ORA-06504). Keep the SELECT list and the INTO list next to each other in reviews, or use a strong REF CURSOR type where the shape is fixed.

4. Never closing the cursor

Each open cursor uses a slot in the session. Code that opens cursors and never closes them, very often client code that forgets to close a result set, eventually hits ORA-01000 (maximum open cursors exceeded). The limit is the OPEN_CURSORS initialization parameter. Raising it only delays the error; the fix is to close every cursor when you finish with it, including on the error path:

EXCEPTION
  WHEN OTHERS THEN
    IF c_orders%ISOPEN THEN
      CLOSE c_orders;
    END IF;
    RAISE;
Close the cursor in the exception handler, then re-raise

5. Expecting %ROWCOUNT to be the total row count

Right after OPEN, %ROWCOUNT is 0, because nothing has been fetched yet. Oracle does not know the total until the last row is read. If the caller needs a total up front, return it separately (as p_total in Example 3) or add COUNT(*) OVER () as a column.

6. Testing the cursor with IS NULL or =

You cannot compare cursor variables for equality, inequality or nullity. To check whether a cursor is usable, test c%ISOPEN.

Performance tips and best practices

  • Fetch in batches. In PL/SQL use BULK COLLECT with LIMIT. In client code, set the driver's fetch size (for example the JDBC fetch size, or SET ARRAYSIZE in SQL*Plus) so each network round trip brings back many rows.
  • Use binds. In static OPEN FOR queries, PL/SQL variables are bound automatically. In dynamic strings, pass values with USING so the statement is shared, not hard parsed each time.
  • The result set is fixed at OPEN time. Oracle evaluates the variables in the query when the cursor opens, and the rows you fetch are read consistent as of that point. A cursor that stays open while the client fetches slowly for a long time can hit ORA-01555 snapshot too old.
  • Return only the columns the caller needs. SELECT * through a cursor sends every column over the network and breaks callers when the table changes.
  • Do not pass cursors over database links. The documentation states that cursor variables cannot be passed to or returned from subprograms called through a database link.
  • Close what you open, in one place. Decide which layer closes the cursor (usually the caller) and stick to it.

Frequently asked questions

What is the difference between SYS_REFCURSOR and REF CURSOR?

REF CURSOR is the general type of cursor variable; you declare your own type with TYPE t IS REF CURSOR, optionally with a RETURN clause. SYS_REFCURSOR is a predefined weak REF CURSOR type, so you can use it directly without declaring a type. Weak REF CURSOR types and SYS_REFCURSOR are interchangeable.

Can I use a cursor FOR loop with SYS_REFCURSOR?

No. Cursor FOR loops accept explicit cursors and inline queries only. Fetch from a SYS_REFCURSOR with an explicit FETCH loop or BULK COLLECT.

How do I count the rows in a SYS_REFCURSOR?

You cannot know the count before fetching. %ROWCOUNT tells you how many rows have been fetched so far, so after the loop finishes it holds the total. If you need the count first, run a separate COUNT(*) or include COUNT(*) OVER () in the query.

How do I see SYS_REFCURSOR output in SQL Developer?

Declare a bind variable with VARIABLE rc REFCURSOR, assign the cursor with EXEC :rc := your_function(...), then PRINT rc, and run all three lines as a script with F5. For a procedure that uses DBMS_SQL.RETURN_RESULT, just execute the procedure.

Who should close a SYS_REFCURSOR, the procedure or the caller?

The code that finishes fetching. When a function or procedure returns an open cursor, the caller must close it. Closing it inside the procedure makes it useless to the caller.

Summary

  • SYS_REFCURSOR is a predefined weak cursor variable type: a pointer to a query result set.
  • Pattern: OPEN cur FOR query, FETCH in a loop with EXIT WHEN cur%NOTFOUND right after the fetch, then CLOSE.
  • Return it from a function or an OUT parameter to give result sets to callers and client programs; return it open.
  • For dynamic queries, use OPEN FOR string USING binds, and whitelist anything that cannot be bound, like ORDER BY columns.
  • Use BULK COLLECT LIMIT and exit on COUNT = 0 for large result sets.
  • Cursor FOR loops do not work on cursor variables; INVALID_CURSOR means it is closed, ROWTYPE_MISMATCH means the INTO list does not match.
  • Close every cursor, including in exception handlers, to avoid ORA-01000.
  • From 12c, DBMS_SQL.RETURN_RESULT returns result sets to the client without OUT parameters.
PT Ganesh

An experienced PostgreSQL DBA/SQL developer with years of expertise in designing and implementing robust database solutions. Proficient in writing complex queries, developing stored procedures, and conducting performance tuning to deliver highly efficient data-driven applications that meet business requirements.

Home
SQL
PLSQL
Interview Q&A