Recent from talks
Nothing was collected or created yet.
SQL Plus
View on WikipediaThis article's lead section may be too short to adequately summarize the key points. (November 2022) |

SQL Plus is the most basic Oracle Database utility, with a basic command-line interface, commonly used by users, administrators, and programmers.
Command types
[edit]SQL Plus understands five categories of text:[1]
- SQL statements
- PL/SQL blocks
- SQL Plus internal commands, for example:
- environment control commands such as SET
- environment monitoring commands such as SHOW
- Comments
- External commands prefixed by the ! char
Scripts can include all of these components.
An Oracle programmer in the appropriately configured software environment can launch SQL Plus, for example, by entering:
$ sqlplus scott/tiger
where the Oracle user scott has the password tiger. SQL Plus then presents a prompt with the default form of:
SQL>
Interactive use can then start by entering a SQL statement (terminated by a semicolon), a PL/SQL block, or another command. For example:
SQL> select 'Hello world' as example from dual;
EXAMPLE
--------------------------------
Hello world
History
[edit]The first version of SQL Plus was called UFI ("User Friendly Interface"). UFI appeared in Oracle database releases up to Version 4.
After Oracle programmers had added new features to UFI, its name became Advanced UFI. The name "Advanced UFI" changed to "SQL Plus" with the release of the version 5 of Oracle.[2]
Usage
[edit]Graphical interfaces from Oracle or third parties have diminished the proportion of Oracle database end-users who depend on the SQL Plus environment. Oracle shops typically continue to use SQL Plus scripts for batch updating or simple reports.[citation needed]
Oracle Corporation's wrappers/gui-fications/replacements for SQL Plus include:
- Oracle SQL Plus Worksheet, a component of OEM[3]
- iSQL Plus or iSQLPlus, a web-based utility[4]
- SQL Worksheet,[5] a component of Oracle SQL Developer
- SQL Workshop (part of Oracle Application Express)[6]
Oracle 11g
[edit]Starting from Oracle database 11g, iSqlplus (web based) and sqlplus GUI no longer ship with Oracle database software.[7]
The command-line SQL Plus interface continues in use, mostly[citation needed] for non-interactive scripting or for administrative purposes. The Server Manager Command Line — a replacement of SQL*DBA — is obsolete and SQL Plus 8i and later allows the user to issue statements like STARTUP and SHUTDOWN when connected as SYSDBA. Server Manager 7.1 introduced the command CONNECT / AS SYSDBA to replace CONNECT INTERNAL.[8] SQL Plus 8i and later allows the use of CONNECT / AS SYSDBA
Compatibility
[edit]Other vendors have made their software somewhat compatible with SQL Plus script commands or offer a SQL Plus mode of operation. Relevant products include TOAD from Quest Software.[9]
Integration
[edit]This section needs expansion. You can help by adding missing information. (July 2009) |
Variables
[edit]SQL Plus-internal variables, accessible within an SQL Plus session, include:
- user variables, displayable with the
DEFINEcommand and referenceable with one or two cases of a prefixed character (default prefixes: '&' and '&&'). Oracle Corporation calls these variables "substitution variables". Programmers can use them anywhere in a SQL or PL/SQL statement or in SQL Plus commands. They can be populated by a literal usingDEFINEor from the database using thecolumncommand. - bind variables, prefixed by a colon (':'), which can interact with the PL/SQL environment. Displayable with the VARIABLE and PRINT commands[12]
Error trapping
[edit]The WHENEVER command specifies an action to perform in the event of the system detecting an SQL error[13]
or an operating-system error[14]
while running a subsequent SQL Plus command.
Installation and configuration
[edit]SQL*Plus needs to be installed and configured on the machine where you intend to use it. This usually involves setting up Oracle client software and configuring network connections to Oracle databases.[15]
Supplementary software
[edit]- SQL Assistant SQL Assistant add-on for SQL Plus Windows version extends SQL Plus with SQL automatic word completion, in-line Oracle SQL Reference, data export/import, code unit testing, data browsing, and code development functions.
- rlwrap rlwrap does GNU Readline like command completion for SQL Plus on UNIX and Linux.
See also
[edit]References
[edit]- ^ "SQL Plus at orafaq.com". Archived from the original on 2007-11-09. Retrieved 2007-11-26.
- ^ Millsap, Cary; Kolk, Anjo; McDonald, Connor; Gorman, Tim; Hailey, Kyle; Ensor, David; Lewis, Jonathan; Vaidyanatha, Gaja Krishna; Ruthven, David; Morle, James (2004). Oracle Insights (1st ed.). Apress. p. 35. ISBN 978-1590593875. Retrieved March 18, 2014.
- ^ Evans, Robert (2008-10-01). "The SQL Plus Worksheet". Cardiff University. Archived from the original on 2008-12-01. Retrieved 2008-11-21.
Oracle's SQL Plus Worksheet is a straight-forward, easy-to-use, graphical user interface for SQL.
- ^ "ISQLPlus". Oracle FAQ. 2008-02-29. Retrieved 2008-11-21.
iSQLPlus (iSQL Plus) is a web-based utility similar to the SQL Plus command line utility for executing SQL and PL/SQL commands (available up to Oracle 10gR2).
- ^ "Oracle SQL Developer 1.5: Feature List". Oracle Corporation. Archived from the original on 2008-07-24. Retrieved 2008-11-21.
The SQL Plus commands supported by Oracle SQL Developer SQL Worksheet are listed [...]
- ^ "Oracle Application Express". Oracle Corporation. Archived from the original on 2006-10-21. Retrieved 2008-11-21.
SQL Workshop provides tools to enable you to view and manage database objects from a Web browser. Use SQL Commands to run SQL and PL/SQL statements. ...
- ^ Deprecated Components in Oracle Database 11g Release 1 (11.1), retrieve by 25-Jun-2009
- ^ [1] Oracle 7 doc, 1994
- ^ Hotka, Dan; Scalzo, Bert (2003-04-18). TOAD SQL Editor.
- ^ Alapati, Sam R. (2008). "4". Expert Oracle Database 11g Administration. Apress. pp. 118–119. ISBN 978-1-4302-1015-3. Retrieved 2009-07-29.
- ^
Roshak, Natalka (2005-11-06). "Spice up your SQL Scripts with Variables". Oracle FAQ. Retrieved 2009-07-29.
& and && indicate substitution variables in SQL Plus scripts or commands.
- ^
Nyffenegger, René. "Using bind variables in SQL Plus". René Nyffenegger's collection of things on the web. Retrieved 2009-07-29.
In SQL Plus, a bind variable is declared with
variable[...] The value of the bind variable can then be printed withprint - ^
Watt, Simon. "SQL Plus User's Guide and Reference". Oracle Help Center. Oracle Database Online Documentation, 10g Release 2 (10.2) / Administration. Oracle. p. 74. Retrieved 2015-11-04.
WHENEVER SQLERROR [...] [d]irects SQL Plus to perform the specified action as soon as it detects a SQL command or PL/SQL block error (but after printing the error message).
- ^
Watt, Simon. "SQL Plus User's Guide and Reference". Oracle Help Center. Oracle Database Online Documentation, 10g Release 2 (10.2) / Administration. Oracle. p. 73. Retrieved 2015-11-04.
WHENEVER OSERROR [...] [d]irects SQL Plus to perform the specified action as soon as an operating system error is detected.
- ^ "Oracle database services and products offer customers cost-optimized and high-performance versions of Oracle Database, the world's leading converged, multi-model database management system".
External links
[edit]SQL Plus
View on GrokipediaHistory
Origins and Development
SQL*Plus originated in the late 1970s as part of Oracle Corporation's early relational database development efforts, initially under the name User Friendly Interface (UFI). Developed primarily by Bruce Scott, one of Oracle's founding employees and co-architect of its first versions, UFI served as a basic command-line tool for interacting with the database. It was introduced alongside Oracle Version 2, the company's first commercially available relational database management system, released in 1979.[5] The primary motivations for creating UFI, later evolving into SQL*Plus, were to provide database administrators and developers with a straightforward interface for executing SQL queries and retrieving results without relying on graphical user interfaces, which were not yet prevalent. This tool emphasized portability across diverse early computing platforms, including mainframes and minicomputers, and drew inspiration from IBM's System R User Friendly Interface, one of the earliest relational database prototypes. Early contributors like Kirk Bradley highlighted the need for a simple mechanism to input SQL statements and format output, addressing the limitations of direct database access methods at the time.[5][6] UFI remained the standard interface through Oracle Version 4, released in 1984, supporting core functions like query execution and basic reporting on platforms such as PDP-11 systems. By 1985, with the release of Oracle Version 5 in April, the tool was renamed SQL*Plus and enhanced to better align with the growing adoption of SQL as a standard language. This version introduced improved command-line interaction tailored for mainframes and minicomputers, marking its first widespread public availability.[6][7][8] In the mid-1980s, SQLPlus began evolving from a rudimentary query tool to include scripting capabilities, allowing users to automate sequences of SQL and control commands in batch files. This development supported Oracle's expansion into client-server architectures with Versions 5.0 and 5.1, facilitating more efficient database administration on emerging networked systems. These early advancements laid the foundation for SQLPlus's role as a durable, text-based utility in Oracle environments.[5][7]Major Releases and Evolution
The name SQLPlus was introduced with Oracle Database version 5 in 1985, enabling basic scripting and interactive query processing as an evolution of the earlier UFI tool.[2] By Oracle Database version 6 in 1991, SQLPlus gained support for PL/SQL blocks, allowing users to execute procedural code alongside standard SQL commands. In Oracle 8i (1998), enhancements to globalization support were added, including improved handling of national character sets (NCHAR and NVARCHAR) for multilingual data processing and display.[9] Oracle Database 10g (2004) integrated XML capabilities into SQLPlus, with the SET MARKUP command enabling XML-formatted output for queries and support for XMLType data manipulation.[10] The release of Oracle 12c in 2013 introduced multitenant architecture, and SQLPlus was updated to connect to container databases (CDBs) and pluggable databases (PDBs) using the ALTER SESSION SET CONTAINER command, facilitating management in consolidated environments.[11] Oracle 19c (2019), designated as a long-term support release, optimized SQL*Plus for cloud deployments with features like Easy Connect Plus syntax for simplified connections and desupport of legacy elements such as the PRODUCT_USER_PROFILE table.[12] In Oracle 21c (2021), SQLPlus received updates including an enhanced HISTORY command for easier access to previous commands and the SET JSONPRINT option for formatted JSON output readability.[13] The iSQLPlus web interface, introduced earlier for browser-based access, was deprecated starting with Oracle 11g in 2009 and fully desupported by 2010. Oracle Database 23ai (2024) maintained SQL*Plus compatibility while adding commands like ARGUMENT for parameter handling, SET ERRORDETAILS for diagnostic output, PING for connection testing, OERR for error lookups, and support for BOOLEAN data types in queries.[14] As of November 2025, SQL*Plus remains bundled with Oracle Database 23ai and the newly announced 26ai release, receiving minor patches focused on security hardening and cloud integration, such as improved compatibility with Oracle Cloud Infrastructure services, amid a broader industry shift toward automated database tools.[15][16]Overview
Purpose and Functionality
SQL*Plus serves as both an interactive and non-interactive command-line interface for executing SQL statements, PL/SQL blocks, and Oracle-specific commands directly against Oracle databases. As a core component of the Oracle Database installation, it enables users to interact with the Oracle Relational Database Management System (RDBMS) in a text-based environment, supporting both ad-hoc queries and automated batch processing.[17] Its primary functionalities encompass executing queries for data retrieval and manipulation, running PL/SQL code blocks for procedural logic, formatting and printing report outputs with customizable column headings and page layouts, and performing essential database administration tasks such as starting up or shutting down database instances. SQLPlus also allows users to connect to remote or local databases, examine object definitions like tables and views, and store or retrieve command buffers for repeated use. These capabilities make it a versatile tool for database developers, administrators, and scripters. In recent versions such as Oracle Database 23ai and 26ai, SQLPlus has been enhanced to support new SQL features like the BOOLEAN data type and improved error handling with commands such as OERR and SET ERRORDETAILS.[17][18] In contrast to comprehensive graphical Integrated Development Environments (IDEs) like Oracle SQL Developer, SQLPlus is designed as a lightweight, platform-independent utility that operates without a graphical user interface, rendering it ideal for headless server environments, command-line scripting, and resource-constrained systems. The SQLPlus Instant Client variant further enhances this portability by providing a standalone executable without requiring a full local database installation.[17] Effective use of SQL*Plus requires installation of the Oracle Database client software or the Instant Client package, which includes the necessary binaries and libraries. Additionally, database connectivity must be configured, typically through Transparent Network Substrate (TNS) entries in a configuration file or via direct Easy Connect strings specifying the host, port, and service name.[19]Core Components
SQLPlus maintains a SQL buffer as its primary internal storage mechanism for user-entered commands. This buffer temporarily holds the most recently executed SQL statement or PL/SQL block, excluding SQLPlus-specific commands, and persists until overwritten by new input.[20] The buffer enables editing without retyping, supporting operations such as viewing contents with the LIST command, replacing text in the current line via CHANGE (e.g.,CHANGE /old_text/new_text), appending lines with APPEND, inserting new lines with INPUT, or deleting lines with DEL.[21] For more extensive modifications, the EDIT command loads the buffer into an external editor, allowing users to refine commands before re-execution with RUN or the forward slash (/).[21]
Input to SQLPlus occurs through multiple channels to facilitate both interactive and automated workflows. In interactive mode, users enter commands directly at the SQL> prompt, with each line processed upon pressing Return, and multi-line blocks terminated by a semicolon or forward slash.[20] For batch operations, input can be drawn from script files using the @ or START command (e.g., @myscript.sql), which loads and executes the file's contents sequentially into the buffer.[22] Additionally, SQLPlus supports piped input from standard input (stdin), enabling automation by redirecting commands from external processes, such as echo "SELECT * FROM table;" | sqlplus username/password.[22]
Output processing in SQL*Plus emphasizes structured presentation and control for reporting. By default, query results feature column headings derived from table or expression names, with widths automatically set based on data types—such as 10 characters for NUMBER columns via the NUMWIDTH setting or the database-defined width for other types—and overflow handled by truncation or hash symbols.[23] Users can suppress elements like headings (SET HEADING OFF) or feedback messages (SET FEEDBACK OFF) to streamline output, while the COLUMN command allows precise formatting (e.g., COLUMN [salary](/page/Salary) FORMAT $99,999).[23] For persistence, the SPOOL command directs output to a file (e.g., SPOOL results.txt), capturing formatted results until SPOOL OFF, which is essential for logging in non-interactive sessions.[23]
Editor integration in SQLPlus is handled externally to leverage operating system tools, avoiding any native graphical interface. The EDIT command invokes the user's defined text editor—typically vi on Unix-like systems or Notepad on Windows, configurable via DEFINE _EDITOR = editor_name—to modify the SQL buffer or a specified file, returning changes upon exit.[21] This approach ensures compatibility across platforms but relies on command-line or basic OS editors, with no embedded GUI for buffer editing.[21] These components collectively underpin SQLPlus's role in scripting environments by enabling seamless input processing and output capture.[22]
Commands and Syntax
SQL and PL/SQL Execution
SQLPlus facilitates the direct execution of standard SQL Data Manipulation Language (DML) statements, including SELECT, INSERT, UPDATE, and DELETE, by allowing users to enter them interactively at the command prompt.[17] These statements are processed by the connected Oracle Database server, with SQLPlus handling input, transmission, and output formatting. To execute a SQL statement, it is terminated with a semicolon (;) or by entering a forward slash (/) on a subsequent line, which prompts SQLPlus to run the contents of its SQL buffer.[24] For query results from SELECT statements, SQLPlus automatically formats output with column headings enabled by default via the SET HEADING ON system variable, which can be toggled to control header display.[17] For example, the following SQL statement retrieves employee data and displays it with formatted columns:SQL> SELECT employee_id, last_name FROM employees WHERE department_id = 10;
SQL> SELECT employee_id, last_name FROM employees WHERE department_id = 10;
SQL> SET SERVEROUTPUT ON
SQL> BEGIN
2 DBMS_OUTPUT.PUT_LINE('Hello, SQL*Plus!');
3 END;
4 /
Hello, SQL*Plus!
SQL> SET SERVEROUTPUT ON
SQL> BEGIN
2 DBMS_OUTPUT.PUT_LINE('Hello, SQL*Plus!');
3 END;
4 /
Hello, SQL*Plus!
SQL> EXECUTE procedure_name('argument');
SQL> EXECUTE procedure_name('argument');
SQL> SELECT * FROM employees WHERE department_id = &deptno;
Enter value for deptno: 20
SQL> SELECT * FROM employees WHERE department_id = &deptno;
Enter value for deptno: 20
SQL*Plus-Specific Commands
SQLPlus provides a set of commands distinct from standard SQL and PL/SQL that enable users to manage sessions, format output, handle files, and interact with the host operating system, facilitating efficient database administration and scripting. These commands operate within the SQLPlus environment to control its behavior without directly affecting the database schema or data.[17]Session Control
Session control commands in SQLPlus allow users to establish, maintain, and terminate connections to the Oracle database. The CONNECT command logs a user into a specified database instance, optionally with elevated privileges such as SYSDBA for administrative access. Its syntax isCONNECT [username[/password][@connect_identifier] [AS {SYSASM|SYSBACKUP|SYSDBA|SYSDG|SYSOPER|SYSKM}]], as in the example CONNECT SYS/password@orcl AS SYSDBA, which connects as SYS with password to the orcl database as a system database administrator.[17] The DISCONNECT command severs the current database connection while keeping the SQLPlus session active, using the simple syntax DISCONNECT; this is useful for switching databases without exiting the tool.[17] For complete termination, the EXIT command logs out of SQL*Plus entirely, with syntax EXIT [SUCCESS|FAILURE|WARNING|n] [COMMIT|ROLLBACK], such as EXIT SUCCESS COMMIT to end the session successfully and commit pending changes.[17]
Formatting
Formatting commands customize the display of query results and session output to improve readability and fit specific reporting needs. The SET command configures various SQL*Plus environment variables, particularly for output control; for instance,SET PAGESIZE 50 limits each page of output to 50 lines, while SET LINESIZE 100 sets the maximum width of each line to 100 characters, preventing wrapping in wide reports.[17] Complementing this, the COLUMN command formats individual columns in query results, specifying options like width or justification; an example is COLUMN ename FORMAT A10, which displays the ename column as a left-justified string of up to 10 characters.[17] These commands are applied before executing SQL statements to ensure consistent presentation without altering the underlying data.
File Operations
File operations in SQLPlus support loading, saving, and redirecting content for scripting and logging purposes. The GET command retrieves the contents of a script file into the SQL buffer for editing or immediate execution, using syntaxGET filename [.ext] [LIST|NOLIST], as in GET script.sql to load and optionally list the file's commands.[17] Conversely, SAVE stores the current buffer contents to a file, with syntax SAVE filename [.ext] [CREATE|REPLACE|APPEND], such as SAVE myscript.sql to create or overwrite a file with the buffered SQL.[17] The SPOOL command redirects output from SQLPlus sessions to a file, enabling capture of results for review or printing; its syntax is SPOOL [filename[.ext] [CREATE|REPLACE|APPEND]|OFF|OUT], exemplified by SPOOL output.txt to start spooling query results to a text file, followed by SPOOL OFF to stop.[17]
Host and Shell Integration
To bridge SQLPlus with the underlying operating system, the HOST command executes external programs or shell commands directly from within a session. Its syntax isHOST [command], allowing integration like HOST ls -l on Unix-like systems to list files in the current directory or HOST dir on Windows for similar functionality. This command temporarily suspends SQLPlus, runs the host operation, and returns control upon completion, supporting tasks such as file management or system queries without leaving the tool.[17]
Usage
Starting and Basic Operations
SQLPlus is invoked from the command line using thesqlplus command, which can include credentials and connection details directly. For example, to connect as a specific user to a remote database, the syntax is sqlplus username/[password](/page/Password)@connect_identifier, such as sqlplus hr/mypassword@SALES1.[26] Local administrative access is achieved with sqlplus / as sysdba, allowing privileged operations without specifying a username or password on the same host.[26] If credentials are omitted, SQLPlus prompts for the username and password separately.[26]
The login process requires a valid username and password, with the connect identifier specifying the target database instance. Supported identifiers include TNS names resolved via the tnsnames.ora file, such as @SALES1, or Easy Connect strings in the format host:port/service_name, like @"sales-server:1521/sales.us.acme.com".[26] For connections using Oracle Wallet or other secure stores, the syntax CONNECT /@database_alias can be used after initial login.[26] To start SQL*Plus without connecting, the command SQLPLUS /NOLOG opens the tool in a disconnected state.[26]
Once connected, SQLPlus displays the SQL> prompt, where users enter SQL statements or SQLPlus commands interactively. SQL statements must be terminated with a semicolon (;) to execute, for instance, SELECT * FROM employees;.[26] Commands are processed line by line, and multi-line statements continue until the semicolon is encountered.[26]
To explore available commands, users can invoke HELP INDEX or HELP TOPICS at the SQL> prompt, which lists all supported topics.[26] For details on a specific command, HELP command_name provides syntax and usage, such as HELP ACCEPT.[26] Schema information for database objects is retrieved using the DESCRIBE command, abbreviated as DESC, followed by the object name, e.g., DESCRIBE employees, which outputs column names, data types, and nullability.[26]
Basic navigation includes re-executing the most recent command or buffer contents with a forward slash (/) on a new line, which is useful for repeating queries without retyping.[26] This operation runs the last SQL statement or SQL*Plus command entered.[26]
Scripting and Batch Processing
SQLPlus supports scripting to automate repetitive database tasks by allowing users to create files containing sequences of SQL, PL/SQL, and SQLPlus commands. These scripts are typically saved with a .sql extension using any text editor, and SQL statements within them must end with a semicolon (;), while PL/SQL blocks conclude with a forward slash (/).[27] To execute a script from within a SQL*Plus session, the START command or its shorthand @ is used, followed by the filename, such as START myscript.sql, which runs the commands in the specified file sequentially.[28] This enables modular workflows where multiple scripts can reference each other for complex operations. For batch processing in non-interactive environments, SQL*Plus operates in silent mode using the -s flag on the command line, suppressing prompts and banners, as in sqlplus -s username/password@database @script.sql, ideal for automated runs without user intervention.[26] This mode facilitates headless execution on servers, integrating with operating system schedulers. Parameter passing enhances script flexibility; positional parameters like &1 substitute values provided at runtime, for example, SELECT * FROM employees WHERE dept_id = &1;, while the ACCEPT command prompts for input if not supplied, such as ACCEPT dept_num PROMPT 'Enter department ID:'.[29] These mechanisms allow scripts to adapt dynamically without modification. A common example is a backup script that spools query results to a CSV file:SPOOL employee_backup.csv
SET PAGESIZE 0
SET LINESIZE 1000
SET FEEDBACK OFF
SET HEADING ON
SELECT employee_id || ',' || first_name || ',' || last_name || ',' || [salary](/page/Salary) FROM employees;
SPOOL OFF
EXIT
SPOOL employee_backup.csv
SET PAGESIZE 0
SET LINESIZE 1000
SET FEEDBACK OFF
SET HEADING ON
SELECT employee_id || ',' || first_name || ',' || last_name || ',' || [salary](/page/Salary) FROM employees;
SPOOL OFF
EXIT
Configuration and Integration
Installation and Setup
SQLPlus is bundled with Oracle Instant Client, which provides a minimal installation option, as well as full Oracle Database and Oracle Client installations supporting platforms including Windows, Linux, and macOS.[31] The Instant Client packages include the SQLPlus executable along with necessary libraries for basic functionality, while full installations offer additional tools and administrative features.[32] Prerequisites for SQL*Plus deployment include Oracle Net Services for database connectivity, which is incorporated in the Instant Client Basic or Basic Light packages.[33] Environment variables such as PATH must be configured to include the Instant Client directory, and on Unix-like systems, LD_LIBRARY_PATH may be required to locate shared libraries; ORACLE_HOME is typically unnecessary for Instant Client but is set in full installations.[32] Setup involves downloading the relevant packages from the Oracle website, such as the Basic and SQLPlus ZIP files for Oracle AI Database 26ai (version 23.26) as of November 2025.[34] Extract the files to a designated directory (e.g., C:\instantclient on Windows or /opt/oracle/instantclient on Linux), then update the PATH environment variable to point to this directory.[35] For Linux, RPM packages can be installed via yum from Oracle Linux repositories.[36] On macOS, DMG or ZIP files are available for Intel x86-64 and ARM architectures, with similar extraction and PATH configuration.[31] To verify the installation, executesqlplus -v in the command prompt or terminal, which displays the SQLPlus version information.
Initial configuration requires editing files such as sqlnet.ora for network settings, located by default in the network/admin subdirectory of the installation directory or specified via the TNS_ADMIN environment variable. This file configures parameters like naming methods and authentication protocols for Oracle Net Services. Additionally, glogin.sql serves as a global startup script, typically placed in $ORACLE_HOME/sqlplus/admin/ for full installations or a user-defined location, to set site-wide defaults executed upon connection.
Variables and Customization
SQLPlus supports substitution variables to enable dynamic content in SQL statements and commands, allowing users to parameterize scripts and prompts for input at runtime. These variables are referenced using an ampersand (&) prefix for single-use substitution or double ampersand (&&) for persistent definition within the session. When SQLPlus encounters an undefined substitution variable, it prompts the user for a value, which is then substituted before executing the command; this feature is particularly useful for tailoring queries without hardcoding values. Substitution variables can be used anywhere in SQL and SQL*Plus commands except as the first word in a statement.[37] User-defined substitution variables are created and managed through the DEFINE and UNDEFINE commands. The DEFINE command assigns a value to a variable, storing it as a character string up to 240 bytes, which can then be referenced in subsequent commands; for example,DEFINE dept = 10 creates a variable named "dept" with the value "10", allowing its use in queries like SELECT * FROM employees WHERE department_id = &dept. Variables defined with && are retained for the entire session unless explicitly undefined, while single & prompts anew each time. The UNDEFINE command removes a variable from the session, such as UNDEFINE dept, preventing accidental reuse and conserving session resources; SQL*Plus supports up to 2048 such variables simultaneously.[37]
System-defined substitution variables provide predefined session information without user intervention, accessible across SQL*Plus sessions and modifiable via commands. Examples include _CONNECT_IDENTIFIER, which holds the current database connection identifier, and others like SQL.USER for the current username or DATE for the system date; these are automatically available and can be referenced directly, such as in prompts or titles, to incorporate dynamic metadata into output. There are nine such predefined variables, all modifiable, ensuring consistent access to essential context like user details and timestamps.[37]
Customization in SQLPlus extends to startup scripts that automate session configuration for individual users or sites. The user profile script, typically named login.sql, executes automatically after a successful database connection, applying per-user settings such as formatting options or environment variables. For instance, it can include SET TIMING ON to display execution times for commands, or SET PAGESIZE 24 and SET LINESIZE 78 to control report layout; SQLPlus searches for login.sql in directories specified by the SQLPATH environment variable. Similarly, the site-wide glogin.sql, located in the SQL*Plus administration directory (e.g., $ORACLE_HOME/sqlplus/admin/ on Unix), runs before login.sql to enforce global defaults like NLS date formats via ALTER SESSION SET nls_date_format = 'DD-MON-YYYY HH24:MI:SS'. These scripts enhance usability by preconfiguring sessions without manual intervention each time.[38]
For advanced scenarios, the COLUMN command's NEW_VALUE clause captures query output into substitution variables, facilitating iterative scripting by storing column values for reuse. This is not a bind variable mechanism but a post-fetch assignment, where the variable receives the value from the specified column in the result set—typically the last row or per break group. An example illustrates this:
COLUMN ename NEW_VALUE empvar NOPRINT
SELECT ename FROM emp WHERE deptno = 10;
COLUMN ename NEW_VALUE empvar NOPRINT
SELECT ename FROM emp WHERE deptno = 10;
&empvar holds the last employee's name from the query, which can then be used in subsequent statements like PRINT &empvar; the NOPRINT option suppresses column display in output. This feature supports dynamic report generation, such as populating titles with query-derived data when combined with TTITLE or BREAK commands, but requires the column to be ordered appropriately for accurate capture.[39]
Error Handling and Logging
In SQLPlus, error trapping is primarily managed through the WHENEVER SQLERROR command, which specifies actions to take when a SQL statement or PL/SQL block encounters an Oracle error, such as an ORA- error code.[40] This command does not respond to SQLPlus-specific errors but only to database-level SQL or PL/SQL failures, allowing scripts to conditionally terminate or continue execution.[40] The syntax isWHENEVER SQLERROR {EXIT [SUCCESS | FAILURE | WARNING | n | variable | :BindVariable] [COMMIT | ROLLBACK] | CONTINUE [COMMIT | ROLLBACK | NONE]}, where EXIT halts the session with a specified return code (defaulting to the SQL error code if unspecified), and CONTINUE proceeds to the next command without interruption.[40] For instance, WHENEVER SQLERROR EXIT FAILURE ROLLBACK instructs SQLPlus to exit with a failure status and undo any uncommitted changes upon error, enhancing script reliability in batch environments.[40] Without this command, SQLPlus defaults to continuing execution after displaying the error message.[40]
Starting with Oracle AI Database 26ai, SQL*Plus displays a help URL alongside many error messages, providing direct access to detailed descriptions and resolution guidance.[14]
Logging mechanisms in SQL*Plus capture session output and errors for auditing or debugging. The SPOOL command directs output—including query results, error messages, and command echoes—to a file, facilitating persistent records of interactions.[41] Its syntax is SPO[OL] [file_name[.ext] [CRE[ATE] | REP[LACE] | APP[END]] | OFF | OUT], where CREATE generates a new file, REPLACE overwrites an existing one (default), and APPEND adds to the end of a current file; OFF ceases logging without deleting the file, while OUT also sends it to the default printer on supported platforms.[41] For PL/SQL compilation issues, the SHOW ERRORS command displays detailed error information from the most recent CREATE or ALTER operation on objects like procedures, packages, or triggers.[42] Invoked as SHOW ERRORS [object_type [schema.]name], it lists line/column positions and error descriptions, such as PLS-00302: component 'NON_EXISTENT' must be declared, aiding rapid identification of syntax or semantic problems.[42]
Integration with the DBMS_OUTPUT package allows SQLPlus to display procedural output messages generated by PL/SQL code. To enable this, the SET SERVEROUTPUT command must be used, with syntax SET SERVEROUTPUT {ON | OFF | size_clause}, where ON activates retrieval of buffered messages via DBMS_OUTPUT.GET_LINES after each SQL or PL/SQL execution, and size_clause (e.g., SIZE 1000000) sets the buffer limit to prevent truncation.[43] OFF disables this feature, suppressing output for cleaner sessions.[43] This is essential for viewing debug statements from PUT_LINE calls within procedures, as SQLPlus does not fetch them by default.[43]
Best practices for error handling in SQL*Plus emphasize combining tool-specific controls with PL/SQL's built-in functions for robust, custom responses. Within PL/SQL exception handlers, SQLCODE returns the numeric error code (e.g., -1 for cursor-related issues) and SQLERRM provides the associated message string (up to 512 bytes), enabling precise logging or recovery actions.[44] These functions are only meaningful inside handlers and must be assigned to variables before use in SQL statements to avoid errors.[44] For transaction integrity, a common approach is to implement rollback in an OTHERS handler upon failure, as in the following example:
BEGIN
-- Transaction logic here
UPDATE employees SET salary = salary * 1.1;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
DECLARE
err_code NUMBER := SQLCODE;
err_msg VARCHAR2(512) := SQLERRM;
BEGIN
ROLLBACK; -- Undo changes on error
DBMS_OUTPUT.PUT_LINE('Error ' || err_code || ': ' || err_msg);
END;
END;
/
BEGIN
-- Transaction logic here
UPDATE employees SET salary = salary * 1.1;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
DECLARE
err_code NUMBER := SQLCODE;
err_msg VARCHAR2(512) := SQLERRM;
BEGIN
ROLLBACK; -- Undo changes on error
DBMS_OUTPUT.PUT_LINE('Error ' || err_code || ': ' || err_msg);
END;
END;
/
Compatibility and Limitations
Supported Oracle Versions
SQLPlus maintains broad compatibility with Oracle Database releases, providing full support from Oracle 9i (9.0.1) through the latest long-term support version, Oracle AI Database 26ai (via Release Update in October 2025), with SQLPlus Release 26ai available as of November 2025.[45] The official client/server interoperability matrix outlines supported combinations, allowing SQL*Plus as part of the Oracle Client to connect to database servers typically within two prior major releases while ensuring certification for current and recent versions.[46] Backward compatibility enables older SQL*Plus versions, such as those bundled with Oracle 11g, to establish connections to newer Oracle Databases, including 12c and beyond; however, these legacy clients lack support for database-specific enhancements like native JSON data handling introduced in Oracle Database 12c Release 1.[46] This means users may encounter limitations in formatting output or utilizing server-side features without upgrading the client. Forward compatibility requires newer SQL*Plus versions to access advanced capabilities in environments like Oracle Autonomous Database, where features such as wallet-based secure connections and optimized cloud networking demand clients from Oracle Database 19c or later for seamless integration.[46] Notable deprecations include iSQLPlus, a web-based interface, which was removed starting with Oracle Database 11g Release 1, shifting focus to command-line SQLPlus and graphical alternatives. The 19c Long Term Support release introduced no significant changes to SQLPlus core functionality, preserving stability for extended support periods. In contrast, Oracle AI Database 26ai includes enhancements to SQLPlus, such as new commands for argument handling (ARGUMENT) and connectivity testing (PING), while providing database support for AI-driven features like vector data types and query optimizations for AI vector search, accessible via SQLPlus. As of October 2025, Oracle Database 23ai was updated to Oracle AI Database 26ai via Release Update 23.26.0, introducing SQLPlus enhancements including the CONFIG command for generating configuration files and improved error details.[45][14]| Oracle Database Version | SQL*Plus Version Support | Key Compatibility Notes |
|---|---|---|
| 9i (9.2) | 9.2.x | Basic connectivity; limited to legacy SQL features.[46] |
| 11g (11.2) | 11.2.x | Full support; connects to up to 19c with feature gaps.[46] |
| 12c (12.2) | 12.2.x | JSON support added; backward to 11g, forward to 26ai with limits. |
| 19c LTS | 19.x.x | Stable; no major SQL*Plus changes, certified through 2027 Premier Support. |
| 26ai (26.0) | 26ai | New SQL*Plus commands (e.g., ARGUMENT, PING); supports database AI features like vector types via SQL; full interoperability with prior clients where possible (as of November 2025).[45][46][14] |
