In this article
- What EXECUTE IMMEDIATE does
- Sample setup
- Example 1: Run DDL with EXECUTE IMMEDIATE
- Example 2: SELECT INTO with bind variables
- Example 3: UPDATE, INSERT and DELETE with USING
- Example 4: RETURNING INTO with dynamic DML
- Example 5: Fetch many rows with BULK COLLECT INTO
- Example 6: Dynamic table or column names, safely
- Example 7: Run a dynamic PL/SQL block
- Common mistakes and how to fix them
- Performance tips and best practices
- Frequently asked questions
- Summary
EXECUTE IMMEDIATE runs a SQL statement or PL/SQL block that you build as a string at run time. You put the statement text in quotes, pass values with USING, and read results with INTO, BULK COLLECT INTO or RETURNING INTO. A typical call looks like EXECUTE IMMEDIATE 'SELECT salary FROM employees WHERE emp_id = :id' INTO v_sal USING 101;
This tutorial walks through every common form with a small employees table: DDL, single-row queries, updates, RETURNING INTO, multi-row queries, dynamic table and column names, and dynamic PL/SQL blocks. Each example shows the output you should see, and the last sections cover the mistakes that cause most EXECUTE IMMEDIATE errors.
What EXECUTE IMMEDIATE does
Normal SQL inside PL/SQL is static SQL. The compiler sees the full statement when you compile the procedure, checks that tables and columns exist, and works out the privileges. That is fast and safe, so it should be your default.
Sometimes the statement is not known until the code runs. The table name comes from a parameter, you need to run DDL such as CREATE TABLE or TRUNCATE, or the WHERE clause depends on which filters a user picked. Static SQL cannot do these things. This is dynamic SQL, and EXECUTE IMMEDIATE is Oracle's native way to run it.
When the line runs, Oracle takes the string, parses it, binds the values you pass in USING, executes it and hands back any results, all in one step. The Oracle docs note that it "prepares the dynamic string before every execution", so there is a small cost each time compared with static SQL.
| Statement type | Where inputs go | Where results go |
|---|---|---|
| SELECT returning at most one row | USING | INTO |
| SELECT returning many rows | USING | BULK COLLECT INTO |
| INSERT / UPDATE / DELETE | USING | none (check SQL%ROWCOUNT) |
| DML with RETURNING clause | USING (IN only) | RETURNING INTO |
| Anonymous PL/SQL block or CALL | USING (IN, OUT, IN OUT) | OUT binds in USING |
| DDL with no placeholders | none | none |
This table follows the rules in the PL/SQL Language Reference. If you remember it, you will know which clause to write for any statement. If the number or data types of the inputs and outputs are not known until run time, native dynamic SQL cannot handle it and you need the DBMS_SQL package instead.
Sample setup
Create this table and data so you can run every example in SQL*Plus, SQL Developer or SQLcl. Turn on server output first so you can see DBMS_OUTPUT messages.
SET SERVEROUTPUT ON
CREATE TABLE employees (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(50) NOT NULL,
dept VARCHAR2(20) NOT NULL,
salary NUMBER(10,2)
);
INSERT INTO employees VALUES (101, 'Asha Rao', 'IT', 65000);
INSERT INTO employees VALUES (102, 'Vikram Shah', 'IT', 72000);
INSERT INTO employees VALUES (103, 'Neha Gupta', 'HR', 48000);
INSERT INTO employees VALUES (104, 'Rahul Verma', 'SALES', 55000);
INSERT INTO employees VALUES (105, 'Priya Nair', 'SALES', 51000);
COMMIT;| EMP_ID | EMP_NAME | DEPT | SALARY |
|---|---|---|---|
| 101 | Asha Rao | IT | 65000 |
| 102 | Vikram Shah | IT | 72000 |
| 103 | Neha Gupta | HR | 48000 |
| 104 | Rahul Verma | SALES | 55000 |
| 105 | Priya Nair | SALES | 51000 |
Example 1: Run DDL with EXECUTE IMMEDIATE
You cannot write CREATE TABLE or DROP TABLE directly inside a PL/SQL block. The compiler rejects it. Wrap the statement in a string and run it with EXECUTE IMMEDIATE.
Create a backup table
BEGIN
EXECUTE IMMEDIATE
'CREATE TABLE employees_bkp AS SELECT * FROM employees';
DBMS_OUTPUT.PUT_LINE('Backup table created');
END;
/Backup table created
PL/SQL procedure successfully completed.The statement has no placeholders and returns nothing, so it needs no INTO or USING clause. Notice there is no semicolon inside the quotes. A SQL statement string must not end with one.
Drop a table only if it exists
A common need in deployment scripts is to drop a table without failing when it is missing. Catch the "table or view does not exist" error, ORA-00942, and re-raise anything else.
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE employees_bkp PURGE';
DBMS_OUTPUT.PUT_LINE('Dropped');
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE = -942 THEN
DBMS_OUTPUT.PUT_LINE('Table did not exist, nothing to drop');
ELSE
RAISE;
END IF;
END;
/Dropped
PL/SQL procedure successfully completed.Run it a second time and you get the other message. In Oracle Database 23ai you can write DROP TABLE IF EXISTS employees_bkp instead, but the pattern above works on 19c and older releases.
Example 2: SELECT INTO with bind variables
For a query that returns one row, put the output variables in INTO and the input values in USING. Inside the string, each input is a placeholder: a colon followed by a name or number, such as :id or :1.
DECLARE
v_name employees.emp_name%TYPE;
v_salary employees.salary%TYPE;
v_id NUMBER := 102;
BEGIN
EXECUTE IMMEDIATE
'SELECT emp_name, salary FROM employees WHERE emp_id = :id'
INTO v_name, v_salary
USING v_id;
DBMS_OUTPUT.PUT_LINE(v_name || ' earns ' || v_salary);
END;
/Vikram Shah earns 72000
PL/SQL procedure successfully completed.The order matters. INTO comes before USING, and the variables in INTO must match the selected columns in number and compatible type. Oracle matches placeholders in a SQL statement to USING values by position, not by name. The name :id is only a label.
When no row or many rows come back
EXECUTE IMMEDIATE ... INTO behaves like static SELECT INTO. No row raises NO_DATA_FOUND (ORA-01403). More than one row raises TOO_MANY_ROWS (ORA-01422). Handle the case you expect.
DECLARE
v_name employees.emp_name%TYPE;
BEGIN
EXECUTE IMMEDIATE
'SELECT emp_name FROM employees WHERE emp_id = :id'
INTO v_name
USING 999;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee with that id');
END;
/No employee with that id
PL/SQL procedure successfully completed.You can pass a literal such as 999 in USING. The only value you cannot write there is the keyword NULL, which is covered in the mistakes section.
Example 3: UPDATE, INSERT and DELETE with USING
For DML without a RETURNING clause, every bind value goes in USING. After the statement runs, SQL%ROWCOUNT tells you how many rows it touched.
DECLARE
v_dept VARCHAR2(20) := 'SALES';
v_pct NUMBER := 10;
BEGIN
EXECUTE IMMEDIATE
'UPDATE employees
SET salary = salary * (1 + :pct / 100)
WHERE dept = :dept'
USING v_pct, v_dept;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated');
END;
/2 rows updated
PL/SQL procedure successfully completed.| EMP_ID | EMP_NAME | DEPT | SALARY |
|---|---|---|---|
| 104 | Rahul Verma | SALES | 60500 |
| 105 | Priya Nair | SALES | 56100 |
The two SALES rows went from 55000 and 51000 to 60500 and 56100. The values are bound in the same order as the placeholders appear: :pct first, then :dept. The change is not committed. EXECUTE IMMEDIATE does not commit DML for you, so you decide when to COMMIT or ROLLBACK, as with static SQL.
Example 4: RETURNING INTO with dynamic DML
When the DML statement has its own RETURNING ... INTO :placeholder part, the input values go in USING and the returned values go in a separate RETURNING INTO clause at the end of EXECUTE IMMEDIATE.
DECLARE
v_new_salary employees.salary%TYPE;
BEGIN
EXECUTE IMMEDIATE
'UPDATE employees
SET salary = salary + :amt
WHERE emp_id = :id
RETURNING salary INTO :new_sal'
USING 5000, 103
RETURNING INTO v_new_salary;
DBMS_OUTPUT.PUT_LINE('New salary: ' || v_new_salary);
END;
/New salary: 53000
PL/SQL procedure successfully completed.Neha Gupta's salary was 48000, so it is now 53000. The docs state that when the statement has a RETURNING INTO clause, USING may contain only IN binds. The returned values are always OUT, so you do not write a mode for them. To get values back from an UPDATE that hits many rows, use RETURNING BULK COLLECT INTO with a collection.
Example 5: Fetch many rows with BULK COLLECT INTO
INTO works only for one row. When a dynamic query can return several rows, collect them into a collection with BULK COLLECT INTO.
DECLARE
TYPE t_names IS TABLE OF employees.emp_name%TYPE;
v_names t_names;
BEGIN
EXECUTE IMMEDIATE
'SELECT emp_name FROM employees
WHERE dept = :d
ORDER BY emp_name'
BULK COLLECT INTO v_names
USING 'IT';
FOR i IN 1 .. v_names.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(i || '. ' || v_names(i));
END LOOP;
END;
/1. Asha Rao
2. Vikram Shah
PL/SQL procedure successfully completed.If no rows match, BULK COLLECT does not raise NO_DATA_FOUND. The collection is simply empty and v_names.COUNT is 0. For very large results, open a cursor variable with OPEN c FOR 'SELECT ...' USING ... and fetch in batches with LIMIT, so you do not load everything into memory at once.
Example 6: Dynamic table or column names, safely
Bind variables hold values only. You cannot bind a table name, column name or keyword, because Oracle must know the objects when it parses the statement. Writing 'SELECT * FROM :tab' fails at run time.
So names have to be concatenated into the string. That is exactly where SQL injection happens, so validate every name before you use it. The safe pattern has two steps.
Step 1: check the name against the data dictionary
Step 2: quote it with DBMS_ASSERT
CREATE OR REPLACE PROCEDURE show_max (p_column IN VARCHAR2) AS
v_col user_tab_cols.column_name%TYPE;
v_max VARCHAR2(100);
BEGIN
-- Step 1: the column must really exist on EMPLOYEES
SELECT column_name
INTO v_col
FROM user_tab_cols
WHERE table_name = 'EMPLOYEES'
AND column_name = UPPER(p_column);
-- Step 2: quote the validated name and build the SQL
EXECUTE IMMEDIATE
'SELECT TO_CHAR(MAX(' || DBMS_ASSERT.ENQUOTE_NAME(v_col)
|| ')) FROM employees'
INTO v_max;
DBMS_OUTPUT.PUT_LINE('MAX(' || v_col || ') = ' || v_max);
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20001, 'Unknown column: ' || p_column);
END;
/
EXEC show_max('salary')
EXEC show_max('emp_id) || (SELECT 1 FROM dual')MAX(SALARY) = 72000
PL/SQL procedure successfully completed.
ERROR at line 1:
ORA-20001: Unknown column: emp_id) || (SELECT 1 FROM dual
(followed by ORA-06512 lines)The first call works because SALARY is a real column. The second call is an injection attempt, and it never reaches EXECUTE IMMEDIATE because no column has that name. DBMS_ASSERT.ENQUOTE_NAME wraps the name in double quotes and checks that it is a valid quoted SQL name. By default it converts an unquoted name to upper case, so salary becomes "SALARY".
Other useful DBMS_ASSERT functions: SIMPLE_SQL_NAME raises ORA-44003 if the input is not a simple SQL name, and SQL_OBJECT_NAME raises ORA-44002 if the object does not exist. The Oracle docs warn that these functions help validation code but do not replace it.
Example 7: Run a dynamic PL/SQL block
EXECUTE IMMEDIATE can also run an anonymous PL/SQL block, for example to call a procedure whose name is decided at run time. Here the string must end with END; including the semicolon, because that is part of PL/SQL syntax.
DECLARE
v_total NUMBER := 10;
BEGIN
EXECUTE IMMEDIATE 'BEGIN :n := :n * 2; END;'
USING IN OUT v_total;
DBMS_OUTPUT.PUT_LINE('v_total = ' || v_total);
END;
/v_total = 20
PL/SQL procedure successfully completed.Two things are different from a SQL statement. First, you can use OUT and IN OUT binds in USING, and the variable gets the new value back. Second, repeated placeholder names behave differently.
Repeated placeholders: SQL vs PL/SQL block
In a dynamic SQL statement, placeholders are matched by position, so a repeated name needs a repeated value. In a dynamic PL/SQL block or CALL statement, each unique name maps to one bind value. That is why :n appears twice above but v_total is passed only once.
-- SQL statement: :s appears twice, so pass the value twice
EXECUTE IMMEDIATE
'UPDATE employees SET salary = :s WHERE salary < :s'
USING v_floor, v_floor;
-- PL/SQL block: :n appears twice, pass it once
EXECUTE IMMEDIATE 'BEGIN :n := :n * 2; END;'
USING IN OUT v_total;Common mistakes and how to fix them
1. A semicolon at the end of a SQL string
EXECUTE IMMEDIATE 'DELETE FROM employees WHERE emp_id = 105;' fails, usually with ORA-00911: invalid character. Remove the semicolon from SQL strings. Keep it only for PL/SQL blocks, which must end in END;.
2. Writing NULL in the USING clause
The Oracle docs state that a bind argument cannot be the reserved word NULL, so writing USING NULL fails. Declare a variable, leave it unassigned (so it is NULL), and pass that instead.
DECLARE
v_null NUMBER; -- NULL by default
BEGIN
EXECUTE IMMEDIATE
'UPDATE employees SET salary = :s WHERE emp_id = :id'
USING v_null, 105;
END;
/3. Trying to bind a table or column name
Placeholders work only for values. For identifiers, validate the name and concatenate it, as shown in Example 6.
4. A SELECT with no INTO clause
If the dynamic statement is a SELECT and you leave out both INTO and BULK COLLECT INTO, the docs say the statement "never executes". For example, EXECUTE IMMEDIATE 'SELECT my_seq.NEXTVAL FROM dual' does not increment the sequence. You get no error, just nothing happening.
5. Building values into the string
Concatenating values causes SQL injection, quoting bugs with names like O'Brien, and date format problems that depend on NLS settings. It also creates a different statement text for each value, so Oracle hard parses each one. Bind values with USING.
6. ORA-00942 or ORA-01031 only inside a procedure
A dynamic statement can work in an anonymous block but fail inside a stored procedure. Definer's rights procedures do not use privileges granted through roles, and dynamic SQL is only checked at run time. Grant the privilege on the object directly to the procedure owner.
7. Debugging a string you cannot see
When a long dynamic statement fails, build it into a variable first, print it with DBMS_OUTPUT.PUT_LINE, and then run it. Most errors are obvious once you see the final text, such as a missing space between 'FROM employees' and 'WHERE'.
Performance tips and best practices
- Use static SQL when the statement is known at compile time. It is checked at compile time, records dependencies, and avoids the extra prepare step.
- Always use bind variables for values. The statement text stays the same, so Oracle can reuse the cursor in the shared pool instead of hard parsing each new value.
- Store the statement in a VARCHAR2 or CLOB variable before running it. You can log it, print it and reuse it in a loop.
- For many rows, prefer BULK COLLECT INTO, or OPEN FOR with FETCH ... LIMIT, over a row-by-row loop of EXECUTE IMMEDIATE calls.
- Use DBMS_SQL when the number or types of columns or binds are unknown until run time, for example a generic CSV export of any table.
- Keep DDL out of transactional code paths, because each DDL statement commits.
Frequently asked questions
What is EXECUTE IMMEDIATE in Oracle?
It is the PL/SQL statement that builds and runs a dynamic SQL statement or PL/SQL block in one step. You pass the statement as a string, bind values with USING, and collect results with INTO, BULK COLLECT INTO or RETURNING INTO.
Does EXECUTE IMMEDIATE commit automatically?
Not for DML. An INSERT, UPDATE or DELETE run through EXECUTE IMMEDIATE waits for your COMMIT or ROLLBACK, like static SQL. DDL is different. Oracle commits before and after every DDL statement, so dynamic CREATE, ALTER, DROP or TRUNCATE commits the open transaction.
Can I use COMMIT inside EXECUTE IMMEDIATE?
You can, with EXECUTE IMMEDIATE 'COMMIT', but there is no reason to. A plain COMMIT statement works directly in PL/SQL and is clearer.
How do I use EXECUTE IMMEDIATE with an INTO variable?
Write the INTO clause before USING: EXECUTE IMMEDIATE 'SELECT salary FROM employees WHERE emp_id = :1' INTO v_sal USING v_id; The query must return exactly one row, or you get NO_DATA_FOUND or TOO_MANY_ROWS.
What is the difference between EXECUTE IMMEDIATE and DBMS_SQL?
EXECUTE IMMEDIATE is simpler and, per the Oracle docs, runs noticeably faster. It needs you to know the number and types of inputs and outputs when you write the code. DBMS_SQL is a lower-level API that can describe and handle statements whose shape is only known at run time.
Summary
- Use EXECUTE IMMEDIATE only when static SQL cannot do the job: DDL, run-time table or column names, or truly dynamic WHERE clauses.
- Inputs go in USING, single-row results in INTO, many rows in BULK COLLECT INTO, DML results in RETURNING INTO.
- No semicolon at the end of a SQL string; PL/SQL block strings must end with END;
- Bind every value. Validate every identifier against the data dictionary and quote it with DBMS_ASSERT.ENQUOTE_NAME.
- Pass NULL through an unassigned variable, never the NULL keyword.
- Remember that dynamic DDL commits the current transaction.
- Print the final statement text when something fails.