Oracle Database Commands Guide: SQL*Plus, SQL, PL/SQL, RMAN and Data Pump Explained

Oracle Database 52 min readUpdated Oct 30, 2026
11 views0 comments

Oracle Database is one of the most powerful and widely used databases in the world, and also one of the most intimidating for newcomers. It has its own tools (SQL*Plus, RMAN, Data Pump, the listener), its own SQL dialect, its own programming language (PL/SQL) and a huge data dictionary. This guide walks through all of it in a logical order, explaining what each command does, why you would use it and what happens inside the database when you run it. It is aimed at people who administer or develop on Oracle, including the many SQL Server and MySQL users who suddenly have to support an Oracle system.

The commands work on Oracle Database 19c (the long-term release most companies run), 21c and 23ai, on Linux. Where something needs a newer version or an extra-cost option, the text says so. Examples use a small demo schema that you create in section 7, so you can follow along on a test database. The free Oracle Database Free edition and a Linux virtual machine (see our Linux commands guide for Red Hat) are enough to practise everything.

Be careful on real systems. Several commands here (SHUTDOWN, DROP, RESETLOGS, ALTER SYSTEM KILL SESSION) can interrupt users or destroy data. Practise on a test database, and on production always know your backup status first. Some features (AWR, ASH, Data Pump compression, partitioning) need extra licences: those are marked.

Contents

1. How Oracle is built: the ideas behind the commands

Almost every confusing thing in Oracle makes sense once you know a few concepts. Read this section once, and the commands will feel logical.

Instance and database are two different things

  • The database is the set of files on disk: the datafiles with your data, the control file, the redo logs.
  • The instance is the running software: a block of memory (the SGA) plus background processes. The instance opens the database and works with it.

That is why you can have a database (files) with no instance running, and why “start the database” is really “start the instance, then mount and open the files”.

Memory and processes

Part What it does
SGA (System Global Area) Shared memory. It holds the buffer cache (data blocks read from disk), the shared pool (parsed SQL and PL/SQL, dictionary data) and the redo log buffer
PGA (Program Global Area) Private memory of each session, used for sorting and joining
DBWn (database writer) Writes changed (“dirty”) blocks from the buffer cache to the datafiles, lazily, in the background
LGWR (log writer) Writes the redo log buffer to the online redo log files. It does this when you COMMIT
CKPT (checkpoint) Records how far the datafiles are up to date, so recovery after a crash starts at the right place
SMON, PMON System monitor (instance recovery at startup, cleanup) and process monitor (cleans up after sessions that died)
ARCn (archiver) Copies full redo logs to the archive destination when the database runs in ARCHIVELOG mode
Listener A separate program that accepts network connections on port 1521 and hands them to the instance

Redo and undo: the two logs that make Oracle safe

When you change a row, Oracle writes redo (a record of the change, used to repeat the work after a crash) and undo (the old version of the data, used to roll back your transaction and to show other users a consistent picture). Understanding the flow explains a lot:

  1. You UPDATE a row. The change happens in memory (the buffer cache), and redo and undo are generated.
  2. You COMMIT. LGWR writes the redo to disk and the commit returns. Your data is now safe, even though the datafile has not been written yet.
  3. Later, DBWn writes the changed blocks to the datafiles.
  4. If the server crashes in between, at the next startup SMON replays the redo (“roll forward”) and undoes uncommitted work (“roll back”). No committed data is lost.

Readers never block writers in Oracle: a query sees the data as it was when it started, rebuilding old versions from undo. If undo is too small for a long query, you get ORA-01555: snapshot too old.

The files

File Purpose
Datafiles (.dbf) The actual data, grouped into tablespaces
Control file(s) The database’s map: names and locations of all other files, backup information. Without it the database cannot be opened
Online redo logs Groups of files that LGWR writes in a circle
Archived redo logs Copies of filled redo logs, needed for point-in-time recovery
spfile / pfile The startup parameters (binary server parameter file, or a text file)
Password file Credentials for the administrative SYS users when connecting remotely
Alert log and trace files The database’s diary and diagnostics, under the “diag” directory

Multitenant: CDB and PDB

Since 12c, a database can be a container database (CDB) holding many pluggable databases (PDBs). The CDB has a root container (CDB$ROOT) and a seed (PDB$SEED); each PDB looks like an independent database with its own users and tablespaces. In 21c and later every database is a CDB. Your applications connect to a PDB, normally not to the root. Many beginner problems (“my user does not exist”, “I cannot create a normal user”) come from being connected to the wrong container.

Schema, user and service

In Oracle a user owns a schema: the set of objects (tables, views, procedures) that belong to it. They are the same thing, so hr.employees means “table employees in the schema of user hr“. Clients connect to a service name (such as ORCLPDB1), not to a database name.

2. The Linux environment and connecting

Oracle software is installed in an ORACLE_HOME directory. The operating system user that owns it is normally called oracle, and belongs to the group dba, which is what allows sqlplus / as sysdba to work without a password.

sudo su - oracle                          # switch to the oracle OS user
cat /etc/oratab                           # lists the instances: SID:ORACLE_HOME:autostart (Y/N)
. oraenv                                  # sets the environment for a SID (it asks for the SID)
echo $ORACLE_HOME $ORACLE_SID             # check

# or set them by hand (use your own paths and SID)
export ORACLE_HOME=/u01/app/oracle/product/19.0.0/dbhome_1
export ORACLE_SID=ORCL
export PATH=$ORACLE_HOME/bin:$PATH
export NLS_LANG=AMERICAN_AMERICA.AL32UTF8   # client character set; stops garbled accents

ps -ef | grep -E "pmon|tnslsnr" | grep -v grep   # is the instance (pmon) and the listener running?

If you see ora_pmon_ORCL, the instance exists. If you see tnslsnr, the listener is running.

Connecting with SQL*Plus

sqlplus / as sysdba                                   # local, operating-system authentication
sqlplus system/MyPassword@//localhost:1521/ORCLPDB1   # EZConnect: host:port/service
sqlplus hr@ORCLPDB1                                   # uses tnsnames.ora; asks for the password
sqlplus -s hr/pwd@ORCLPDB1 @report.sql                # -s = silent, runs a script
sqlplus /nolog                                        # starts without connecting, then: CONNECT user/pwd@service

Do not put passwords on the command line on a shared server: anyone can see them with ps. Leave the password out and SQL*Plus will ask for it, or use an Oracle wallet. Remember that sqlplus / as sysdba connects you to the root container of a CDB; to work in a PDB, either connect to its service name or run ALTER SESSION SET CONTAINER = ORCLPDB1; afterwards.

3. SQL*Plus commands

SQL*Plus is the classic command-line client. Some commands are SQL (run by the database, end with ;) and some are SQL*Plus commands (handled by the tool itself, no semicolon needed). Knowing the difference avoids confusion.

SHOW USER                          -- who am I connected as?
SHOW CON_NAME                      -- which container (CDB$ROOT or a PDB)?
SHOW PDBS                          -- list pluggable databases (from the root)
SHOW PARAMETER sga                 -- parameters whose name contains "sga"
SHOW ERRORS                        -- compilation errors of the last PL/SQL object
DESCRIBE employees                 -- columns and types of a table (short: DESC employees)
SET LINESIZE 200                   -- line width; the default (80) makes tables wrap and look broken
SET PAGESIZE 100                   -- rows between headings (0 = no headings at all)
SET TIMING ON                      -- show how long each statement took
SET SERVEROUTPUT ON SIZE UNLIMITED -- show DBMS_OUTPUT.PUT_LINE output
SET FEEDBACK OFF                   -- hide "3 rows selected"
SET MARKUP CSV ON                  -- print results as CSV (12.2 and later), good with SPOOL
COLUMN last_name FORMAT A20        -- width of a text column
COLUMN salary FORMAT 999,990.00    -- number format
SPOOL result.txt                   -- copy all output to a file...
SPOOL OFF                          -- ...until you stop
@script.sql                        -- run a script (same as START script.sql)
@?/rdbms/admin/utlrp.sql           -- "?" means ORACLE_HOME
HOST ls -l                         -- run an operating-system command (or: !ls -l)
DEFINE dept = 30                   -- a substitution variable; use it as &dept in a statement
ACCEPT who PROMPT 'Name: '         -- ask the user for input
/                                  -- run the statement that is in the buffer again
LIST                               -- show the buffer;  EDIT opens it in an editor
CLEAR SCREEN
EXIT                               -- leave (it commits an open transaction by default!)

Put your favourite SET commands in $ORACLE_HOME/sqlplus/admin/glogin.sql (for everybody) or login.sql in the folder where you start SQL*Plus. The statement buffer holds only the most recent SQL statement. A PL/SQL block or a statement spread over several lines is ended with a semicolon (SQL) or a line with a single / (PL/SQL).

A tip for readable output: ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';. By default Oracle shows dates as 30-OCT-26 and hides the time, even though a DATE always contains one. For a modern client with history and auto-complete, Oracle also offers SQLcl (sql), which accepts the same commands.

4. Starting, stopping and the multitenant containers

An instance goes through three stages when it starts. Each stage reads more of the database:

Stage What happens Use it for
NOMOUNT The instance starts: it reads the parameter file, allocates the SGA and starts the background processes. No database files are opened Creating a database, restoring a lost control file
MOUNT The instance opens the control file and learns where all the files are Turning ARCHIVELOG on, restoring datafiles, renaming files, enabling flashback
OPEN Datafiles and redo logs are opened. Users can connect. If needed, crash recovery runs here Normal operation
sqlplus / as sysdba

STARTUP;                          -- all three stages in one go
STARTUP NOMOUNT;                  -- stop at stage 1
ALTER DATABASE MOUNT;             -- move to stage 2
ALTER DATABASE OPEN;              -- move to stage 3
STARTUP MOUNT;                    -- start straight to stage 2
STARTUP FORCE;                    -- SHUTDOWN ABORT then STARTUP: a quick restart of a stuck instance
ALTER DATABASE OPEN READ ONLY;    -- open without allowing changes

Shutting down: choose the right mode

Command New connections Running sessions When
SHUTDOWN NORMAL Refused Waits until every user disconnects (may wait forever) Rarely
SHUTDOWN TRANSACTIONAL Refused Waits for open transactions to finish, then disconnects Polite shutdown
SHUTDOWN IMMEDIATE Refused Rolls back open transactions and disconnects everyone The normal choice: the database is consistent, no recovery needed at the next start
SHUTDOWN ABORT Refused Kills the instance at once, like pulling the power cable Emergency. The next start does crash recovery (usually fine, but not a habit)

SHUTDOWN IMMEDIATE can take minutes if a big transaction has to roll back. Be patient and watch the alert log instead of switching to ABORT. A clean shutdown is also needed before you copy database files at the operating-system level.

ALTER SYSTEM CHECKPOINT;           -- force dirty blocks to the datafiles now
ALTER SYSTEM SWITCH LOGFILE;       -- move to the next redo log (and archive the old one)
SELECT status FROM v$instance;     -- STARTED, MOUNTED, OPEN

Containers: starting and entering pluggable databases

SHOW CON_NAME                                   -- CDB$ROOT
SELECT name, open_mode FROM v$pdbs;             -- MOUNTED means closed; READ WRITE means open
ALTER PLUGGABLE DATABASE ORCLPDB1 OPEN;
ALTER PLUGGABLE DATABASE ALL OPEN;
ALTER PLUGGABLE DATABASE ORCLPDB1 SAVE STATE;   -- reopen automatically after the CDB restarts
ALTER PLUGGABLE DATABASE ORCLPDB1 CLOSE IMMEDIATE;
ALTER SESSION SET CONTAINER = ORCLPDB1;         -- switch into the PDB
ALTER SESSION SET CONTAINER = CDB$ROOT;         -- and back

Without SAVE STATE, a PDB stays in MOUNTED after every restart of the CDB, a very common reason why “the application cannot connect after the reboot”.

5. Users, roles, privileges and profiles

Everything in Oracle is controlled by privileges. A system privilege allows an action (CREATE TABLE); an object privilege allows an action on one object (SELECT ON hr.employees). A role is a named bundle of privileges that you can give to many users.

-- Work inside your PDB, not in the root
ALTER SESSION SET CONTAINER = ORCLPDB1;

CREATE USER app_owner IDENTIFIED BY "Str0ng#Passw0rd"
  DEFAULT TABLESPACE users
  TEMPORARY TABLESPACE temp
  QUOTA 500M ON users;

GRANT CREATE SESSION, CREATE TABLE, CREATE VIEW, CREATE SEQUENCE, CREATE PROCEDURE, CREATE TRIGGER TO app_owner;

Two details beginners miss. First, a new user cannot even log in until you grant CREATE SESSION. Second, without a quota on a tablespace the user cannot store data (ORA-01950: no privileges on tablespace). Since 12.2, passwords are case-sensitive; put the password in double quotes if it has special characters.

Managing accounts

ALTER USER app_owner IDENTIFIED BY "N3w#Passw0rd";        -- change the password
ALTER USER app_owner ACCOUNT UNLOCK;                      -- after too many failed logins
ALTER USER app_owner ACCOUNT LOCK;
ALTER USER app_owner PASSWORD EXPIRE;                     -- must change it at the next login
ALTER USER app_owner QUOTA UNLIMITED ON users;
ALTER USER app_owner DEFAULT TABLESPACE app_data;
DROP USER app_owner CASCADE;                              -- also deletes every object the user owns!

Privileges and roles

GRANT SELECT, INSERT, UPDATE ON app_owner.employees TO bob;          -- object privileges
GRANT SELECT ON app_owner.employees TO bob WITH GRANT OPTION;         -- bob may pass it on
REVOKE INSERT ON app_owner.employees FROM bob;

CREATE ROLE reporting;
GRANT SELECT ON app_owner.employees   TO reporting;
GRANT SELECT ON app_owner.departments TO reporting;
GRANT reporting TO bob, alice;                                        -- give the bundle to people
GRANT CREATE SESSION TO reporting;

GRANT DBA TO admin_user;                                              -- a powerful built-in role: use rarely
ALTER USER bob DEFAULT ROLE ALL;

Privileges received through a role do not work inside stored PL/SQL procedures; they need direct grants (or AUTHID CURRENT_USER). The old RESOURCE role gives broad rights and should not be used for new applications; grant the exact CREATE privileges instead. In a CDB, a user created in the root must be a common user whose name starts with C## (CREATE USER c##admin IDENTIFIED BY "..." CONTAINER = ALL;); ordinary application users are created inside the PDB.

Profiles: password and resource rules

CREATE PROFILE app_profile LIMIT
  FAILED_LOGIN_ATTEMPTS 5
  PASSWORD_LOCK_TIME 1                -- days locked after 5 failures
  PASSWORD_LIFE_TIME 90
  PASSWORD_REUSE_MAX 5
  IDLE_TIME 30;                       -- minutes of inactivity before the session is ended
ALTER USER app_owner PROFILE app_profile;

The password-complexity function itself is set up with the script utlpwdmg.sql and the profile parameter PASSWORD_VERIFY_FUNCTION. Note that IDLE_TIME only takes effect when RESOURCE_LIMIT is true (the default in recent versions).

Who has what?

SELECT username, account_status, default_tablespace, profile, created, last_login FROM dba_users ORDER BY created;
SELECT grantee, privilege FROM dba_sys_privs WHERE grantee = 'APP_OWNER';
SELECT grantee, owner, table_name, privilege FROM dba_tab_privs WHERE grantee = 'BOB';
SELECT grantee, granted_role FROM dba_role_privs WHERE grantee = 'BOB';
SELECT * FROM session_privs;                -- everything I can do right now
SELECT grantee FROM dba_role_privs WHERE granted_role = 'DBA';   -- who are the DBAs?

SYS and SYSTEM are internal accounts. SYS owns the data dictionary: never create your own objects in it, and never use it for applications. Use named accounts for administrators, and the least privilege that works.

6. Tablespaces and datafiles

Logical storage is organised into tablespaces; each is made of one or more physical datafiles. Objects (tables, indexes) are stored as segments inside tablespaces, made of extents, made of blocks (normally 8 KB). A few tablespaces always exist: SYSTEM and SYSAUX (Oracle’s own data), UNDO (undo data), TEMP (sorting and temporary results) and USERS (a default for user data).

-- A tablespace for application data that grows by itself, up to a limit
CREATE TABLESPACE app_data
  DATAFILE '/u02/oradata/ORCL/ORCLPDB1/app_data01.dbf' SIZE 1G
  AUTOEXTEND ON NEXT 256M MAXSIZE 20G;

ALTER TABLESPACE app_data ADD DATAFILE '/u02/oradata/ORCL/ORCLPDB1/app_data02.dbf' SIZE 1G AUTOEXTEND ON NEXT 256M MAXSIZE 20G;
ALTER DATABASE DATAFILE '/u02/oradata/ORCL/ORCLPDB1/app_data01.dbf' RESIZE 4G;
ALTER DATABASE DATAFILE '/u02/oradata/ORCL/ORCLPDB1/app_data01.dbf' AUTOEXTEND ON NEXT 512M MAXSIZE 30G;

CREATE TEMPORARY TABLESPACE temp2 TEMPFILE '/u02/oradata/ORCL/ORCLPDB1/temp02.dbf' SIZE 2G AUTOEXTEND ON;
CREATE UNDO TABLESPACE undotbs2 DATAFILE '/u02/oradata/ORCL/undotbs02.dbf' SIZE 2G;   -- then ALTER SYSTEM SET UNDO_TABLESPACE = undotbs2;

ALTER TABLESPACE app_data OFFLINE NORMAL;            -- take it out of use (and back: ONLINE)
ALTER DATABASE MOVE DATAFILE '/old/path/app_data01.dbf' TO '/new/path/app_data01.dbf';   -- moves it while the database is open (12c and later)
DROP TABLESPACE app_data INCLUDING CONTENTS AND DATAFILES;   -- destroys the data and deletes the files

If you use Oracle-managed files (db_create_file_dest is set), you can leave out the file name: CREATE TABLESPACE app_data DATAFILE SIZE 1G AUTOEXTEND ON;. Use ALTER DATABASE DATAFILE ... RESIZE to grow or shrink a file, and remember that a file can only shrink down to the last used block.

How full is it?

-- The reliable view: it takes autoextend and maximum sizes into account
SELECT tablespace_name, ROUND(used_percent, 1) AS used_pct FROM dba_tablespace_usage_metrics ORDER BY used_percent DESC;

SELECT tablespace_name, file_name, ROUND(bytes/1024/1024) AS size_mb, autoextensible, ROUND(maxbytes/1024/1024) AS max_mb
FROM dba_data_files ORDER BY tablespace_name, file_name;

SELECT df.tablespace_name,
       ROUND(df.total_mb)                       AS total_mb,
       ROUND(df.total_mb - NVL(fs.free_mb, 0))  AS used_mb,
       ROUND(NVL(fs.free_mb, 0))                AS free_mb
FROM (SELECT tablespace_name, SUM(bytes)/1024/1024 total_mb FROM dba_data_files GROUP BY tablespace_name) df
LEFT JOIN (SELECT tablespace_name, SUM(bytes)/1024/1024 free_mb FROM dba_free_space GROUP BY tablespace_name) fs
       ON fs.tablespace_name = df.tablespace_name
ORDER BY 1;

-- The biggest objects
SELECT owner, segment_name, segment_type, ROUND(bytes/1024/1024) AS mb
FROM dba_segments ORDER BY bytes DESC FETCH FIRST 10 ROWS ONLY;

When a tablespace is full, inserts fail with ORA-01653: unable to extend table ... in tablespace. The fix is to add or enlarge a datafile, not to delete data you do not understand. Temporary space problems show up as ORA-01652; see which sessions use it with SELECT * FROM v$tempseg_usage;.

7. Tables, constraints, indexes and other objects

Create the demo schema now. It is small but has everything the later examples need: a parent table, a child table with foreign keys, an identity column and a manager hierarchy. Connect as the user you created (app_owner).

CREATE TABLE departments (
  department_id   NUMBER(4)     CONSTRAINT dept_pk PRIMARY KEY,
  department_name VARCHAR2(40)  NOT NULL
);

CREATE TABLE employees (
  employee_id    NUMBER GENERATED BY DEFAULT AS IDENTITY CONSTRAINT emp_pk PRIMARY KEY,
  first_name     VARCHAR2(40)   NOT NULL,
  last_name      VARCHAR2(40)   NOT NULL,
  email          VARCHAR2(100)  CONSTRAINT emp_email_uk UNIQUE,
  hire_date      DATE           DEFAULT SYSDATE NOT NULL,
  salary         NUMBER(10,2)   CONSTRAINT emp_salary_ck CHECK (salary > 0),
  department_id  NUMBER(4)      CONSTRAINT emp_dept_fk REFERENCES departments (department_id),
  manager_id     NUMBER         CONSTRAINT emp_mgr_fk REFERENCES employees (employee_id)
);

What the pieces mean: NUMBER(10,2) is up to ten digits in total with two after the decimal point; VARCHAR2 is Oracle’s text type (always use it instead of VARCHAR); GENERATED BY DEFAULT AS IDENTITY (12c and later) creates an automatic number, and ALWAYS would forbid supplying your own value. Naming constraints (CONSTRAINT emp_pk) is wise: otherwise Oracle invents names like SYS_C0012345 that tell you nothing in an error message. Load sample data:

INSERT INTO departments VALUES (10, 'Administration');
INSERT INTO departments VALUES (20, 'Sales');
INSERT INTO departments VALUES (30, 'IT');

INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, salary, department_id, manager_id) VALUES (1, 'Sara',    'Alami',     'sara.alami@example.com',     DATE '2020-03-01', 9000, 10, NULL);
INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, salary, department_id, manager_id) VALUES (2, 'Omar',    'Benali',    'omar.benali@example.com',    DATE '2021-06-15', 6500, 20, 1);
INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, salary, department_id, manager_id) VALUES (3, 'Lina',    'Cherkaoui', 'lina.cherkaoui@example.com', DATE '2022-01-10', 5200, 20, 2);
INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, salary, department_id, manager_id) VALUES (4, 'Youssef', 'Daoudi',    'youssef.daoudi@example.com', DATE '2019-09-23', 7800, 30, 1);
INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, salary, department_id, manager_id) VALUES (5, 'Nora',    'Fassi',     'nora.fassi@example.com',     DATE '2023-04-03', 4800, 30, 4);
INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, salary, department_id, manager_id) VALUES (6, 'Hamza',   'Idrissi',   'hamza.idrissi@example.com',  DATE '2024-02-12', 4500, 30, 4);
COMMIT;

A DATE literal like DATE '2020-03-01' is the safest way to write a date: it does not depend on session settings. Note also that Oracle does not allow a row to be inserted before its parent exists: that is the foreign key at work.

Changing a table

ALTER TABLE employees ADD (phone VARCHAR2(20));
ALTER TABLE employees MODIFY (first_name VARCHAR2(80));
ALTER TABLE employees RENAME COLUMN phone TO mobile;
ALTER TABLE employees DROP COLUMN mobile;
ALTER TABLE employees ADD CONSTRAINT emp_name_uk UNIQUE (first_name, last_name);
ALTER TABLE employees DISABLE CONSTRAINT emp_name_uk;   -- ENABLE CONSTRAINT to turn it back on
ALTER TABLE employees DROP CONSTRAINT emp_name_uk;
COMMENT ON TABLE employees IS 'People who work here';
COMMENT ON COLUMN employees.salary IS 'Monthly gross salary';
ALTER TABLE employees RENAME TO staff;                  -- renaming keeps data, indexes and grants; code that used the old name breaks
ALTER TABLE staff RENAME TO employees;                  -- and back

Reducing a column’s size only works if all values still fit. Adding a NOT NULL column with a default to a big table is fast in modern versions, because Oracle stores the default in the dictionary instead of rewriting every row.

Indexes

An index is a sorted structure that lets Oracle find rows without reading the whole table. The default is a B-tree index. Oracle creates indexes automatically for primary key and unique constraints, but not for foreign keys: index them yourself, or deletes on the parent table will lock the child.

CREATE INDEX emp_dept_ix ON employees (department_id);                       -- foreign key column
CREATE UNIQUE INDEX emp_lastname_ux ON employees (last_name, first_name);
CREATE INDEX emp_upper_last_ix ON employees (UPPER(last_name));              -- function-based: speeds up WHERE UPPER(last_name) = 'ALAMI'
CREATE INDEX big_ix ON employees (hire_date) ONLINE;                         -- build without blocking changes (Enterprise Edition)

ALTER INDEX emp_dept_ix REBUILD ONLINE;                                      -- rebuild (rarely needed)
ALTER INDEX emp_dept_ix INVISIBLE;                                           -- the optimizer ignores it; a safe way to test dropping it
ALTER INDEX emp_dept_ix VISIBLE;
DROP INDEX emp_dept_ix;

Bitmap indexes (CREATE BITMAP INDEX ..., Enterprise Edition) suit columns with few distinct values in reporting databases, but not busy transactional tables. Indexes speed up reads and slow down writes, because every insert or update must maintain them. Index what you search and join on, not every column. A query such as WHERE TO_CHAR(hire_date,'YYYY') = '2024' cannot use a normal index on hire_date, because the function hides the column. Write it as a range instead: WHERE hire_date >= DATE '2024-01-01' AND hire_date < DATE '2025-01-01'.

Sequences, views, synonyms and temporary tables

CREATE SEQUENCE order_seq START WITH 1 INCREMENT BY 1 CACHE 100;   -- the older way to make numbers
SELECT order_seq.NEXTVAL FROM dual;                                -- next number
SELECT order_seq.CURRVAL FROM dual;                                -- the last one given to THIS session

CREATE OR REPLACE VIEW it_staff AS
  SELECT employee_id, first_name, last_name, salary FROM employees WHERE department_id = 30;

CREATE MATERIALIZED VIEW dept_totals
  BUILD IMMEDIATE REFRESH COMPLETE ON DEMAND AS
  SELECT department_id, COUNT(*) AS staff, SUM(salary) AS payroll FROM employees GROUP BY department_id;
EXEC DBMS_MVIEW.REFRESH('DEPT_TOTALS');                            -- recalculate when you want

CREATE SYNONYM emp FOR app_owner.employees;                        -- a short name for an object
CREATE PUBLIC SYNONYM emp FOR app_owner.employees;                 -- visible to everybody (needs privilege)

CREATE GLOBAL TEMPORARY TABLE work_list (id NUMBER) ON COMMIT DELETE ROWS;   -- structure is permanent, rows are private to each session

A materialized view stores the result of a query, like a saved snapshot, and is refreshed when you ask or on a schedule: ideal for expensive report queries. dual is Oracle’s built-in one-row table for evaluating expressions (23ai also allows SELECT 1 + 1; without it).

Dropping and getting it back

DROP TABLE employees_copy;                   -- goes to the recycle bin (if enabled), not gone yet
SHOW RECYCLEBIN
FLASHBACK TABLE employees_copy TO BEFORE DROP;   -- undelete it
DROP TABLE employees_copy PURGE;             -- really delete, no way back
PURGE RECYCLEBIN;                            -- empty your recycle bin
TRUNCATE TABLE work_list;                    -- delete all rows instantly; cannot be rolled back

TRUNCATE and all other DDL statements (CREATE, ALTER, DROP) end with an implicit commit in Oracle: you cannot roll them back.

8. Changing data and transactions

INSERT INTO departments (department_id, department_name) VALUES (40, 'Finance');

INSERT INTO employees_archive SELECT * FROM employees WHERE hire_date < DATE '2020-01-01';   -- copy rows (the table must exist)

INSERT ALL                                                       -- several rows in one statement
  INTO departments VALUES (50, 'Legal')
  INTO departments VALUES (60, 'Support')
SELECT 1 FROM dual;

UPDATE employees SET salary = salary * 1.05 WHERE department_id = 30;
DELETE FROM employees WHERE employee_id = 6;

MERGE INTO departments d                                         -- "upsert": update if it exists, insert if not
USING (SELECT 30 AS id, 'Information Technology' AS name FROM dual) s
ON (d.department_id = s.id)
WHEN MATCHED THEN UPDATE SET d.department_name = s.name
WHEN NOT MATCHED THEN INSERT (department_id, department_name) VALUES (s.id, s.name);

Always write the WHERE clause first, and test it with a SELECT before you turn it into an UPDATE or DELETE. An UPDATE without WHERE changes every row.

Transactions

A transaction is a group of changes that succeed or fail together. In Oracle a transaction starts with your first change and ends with COMMIT or ROLLBACK. SQL*Plus does not commit automatically (unless a DDL statement runs or you exit normally), which surprises people coming from other databases: your changes are invisible to others until you commit.

UPDATE employees SET salary = salary + 100 WHERE employee_id = 2;
SAVEPOINT after_raise;                       -- a bookmark inside the transaction
UPDATE employees SET salary = 0 WHERE employee_id = 2;     -- oops
ROLLBACK TO after_raise;                     -- undo only back to the bookmark
COMMIT;                                      -- make the rest permanent (or ROLLBACK; to undo everything)

SELECT * FROM employees WHERE department_id = 30 FOR UPDATE;             -- lock these rows while you decide
SELECT * FROM employees WHERE employee_id = 2 FOR UPDATE NOWAIT;        -- fail at once if somebody else holds the lock
SELECT * FROM employees WHERE employee_id = 2 FOR UPDATE SKIP LOCKED;    -- skip locked rows (handy for work queues)
SET TRANSACTION READ ONLY;                   -- see one consistent snapshot until the next commit

An uncommitted change holds a row lock. If a colleague goes to lunch without committing, anyone else who tries to change the same row waits. Hunting down such sessions is a classic DBA task: see section 12.

9. Querying data

The basics and Oracle’s differences

SELECT first_name, last_name, salary FROM employees WHERE department_id = 30 ORDER BY salary DESC;

SELECT * FROM employees ORDER BY salary DESC FETCH FIRST 3 ROWS ONLY;                   -- top 3 (12c and later)
SELECT * FROM employees ORDER BY employee_id OFFSET 2 ROWS FETCH NEXT 2 ROWS ONLY;     -- paging: skip 2, take 2
SELECT * FROM (SELECT * FROM employees ORDER BY salary DESC) WHERE ROWNUM <= 3;       -- the pre-12c way

SELECT SYSDATE, SYSTIMESTAMP, USER FROM dual;
SELECT COUNT(*), COUNT(email), MIN(hire_date), MAX(salary), ROUND(AVG(salary), 2) FROM employees;

Two Oracle peculiarities to remember. An empty string is NULL: WHERE name = '' never matches anything; use IS NULL. And comparing anything with NULL gives “unknown”, so WHERE x = NULL never works either: always write IS NULL or IS NOT NULL. ROWNUM is assigned before ORDER BY, which is why the old top-N pattern needs a subquery; prefer FETCH FIRST.

NULL handling and conditions

SELECT NVL(manager_id, 0) FROM employees;                         -- replace NULL with 0
SELECT NVL2(manager_id, 'has boss', 'top') FROM employees;        -- one value if not null, another if null
SELECT COALESCE(mobile, phone, 'n/a') FROM contacts;              -- first non-null value (standard SQL)
SELECT NULLIF(a, b) FROM t;                                       -- NULL when a equals b (avoids divide by zero)

SELECT last_name,
       CASE WHEN salary >= 7000 THEN 'high' WHEN salary >= 5000 THEN 'medium' ELSE 'low' END AS band
FROM employees;
SELECT DECODE(department_id, 10, 'Admin', 20, 'Sales', 'Other') FROM employees;     -- older Oracle-only form of CASE

Text, number and date functions

SELECT first_name || ' ' || last_name AS full_name FROM employees;     -- || joins text (CONCAT takes only two arguments)
SELECT UPPER(last_name), LOWER(last_name), INITCAP('john smith'), LENGTH(last_name) FROM employees;
SELECT SUBSTR('Oracle Database', 1, 6), INSTR('Oracle Database', 'Data'), REPLACE('a-b-c', '-', '/') FROM dual;   -- Oracle, 8, a/b/c
SELECT LPAD('7', 3, '0'), RPAD('ab', 5, '*'), TRIM('  hi  '), LTRIM('xxhi', 'x') FROM dual;                       -- 007, ab***, hi, hi
SELECT REGEXP_SUBSTR(email, '[^@]+$') AS domain FROM employees;        -- regular expressions: REGEXP_LIKE, REGEXP_REPLACE too
SELECT ROUND(123.456, 1), TRUNC(123.456, 1), MOD(10, 3), CEIL(4.1), FLOOR(4.9), ABS(-5) FROM dual;

SELECT ADD_MONTHS(SYSDATE, 3), LAST_DAY(SYSDATE), TRUNC(SYSDATE), TRUNC(SYSDATE, 'MM'), SYSDATE - 7 FROM dual;   -- date arithmetic is in days
SELECT MONTHS_BETWEEN(SYSDATE, hire_date) / 12 AS years_here FROM employees;
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'), TO_CHAR(hire_date, 'DD Month YYYY'), TO_CHAR(salary, 'FM999,990.00') FROM employees;
SELECT TO_DATE('30/10/2026', 'DD/MM/YYYY'), TO_NUMBER('1234.5'), TO_TIMESTAMP('2026-10-30 14:30', 'YYYY-MM-DD HH24:MI') FROM dual;
SELECT EXTRACT(YEAR FROM hire_date), SYSDATE + INTERVAL '2' HOUR, SYSTIMESTAMP + INTERVAL '1' DAY FROM employees;

Always give TO_DATE and TO_CHAR an explicit format. Without one, Oracle uses the session setting, and the same code will work on your laptop and fail on the server (ORA-01843 or ORA-01861).

Joins, grouping and sets

SELECT e.last_name, d.department_name
FROM employees e
JOIN departments d ON d.department_id = e.department_id;             -- inner join

SELECT d.department_name, COUNT(e.employee_id) AS staff           -- LEFT JOIN keeps departments with no employees
FROM departments d
LEFT JOIN employees e ON e.department_id = d.department_id
GROUP BY d.department_name
HAVING COUNT(e.employee_id) <= 2                                  -- HAVING filters groups; WHERE filters rows
ORDER BY staff DESC;

SELECT department_id FROM employees
UNION SELECT department_id FROM departments;                      -- UNION removes duplicates; UNION ALL keeps them
SELECT department_id FROM departments
MINUS SELECT department_id FROM employees;                        -- departments with no staff (INTERSECT also exists)

SELECT department_id, LISTAGG(last_name, ', ') WITHIN GROUP (ORDER BY last_name) AS people
FROM employees GROUP BY department_id;                            -- one text line per group

Oracle also accepts the old comma-join style with (+) for outer joins. You will see it in older code; write new queries with the standard JOIN ... ON.

Subqueries, WITH and analytic functions

SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);                 -- who earns above average?
SELECT * FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department_id = d.department_id);

WITH dept_pay AS (                                                    -- a named, reusable subquery
  SELECT department_id, SUM(salary) AS payroll FROM employees GROUP BY department_id
)
SELECT d.department_name, p.payroll FROM dept_pay p JOIN departments d ON d.department_id = p.department_id;

SELECT last_name, department_id, salary,
       ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn,       -- 1, 2, 3 inside each department
       RANK()       OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk,
       SUM(salary)  OVER (PARTITION BY department_id) AS dept_total,
       LAG(salary)  OVER (ORDER BY hire_date) AS previous_hire_salary
FROM employees;

Analytic functions (the ones with OVER) calculate across related rows without collapsing them like GROUP BY does. They solve “top N per group”, running totals and “compare with the previous row” in one pass. For the top earner per department, wrap the query and filter WHERE rn = 1.

Hierarchies: CONNECT BY

SELECT LEVEL, LPAD(' ', 2 * (LEVEL - 1)) || last_name AS org_chart
FROM employees
START WITH manager_id IS NULL                  -- begin at the top
CONNECT BY PRIOR employee_id = manager_id      -- children are the rows whose manager is the parent
ORDER SIBLINGS BY last_name;

This walks the manager tree and indents each level. It is one of Oracle’s best-loved features. (Standard recursive WITH queries also work.)

10. The data dictionary: asking Oracle about itself

Oracle describes itself through read-only views. Learn the naming and you can find out almost anything:

Prefix Shows Example
USER_ Objects you own user_tables
ALL_ Objects you can access all_tab_columns
DBA_ Everything (needs privilege) dba_users
CDB_ Everything, in every container (from the root) cdb_tablespaces
V$ (and GV$ for RAC) Live performance data kept in memory v$session
SELECT instance_name, version_full, status, startup_time, host_name FROM v$instance;      -- version_full: 18c and later
SELECT name, db_unique_name, open_mode, log_mode, cdb, created FROM v$database;           -- log_mode: ARCHIVELOG or NOARCHIVELOG
SELECT banner_full FROM v$version;                                                         -- the exact version and patch level
SELECT con_id, name, open_mode FROM v$containers;

SELECT table_name, num_rows, last_analyzed FROM user_tables;
SELECT column_name, data_type, data_length, nullable FROM user_tab_columns WHERE table_name = 'EMPLOYEES' ORDER BY column_id;
SELECT constraint_name, constraint_type, search_condition FROM user_constraints WHERE table_name = 'EMPLOYEES';   -- P key, R foreign key, U unique, C check
SELECT index_name, uniqueness, status FROM user_indexes WHERE table_name = 'EMPLOYEES';
SELECT object_name, object_type, status FROM user_objects WHERE status = 'INVALID';        -- code that needs recompiling
SET LONG 100000                                                                            -- or long text such as DDL is cut off
SELECT DBMS_METADATA.GET_DDL('TABLE', 'EMPLOYEES') FROM dual;                              -- the CREATE statement of an existing object

SELECT name FROM v$datafile;  SELECT name FROM v$tempfile;  SELECT member FROM v$logfile;  SELECT name FROM v$controlfile;
SELECT * FROM v$diag_info;                                                                 -- where the alert log and trace files are

Names in the dictionary are stored in upper case unless you created them with double quotes, which is why you filter on table_name = 'EMPLOYEES'. Avoid quoted lower-case names in your own objects: you would have to quote them forever.

11. Parameters and memory

The behaviour of the instance is controlled by initialisation parameters, stored in the binary spfile. You change them with ALTER SYSTEM, and the SCOPE says where the change goes:

SCOPE Meaning
MEMORY Takes effect now, lost at the next restart
SPFILE Saved for the next restart only (required for “static” parameters)
BOTH Now and after restarts (the default when an spfile is in use)
SHOW PARAMETER processes
SELECT name, value, isdefault, issys_modifiable FROM v$parameter WHERE name IN ('sga_target', 'pga_aggregate_target', 'processes', 'sessions', 'open_cursors');

ALTER SYSTEM SET open_cursors = 500 SCOPE = BOTH;                  -- dynamic: works immediately
ALTER SYSTEM SET processes = 600 SCOPE = SPFILE;                   -- static: needs a restart
ALTER SYSTEM SET sga_target = 6G SCOPE = BOTH;
ALTER SYSTEM SET pga_aggregate_target = 2G SCOPE = BOTH;
ALTER SYSTEM RESET open_cursors SCOPE = SPFILE;                    -- go back to the default

CREATE PFILE = '/tmp/init_backup.ora' FROM SPFILE;                 -- a readable text copy: always make one before big changes
CREATE SPFILE FROM PFILE = '/tmp/init_backup.ora';                 -- rebuild the spfile from it (instance down)

Memory in short: the SGA (shared) and PGA (private per session) share the server’s RAM with the operating system. Leave RAM for Linux, and do not set sga_target plus pga_aggregate_target larger than about 60 to 70 percent of the machine on a dedicated database server. Setting memory_target (Automatic Memory Management) is not compatible with Linux HugePages, so most production systems set the SGA and PGA targets separately and use HugePages. Wrong parameters are a common cause of a database that “will not start” after a change: if so, start with the pfile copy, STARTUP PFILE='/tmp/init_backup.ora';.

12. Sessions, locks and performance

Who is connected?

SELECT sid, serial#, username, status, machine, program, sql_id, event, seconds_in_wait, logon_time
FROM v$session WHERE type = 'USER' ORDER BY logon_time;

SELECT username, COUNT(*) FROM v$session WHERE type = 'USER' GROUP BY username ORDER BY 2 DESC;   -- connections per user
SELECT resource_name, current_utilization, max_utilization, limit_value FROM v$resource_limit WHERE resource_name IN ('processes', 'sessions');

SID and SERIAL# together identify a session (a SID can be reused, the serial number makes it unique). The column status shows ACTIVE (running something) or INACTIVE (connected but idle).

Blocking and killing

-- Who is waiting for whom?
SELECT sid, serial#, username, blocking_session, event, seconds_in_wait, sql_id
FROM v$session WHERE blocking_session IS NOT NULL;

-- Details about the blocker
SELECT sid, serial#, username, status, machine, program, prev_sql_id, last_call_et AS idle_seconds
FROM v$session WHERE sid = 123;                   -- the blocking_session value from above

ALTER SYSTEM KILL SESSION '123,4567' IMMEDIATE;   -- 'sid,serial#': ends the session and rolls back its transaction
ALTER SYSTEM DISCONNECT SESSION '123,4567' IMMEDIATE;   -- like KILL, but ends the server process right away, so resources are freed faster

Killing a session that has done a lot of work makes Oracle roll it back, and this can take as long as the original work did. Check first whether the blocker is simply a person who forgot to commit: contacting them is often better than a kill. If the session stays in KILLED status, it is cleaning up: leave it alone. In a PDB, run the query and the kill inside that PDB.

What is the database waiting for?

Oracle records what every session is waiting for, and the “wait interface” is the foundation of tuning: do not guess, see where time goes.

SELECT event, total_waits, ROUND(time_waited_micro / 1e6) AS seconds
FROM v$system_event WHERE wait_class <> 'Idle' ORDER BY time_waited_micro DESC FETCH FIRST 10 ROWS ONLY;

SELECT sql_id, executions, ROUND(elapsed_time / 1e6, 1) AS elapsed_s,
       ROUND(elapsed_time / NULLIF(executions, 0) / 1e6, 3) AS avg_s, buffer_gets, disk_reads, SUBSTR(sql_text, 1, 80) AS sql_text
FROM v$sql ORDER BY elapsed_time DESC FETCH FIRST 10 ROWS ONLY;      -- the statements that used the most time
Wait event Usually means
db file sequential read Reading single blocks (index lookups). High numbers mean slow storage or too many index reads
db file scattered read Full table scans
log file sync Waiting for commit to reach the redo log: slow redo disk, or committing after every single row
enq: TX - row lock contention One session waits for another’s uncommitted change
latch / library cache events Hard parsing: SQL without bind variables

Reading an execution plan

EXPLAIN PLAN FOR SELECT * FROM employees WHERE department_id = 30;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);                            -- the plan Oracle would use

-- The plan that was REALLY used, with actual row counts (run the query with the hint, then):
SELECT /*+ gather_plan_statistics */ COUNT(*) FROM employees WHERE department_id = 30;
SET SERVEROUTPUT OFF                                  -- needed, or DISPLAY_CURSOR shows the plan of the wrong statement
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));

SET AUTOTRACE TRACEONLY EXPLAIN STATISTICS                          -- plan and statistics for each statement you run in SQL*Plus
SET AUTOTRACE OFF

Read a plan from the most indented line inward. Look for TABLE ACCESS FULL on a big table where you expected an index, and for large differences between estimated rows (E-Rows) and actual rows (A-Rows): when they are far apart, the optimizer has bad statistics.

Optimizer statistics

The optimizer chooses plans using statistics about your data (row counts, distribution). Stale statistics produce bad plans. Oracle gathers them automatically at night, but you can do it by hand after a big load:

EXEC DBMS_STATS.GATHER_TABLE_STATS(ownname => 'APP_OWNER', tabname => 'EMPLOYEES', cascade => TRUE);
EXEC DBMS_STATS.GATHER_SCHEMA_STATS(ownname => 'APP_OWNER');
SELECT table_name, num_rows, last_analyzed, stale_stats FROM user_tab_statistics;

Two more habits that matter: use bind variables (WHERE id = :id) instead of building SQL with literal values, so Oracle can reuse the parsed statement and you avoid SQL injection; and do not commit after every row in a loop (log file sync waits add up).

Licence warning: the Automatic Workload Repository (awrrpt.sql), ASH and ADDM are part of the Diagnostics Pack, an extra-cost option of Enterprise Edition. Using them without a licence is a compliance risk. The free alternative is Statspack (@?/rdbms/admin/spcreate.sql). Check what you own before running @?/rdbms/admin/awrrpt.sql.

13. PL/SQL

PL/SQL is Oracle’s built-in programming language: SQL plus variables, loops, conditions and error handling, stored and executed inside the database. It runs close to the data, so it is fast for data-heavy logic. A program is made of blocks with three parts: DECLARE (variables), BEGIN (the code) and EXCEPTION (error handling), closed by END;. In SQL*Plus a block is run by a line with a single /.

SET SERVEROUTPUT ON

DECLARE
  v_count   PLS_INTEGER;
  v_name    employees.last_name%TYPE;                 -- same type as that column: survives column changes
BEGIN
  SELECT COUNT(*) INTO v_count FROM employees;
  DBMS_OUTPUT.PUT_LINE('Employees: ' || v_count);

  SELECT last_name INTO v_name FROM employees WHERE employee_id = 999;   -- no such row...
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('No such employee');          -- ...so this runs
  WHEN TOO_MANY_ROWS THEN
    DBMS_OUTPUT.PUT_LINE('More than one row');
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('Unexpected: ' || SQLERRM);
    RAISE;                                               -- pass the error on; do not hide it
END;
/

SELECT ... INTO must return exactly one row: zero rows raise NO_DATA_FOUND, two or more raise TOO_MANY_ROWS. Handle both, or use a cursor.

Control flow and cursors

BEGIN
  FOR r IN (SELECT employee_id, last_name, salary FROM employees WHERE department_id = 30) LOOP   -- the simplest cursor loop
    IF r.salary >= 7000 THEN
      DBMS_OUTPUT.PUT_LINE(r.last_name || ': high');
    ELSIF r.salary >= 5000 THEN
      DBMS_OUTPUT.PUT_LINE(r.last_name || ': medium');
    ELSE
      DBMS_OUTPUT.PUT_LINE(r.last_name || ': low');
    END IF;
  END LOOP;

  FOR i IN 1..3 LOOP DBMS_OUTPUT.PUT_LINE('Round ' || i); END LOOP;
END;
/

Procedures, functions and packages

CREATE OR REPLACE PROCEDURE raise_salary (p_employee_id IN NUMBER, p_percent IN NUMBER) AS
BEGIN
  IF p_percent NOT BETWEEN 0 AND 50 THEN
    RAISE_APPLICATION_ERROR(-20001, 'Percent must be between 0 and 50');   -- your own error, numbers -20000 to -20999
  END IF;
  UPDATE employees SET salary = salary * (1 + p_percent / 100) WHERE employee_id = p_employee_id;
  IF SQL%ROWCOUNT = 0 THEN                                                  -- how many rows did the last statement touch?
    RAISE_APPLICATION_ERROR(-20002, 'Employee not found');
  END IF;
END raise_salary;
/

CREATE OR REPLACE FUNCTION annual_pay (p_employee_id IN NUMBER) RETURN NUMBER AS
  v_salary employees.salary%TYPE;
BEGIN
  SELECT salary INTO v_salary FROM employees WHERE employee_id = p_employee_id;
  RETURN v_salary * 12;
END annual_pay;
/

EXEC raise_salary(2, 10);                              -- call a procedure
SELECT last_name, annual_pay(employee_id) FROM employees;      -- a function can be used in SQL
COMMIT;

A package groups related procedures, functions and variables into a specification (the public list) and a body (the code). It is the standard way to organise PL/SQL:

CREATE OR REPLACE PACKAGE hr_pkg AS
  PROCEDURE raise_salary (p_employee_id NUMBER, p_percent NUMBER);
  FUNCTION  annual_pay   (p_employee_id NUMBER) RETURN NUMBER;
END hr_pkg;
/
CREATE OR REPLACE PACKAGE BODY hr_pkg AS
  PROCEDURE raise_salary (p_employee_id NUMBER, p_percent NUMBER) IS
  BEGIN
    UPDATE employees SET salary = salary * (1 + p_percent / 100) WHERE employee_id = p_employee_id;
  END;
  FUNCTION annual_pay (p_employee_id NUMBER) RETURN NUMBER IS
    v_salary employees.salary%TYPE;
  BEGIN
    SELECT salary INTO v_salary FROM employees WHERE employee_id = p_employee_id;
    RETURN v_salary * 12;
  END;
END hr_pkg;
/

Triggers

CREATE TABLE salary_audit (employee_id NUMBER, old_salary NUMBER, new_salary NUMBER, changed_by VARCHAR2(30), changed_at DATE);

CREATE OR REPLACE TRIGGER emp_salary_audit
AFTER UPDATE OF salary ON employees
FOR EACH ROW                                            -- once per changed row
BEGIN
  INSERT INTO salary_audit VALUES (:OLD.employee_id, :OLD.salary, :NEW.salary, USER, SYSDATE);   -- :OLD and :NEW are the row before and after
END;
/

Triggers run invisibly, so use them sparingly (auditing, rules that must never be bypassed). Hidden logic makes systems hard to debug.

Bulk processing and compile errors

DECLARE
  TYPE t_ids IS TABLE OF employees.employee_id%TYPE;
  v_ids t_ids;
BEGIN
  SELECT employee_id BULK COLLECT INTO v_ids FROM employees WHERE department_id = 30;   -- fetch all rows in one call
  FORALL i IN 1 .. v_ids.COUNT                                                          -- update them in one call
    UPDATE employees SET salary = salary + 50 WHERE employee_id = v_ids(i);
  COMMIT;
END;
/

Looping and running one statement per row switches constantly between the PL/SQL and SQL engines. BULK COLLECT and FORALL do the same work with far fewer switches and are often ten times faster. If a procedure compiles with errors, SQL*Plus says “Warning: Procedure created with compilation errors”. Then run SHOW ERRORS (or SELECT * FROM user_errors;). To recompile everything that became invalid (for example after a patch): @?/rdbms/admin/utlrp.sql, or ALTER PROCEDURE raise_salary COMPILE;.

14. Scheduled jobs

Oracle has its own scheduler, DBMS_SCHEDULER, which is more capable than cron because it knows about the database (it survives restarts, logs its runs and can run on a calendar).

BEGIN
  DBMS_SCHEDULER.CREATE_JOB(
    job_name        => 'NIGHTLY_STATS',
    job_type        => 'PLSQL_BLOCK',
    job_action      => 'BEGIN DBMS_STATS.GATHER_SCHEMA_STATS(''APP_OWNER''); END;',
    start_date      => SYSTIMESTAMP,
    repeat_interval => 'FREQ=DAILY;BYHOUR=2;BYMINUTE=30',
    enabled         => TRUE,
    comments        => 'Refresh optimizer statistics at 02:30');
END;
/

EXEC DBMS_SCHEDULER.RUN_JOB('NIGHTLY_STATS');          -- run it now
EXEC DBMS_SCHEDULER.DISABLE('NIGHTLY_STATS');          -- and ENABLE
EXEC DBMS_SCHEDULER.DROP_JOB('NIGHTLY_STATS');

SELECT job_name, enabled, state, last_start_date, next_run_date FROM user_scheduler_jobs;
SELECT job_name, status, actual_start_date, run_duration, additional_info
FROM user_scheduler_job_run_details ORDER BY log_date DESC FETCH FIRST 10 ROWS ONLY;      -- did it work? why not?

Note the doubled single quotes inside the action: in a text value, one quote is written as two. The repeat interval uses a calendar syntax (FREQ=WEEKLY;BYDAY=MON,WED;BYHOUR=6). Oracle already runs maintenance jobs such as statistics gathering in the maintenance windows (DBA_AUTOTASK_CLIENT).

15. The listener and connection strings

The listener is a separate process. Clients connect to it, name a service, and the listener passes them to the instance that offers it. If the listener is down, existing sessions continue, but nobody new can connect.

lsnrctl status                  # is it running, on which port, and which services does it know?
lsnrctl start                   # start it
lsnrctl stop
lsnrctl reload                  # re-read listener.ora without dropping anyone
lsnrctl services                # detailed: each service, its handlers and the number of connections

tnsping ORCLPDB1                # can I reach the service from this machine? (tests names and the network, not the login)
ss -tulpn | grep 1521           # is something listening on the port? (Linux)

In lsnrctl status, look for your service name with the status READY. If it is missing or says BLOCKED or UNKNOWN, the database has not registered. Force registration with ALTER SYSTEM REGISTER;, and make sure the local_listener parameter points to the right host and port.

The configuration files

Both live in $ORACLE_HOME/network/admin (or the folder named by $TNS_ADMIN).

# listener.ora
LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = dbserver.example.com)(PORT = 1521))
    )
  )

# tnsnames.ora: a nickname for a connection
ORCLPDB1 =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = dbserver.example.com)(PORT = 1521))
    (CONNECT_DATA = (SERVICE_NAME = orclpdb1))
  )

With a tnsnames.ora entry you connect with sqlplus app_owner@ORCLPDB1. Without one, the EZConnect form is enough and needs no file: sqlplus app_owner@//dbserver.example.com:1521/orclpdb1. Always connect by SERVICE_NAME, not the old SID: with multitenant, each PDB has its own service. Open the port in the firewall (sudo firewall-cmd --permanent --add-port=1521/tcp, then --reload), and see our Linux guide for firewalld and SELinux details.

16. Backup, recovery and flashback

Everything in this section serves one rule: a backup is only real if you have restored it. Oracle offers three layers of protection: physical backups with RMAN, logical exports with Data Pump (next section) and “undo mistakes” tools called Flashback.

Step 1: ARCHIVELOG mode

In the default NOARCHIVELOG mode, Oracle overwrites old redo logs, so you can only restore the database to the exact moment of a cold backup. In ARCHIVELOG mode, every filled redo log is saved, which allows hot backups (while users work) and recovery to any point in time. Every production database needs it.

ARCHIVE LOG LIST;                                          -- current mode, destination, sequence numbers
SELECT log_mode FROM v$database;

SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
ALTER DATABASE ARCHIVELOG;
ALTER DATABASE OPEN;

-- Where do backups and archived logs go? The Fast Recovery Area (set the size FIRST)
ALTER SYSTEM SET db_recovery_file_dest_size = 50G SCOPE = BOTH;
ALTER SYSTEM SET db_recovery_file_dest = '/u03/fra' SCOPE = BOTH;
SELECT * FROM v$recovery_area_usage;                       -- how full is it?

If the Fast Recovery Area fills up, the database stops accepting changes with ORA-00257: archiver error. Delete old archived logs only through RMAN (DELETE ARCHIVELOG ...), never with rm, or Oracle’s records go out of sync.

Step 2: RMAN, the backup tool

rman target /                                                   # connect to the local database as SYSDBA

CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 7 DAYS;        # keep what you need to restore to any point in the last 7 days
CONFIGURE CONTROLFILE AUTOBACKUP ON;                            # the control file is backed up with every backup: crucial for disaster recovery
CONFIGURE DEVICE TYPE DISK PARALLELISM 2;
CONFIGURE BACKUP OPTIMIZATION ON;
SHOW ALL;                                                       # see every setting

BACKUP DATABASE PLUS ARCHIVELOG;                                # a full backup, plus the archived logs
BACKUP INCREMENTAL LEVEL 0 DATABASE PLUS ARCHIVELOG;            # base backup for an incremental strategy (like a full)
BACKUP INCREMENTAL LEVEL 1 DATABASE;                            # only the blocks changed since the last backup: small and fast
BACKUP ARCHIVELOG ALL DELETE INPUT;                             # back up the logs and remove them from disk afterwards
BACKUP TABLESPACE app_data;
BACKUP AS COMPRESSED BACKUPSET DATABASE;                        # smaller (basic compression is free, higher levels are licensed)

A typical schedule is a level 0 backup once a week, a level 1 each night and archived-log backups every hour or so. Run RMAN from a script and a scheduler (cron), and check its exit code.

Looking after the backups

LIST BACKUP SUMMARY;                          # what exists
LIST BACKUP OF DATABASE;
LIST ARCHIVELOG ALL;
REPORT NEED BACKUP;                           # files not backed up recently enough for your policy
REPORT OBSOLETE;                              # backups no longer needed
DELETE OBSOLETE;                              # remove them (asks to confirm)
CROSSCHECK BACKUP;                            # does each backup file still exist on disk?
CROSSCHECK ARCHIVELOG ALL;
DELETE EXPIRED BACKUP;                        # forget the ones that went missing
VALIDATE DATABASE;                            # read all datafiles and look for corruption without making a backup
RESTORE DATABASE VALIDATE;                    # prove the backups are usable, without restoring anything

Recovery scenarios

Always read the alert log and decide what is lost before you restore anything. The three common cases:

# 1. One datafile is damaged or lost; the database stays open (the tablespace goes offline)
RMAN> SQL "ALTER DATABASE DATAFILE 5 OFFLINE";
RMAN> RESTORE DATAFILE 5;
RMAN> RECOVER DATAFILE 5;                       # applies the archived redo to bring it up to date
RMAN> SQL "ALTER DATABASE DATAFILE 5 ONLINE";

# 2. Total loss of the datafiles (the control file and archived logs are intact)
RMAN> STARTUP MOUNT;
RMAN> RESTORE DATABASE;
RMAN> RECOVER DATABASE;
RMAN> ALTER DATABASE OPEN;

# 3. Point-in-time recovery: undo a disaster (a table wiped at 09:15, so go back to 09:00)
RMAN> STARTUP MOUNT;
RMAN> RUN {
  SET UNTIL TIME "TO_DATE('2026-10-30 09:00:00', 'YYYY-MM-DD HH24:MI:SS')";
  RESTORE DATABASE;
  RECOVER DATABASE;
}
RMAN> ALTER DATABASE OPEN RESETLOGS;           # RESETLOGS starts a new "incarnation": take a full backup right after!

Point-in-time recovery rolls back the whole database, including work other users did after that moment. For a single table, use Flashback or restore to a copy and export the table (next).

Flashback: undo mistakes without a restore

-- Flashback Query: look at the table as it was 15 minutes ago (limited by undo retention)
SELECT * FROM employees AS OF TIMESTAMP SYSTIMESTAMP - INTERVAL '15' MINUTE WHERE employee_id = 2;

-- Recover rows deleted by mistake: put them back from the past
INSERT INTO employees SELECT * FROM employees AS OF TIMESTAMP SYSTIMESTAMP - INTERVAL '15' MINUTE
WHERE employee_id NOT IN (SELECT employee_id FROM employees);

-- Flashback Table: rewind a whole table
ALTER TABLE employees ENABLE ROW MOVEMENT;
FLASHBACK TABLE employees TO TIMESTAMP SYSTIMESTAMP - INTERVAL '30' MINUTE;

-- Flashback Database: rewind the whole database without a restore (must be enabled beforehand, in ARCHIVELOG mode)
ALTER DATABASE FLASHBACK ON;
FLASHBACK DATABASE TO TIMESTAMP SYSTIMESTAMP - INTERVAL '1' HOUR;       -- run in MOUNT state, then OPEN RESETLOGS

SHOW PARAMETER undo_retention                                           -- how many seconds of undo Oracle tries to keep (default 900)

Flashback Query relies on undo data, so it only works for a limited time after the change (undo_retention and the size of the undo tablespace). A large table that someone has just truncated cannot be recovered this way (TRUNCATE keeps no undo), which is why backups still come first.

17. Data Pump and SQL*Loader

Data Pump (expdp and impdp) exports and imports data and object definitions as a “dump file”. It is the tool to copy a schema between databases, to move data to a new version or platform, to refresh a test system from production, or to take a logical backup of one table. The files are written by the database server, not by your client, so you must tell Oracle where through a directory object.

-- One time, as a privileged user in the PDB
CREATE OR REPLACE DIRECTORY dp_dir AS '/u01/dpdump';       -- the folder must exist and be writable by the oracle OS user
GRANT READ, WRITE ON DIRECTORY dp_dir TO app_owner;
GRANT DATAPUMP_EXP_FULL_DATABASE, DATAPUMP_IMP_FULL_DATABASE TO app_owner;   -- only if the user must handle other schemas
# Export a whole schema (run in the operating system shell)
expdp app_owner@orclpdb1 schemas=APP_OWNER directory=dp_dir dumpfile=app_%U.dmp logfile=app_exp.log parallel=2

# Export only some tables, filtered by a condition
expdp app_owner@orclpdb1 tables=EMPLOYEES,DEPARTMENTS directory=dp_dir dumpfile=tabs.dmp logfile=tabs_exp.log

# Structure only, no data
expdp app_owner@orclpdb1 schemas=APP_OWNER directory=dp_dir dumpfile=ddl.dmp content=METADATA_ONLY

# Import into another database, renaming the schema
impdp system@orclpdb1 directory=dp_dir dumpfile=app_%U.dmp logfile=app_imp.log remap_schema=APP_OWNER:APP_TEST table_exists_action=REPLACE

# Only write the DDL to a script: nothing is changed
impdp system@orclpdb1 directory=dp_dir dumpfile=app_%U.dmp sqlfile=app_ddl.sql
Parameter What it does
schemas=, tables=, full=y What to export or import
directory=, dumpfile=, logfile= Where files go. %U makes numbered files, needed with parallel
content= ALL, DATA_ONLY or METADATA_ONLY
include=, exclude= Pick object types, e.g. exclude=STATISTICS
remap_schema=, remap_tablespace= Import into a different user or tablespace
table_exists_action= SKIP, APPEND, TRUNCATE or REPLACE when the table already exists
parallel= Number of workers (use more than one dump file)
flashback_time= Export a consistent picture as of a moment (by default each table is consistent, but tables may differ in time)
network_link= Import directly from another database over a database link, with no dump file
parfile= Put all parameters in a file (easier, and keeps quotes and passwords out of the shell)
SELECT owner_name, job_name, operation, state FROM dba_datapump_jobs;          -- running and stopped jobs
expdp system attach=SYS_EXPORT_SCHEMA_01                                       # reconnect to a running job
# then at the prompt:  STATUS, STOP_JOB=IMMEDIATE, START_JOB, KILL_JOB

If you do not give a password on the command line, Data Pump asks for it, which is safer. Licence note: compression=ALL and encryption need the Advanced Compression and Advanced Security options; compression=METADATA_ONLY (the default) is free. The old exp and imp utilities are deprecated: use Data Pump.

SQL*Loader: bulk-loading text files

To load a CSV file, describe it in a control file and run sqlldr:

Save this control file as employees.ctl:

LOAD DATA
INFILE 'employees.csv'
APPEND INTO TABLE employees
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(first_name, last_name, email, hire_date DATE "YYYY-MM-DD", salary, department_id)

Then run it from the operating-system shell:

sqlldr app_owner@orclpdb1 control=employees.ctl log=employees.log bad=employees.bad direct=true

Rows that fail go into the .bad file with the reason in the log. For recurring loads, external tables let you query a text file directly with SQL and are often easier to maintain.

18. Working with pluggable databases

-- From the root container, as a common administrator
CREATE PLUGGABLE DATABASE testpdb
  ADMIN USER pdbadmin IDENTIFIED BY "Str0ng#Passw0rd"
  FILE_NAME_CONVERT = ('/pdbseed/', '/testpdb/');            -- not needed with Oracle-managed files
ALTER PLUGGABLE DATABASE testpdb OPEN;
ALTER PLUGGABLE DATABASE testpdb SAVE STATE;

CREATE PLUGGABLE DATABASE devpdb FROM testpdb FILE_NAME_CONVERT = ('/testpdb/', '/devpdb/');   -- a clone in minutes (in 19c, the source can stay open if local undo is enabled)

ALTER PLUGGABLE DATABASE testpdb CLOSE IMMEDIATE;
DROP PLUGGABLE DATABASE testpdb INCLUDING DATAFILES;       -- deletes its files!

ALTER PLUGGABLE DATABASE testpdb CLOSE IMMEDIATE;
ALTER PLUGGABLE DATABASE testpdb UNPLUG INTO '/tmp/testpdb.xml';       -- move a PDB to another CDB: unplug (it must be closed)...
CREATE PLUGGABLE DATABASE testpdb USING '/tmp/testpdb.xml' NOCOPY;     -- ...and plug it in elsewhere

Cloning a PDB is the quickest way to get a copy of production for testing: it is why multitenant is so popular with developers. After creating a user or a tablespace, always check SHOW CON_NAME: an object created in the root by mistake is a very common mistake.

19. Troubleshooting and the common ORA- errors

Start with the alert log

The alert log is the database’s diary. Almost every serious problem leaves a trace there. Find it and read the end:

SELECT value FROM v$diag_info WHERE name = 'Diag Trace';     -- the folder; the file is alert_<SID>.log
tail -100 $ORACLE_BASE/diag/rdbms/orcl/ORCL/trace/alert_ORCL.log   # on the server

adrci                                                         # the Automatic Diagnostic Repository command line
adrci> show alert -tail 50
adrci> show problem
adrci> show incident

Errors with a trace file point to it (Incident ... trace file). Send that file, not just a screenshot of the error, to Oracle Support or a colleague.

Errors you will meet

Error Meaning and the usual fix
ORA-01017 invalid username/password Wrong password or user (passwords are case-sensitive). Check that you are connecting to the right service
ORA-28000 / ORA-28001 Account locked / password expired: ALTER USER x ACCOUNT UNLOCK; or set a new password
ORA-12154 could not resolve the connect identifier The name is not in tnsnames.ora, or Oracle cannot find the file (TNS_ADMIN). Use EZConnect to confirm
ORA-12541 no listener The listener is down or the host or port is wrong: lsnrctl status, firewall, ss -tulpn
ORA-12514 / ORA-12505 The listener does not know the service or SID you asked for. The database or PDB is not open or not registered: lsnrctl services, ALTER SYSTEM REGISTER;, ALTER PLUGGABLE DATABASE ... OPEN;
ORA-01034 not available, ORA-27101 The instance is not running (or ORACLE_SID is wrong): STARTUP
ORA-00942 table or view does not exist A typo, the wrong schema (schema.table), or a missing SELECT privilege. Oracle uses the same message for all of them
ORA-01031 insufficient privileges You lack a privilege: check session_privs, and whether the right comes from a role (not usable in stored code)
ORA-01653 / ORA-01652 Tablespace / temp tablespace full: add or enlarge a datafile
ORA-00001 unique constraint violated Duplicate key: the constraint name in the message tells you which
ORA-02291 / ORA-02292 Parent key not found (insert) / child record found (delete): a foreign key is protecting the data
ORA-01400 cannot insert NULL A NOT NULL column got no value
ORA-01722 invalid number, ORA-01843 / ORA-01861 Text that is not a number, or a date that does not match its format: give TO_NUMBER / TO_DATE an explicit format
ORA-01427 single-row subquery returns more than one row The subquery gave several rows: use IN, or fix the logic
ORA-00054 resource busy, NOWAIT Someone holds a lock on the object: find the blocker (section 12)
ORA-00060 deadlock detected Two sessions wait for each other. Oracle rolls one statement back and writes a trace file: make the code lock rows in a consistent order
ORA-01555 snapshot too old A long query needed undo that was already overwritten: enlarge undo, raise undo_retention, or shorten the query and commit less often inside the loop that reads
ORA-00257 archiver error The archive destination or Fast Recovery Area is full: back up and delete archived logs with RMAN, or enlarge it
ORA-00018 / ORA-00020 Maximum sessions or processes reached: find who is using them (section 12), raise processes (needs a restart), fix connection leaks
ORA-04031 unable to allocate shared memory The shared pool is too small or fragmented, often caused by SQL without bind variables
ORA-06512 at line N Not an error by itself: it is the call stack of a PL/SQL failure. Read the lines above it for the real error

The number is the key: search the exact ORA- code, and in the database run oerr ora 1555 on the server (this prints Oracle’s own explanation and suggested action).

20. SQL Server to Oracle translation table

If you know SQL Server (see our SQL Server DBA cheat sheet), this table maps what you know to Oracle:

Task SQL Server Oracle
First N rows SELECT TOP 5 ... ... FETCH FIRST 5 ROWS ONLY
Current date and time GETDATE(), SYSDATETIME() SYSDATE, SYSTIMESTAMP
Replace NULL ISNULL(a, b) NVL(a, b) or COALESCE(a, b)
Join text a + b, CONCAT a || b
Text type VARCHAR, NVARCHAR VARCHAR2 (Unicode comes from the database character set)
Auto number IDENTITY(1,1) GENERATED ... AS IDENTITY or a sequence
Select without a table SELECT 1 SELECT 1 FROM dual (23ai allows it without)
Empty string Is not NULL Is NULL
Auto-commit On by default per statement Off: you must COMMIT; DDL commits by itself
Variables and code T-SQL: DECLARE @x INT PL/SQL: x NUMBER; in DECLARE
Switch database USE SalesDB Connect to another service/PDB, or ALTER SESSION SET CURRENT_SCHEMA = hr
Who is connected sp_who2, sys.dm_exec_sessions v$session
Kill a session KILL 55 ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE
Execution plan Actual plan in SSMS EXPLAIN PLAN + DBMS_XPLAN
Backups BACKUP DATABASE ... TO DISK RMAN (BACKUP DATABASE)
Scheduled jobs SQL Server Agent DBMS_SCHEDULER
Database vs. schema A server has many databases, each with schemas An instance (PDB) has many schemas; a schema is a user
Readers and writers Locks by default (RCSI optional) Multiversion read consistency: readers never block writers

21. Good habits and FAQ

  • Know where you are. Run SHOW USER and SHOW CON_NAME before any command that changes something.
  • Check the backups before you change anything big. LIST BACKUP SUMMARY;, and test restores regularly on another server.
  • Use ARCHIVELOG mode on every production database, and watch the Fast Recovery Area.
  • Do not use SYS or SYSTEM for applications. Create named users with only the privileges they need, and use profiles for password rules.
  • Write WHERE first, test with SELECT, and commit consciously. Remember DDL commits automatically.
  • Use bind variables and explicit date formats in your code.
  • Keep statistics fresh, and read the plan before adding an index.
  • Copy the pfile (CREATE PFILE FROM SPFILE) before you change parameters, and change one thing at a time.
  • Mind the licences. AWR, ASH, ADDM, Data Pump compression and encryption, partitioning, and other options cost money. Check DBA_FEATURE_USAGE_STATISTICS and your contract.
  • Patch regularly with the quarterly Release Updates, on a test system first.

Quick answers

What is the difference between SID and service name? The SID identifies an instance on one server. A service name is a logical name that clients use and that can point to an instance, to a PDB, or (in clusters) to several instances. Always connect with the service name.

Is there a free Oracle Database? Yes. Oracle Database Free (23ai) and earlier Express Edition (XE) are free to use, with limits on CPU, memory and data size (the exact limits depend on the release), which is plenty for learning and small applications. Full Enterprise Edition is licensed per processor or per user.

Oracle or SQL Server or PostgreSQL? They solve the same problems. Oracle is strongest in large enterprises with its high-availability and scaling features (RAC, Data Guard) and PL/SQL; its cost and complexity are higher. For comparison with open-source systems, see our guides for MySQL and MariaDB and for SQL Server logins and permissions.

Where do I read more? The official documentation (docs.oracle.com) is free and excellent: start with the Database Concepts guide and the SQL Language Reference. Then practise: create a small schema, break it, back it up, and restore it.

Did you find this helpful?Tap the heart to let us know. It takes one second and no account.

More tutorials like this

Leave a Comment

Your email address will not be published. Required fields are marked *

Bigland Network IT

Practical tutorials for people who run, build and fix things: operating systems, databases, development, networking and security.

Topics

More

Site

© 2026 Bigland Network. All rights reserved.Always test commands on a non-production system first.
Scroll to Top