ORACL
ORACL
Save The Save option has three alternatives: Save Create, Save Replace, and Save Append
Save Create saves the contents of the SQL*Plus buffer in a script
Save Replace replaces the contents of an existing file with the contents
of the SQL*Plus buffer
Save Append adds the contents of the SQL*Plus buffer to the end of
the file you specify.
After you save a script, you can:
Retrieve the file using the Open option on the File menu.
Edit the file using the Editor option on the Edit menu.
Run the file using the START or RUN commands from the SQL*Plus
command prompt.
Save As The Save As option saves the contents of the SQL*Plus buffer in a script.
Spool The Spool option has two alternatives: Spool File and Spool Off .
Spool File stores query results in a file. By default, SQL*Plus assigns the LST
extension to spool files. You can edit the results with the Editor option on the
Edit menu, and print the file from a Windows text editor.
Spool Off turns off spooling.
Run The Run option lists and executes the SQL command or PL/SQL block currently
stored in the SQL buffer. Typically this will be the last statement that was executed.
Cancel(Ctrl+C)) The Cancel option cancels an in-progress operation.
Exit The Exit option commits all pending database changes and closes the SQL*Plus
application window.
Edit Menu:
The Edit menu has the following options:
Option Description of Edit Menu Option
Copy(Ctrl+C) The Copy option copies selected text to the Clipboard
After you copy text to the Clipboard, you can paste the text into other
Windows applications, such as Microsoft Excel and Microsoft Word.
Paste(Ctrl+V) The Paste option pastes the contents of the Clipboard to the SQL*Plus
command-line.
Note: A maximum of 3625 characters can be pasted from the Clipboard to the
SQL*Plus command-line during a single paste operation.
Clear The Clear option clears the screen buffer and the screen of the SQL*Plus
(Shift+Del) application window.
Editor The Editor option has two alternatives: Invoke Editor and DefineEditor.
InvokeEditor loads the contents of the SQL*Plus buffer into an editor.
By default, SQL*Plus saves the file to AFIEDT.BUF
Define Editor defines the editor that is invoked
Search Menu
The Search menu has the following options:
Option Description of Search Menu Option
Find(Alt+F3) The Find option searches for a character, a word, or a group of characters or
words in the SQL*Plus application window. Find begins the search at the top of
the displayed screen.
Find Next The Find Next option finds the next occurrence of the search text.
(F3)
Options Menu
The Options menu has the following options:
Option Description of Options Menu Option
Environment The Environment option enables you to set system variables to alter the
SQL*Plus environment for your current session. This dialog has three areas: Set
Options, Value, and Screen Buffer.
Set Options
This area has a list of variables you can select to establish aspects of the
SQL*Plus environment for your current session, such as:
Setting the display width for NUMBER data.
Enabling or disabling the printing of column headings.
Setting the number of lines in each page.
Value
The Value area has four options: Default, Custom, On, and Off.
Screen Buffer
This area has two text boxes: Buffer Width and Buffer Length.
Use the Buffer Width text box to set the number of characters available to
display on one line. Buffer Width has a default value of 100, a minimum
value of 80, and a maximum value of 32,767 characters.
In the Buffer Length text box, you set the number of lines that SQL*Plus
displays on the screen. The default value of the Buffer Length parameter
is 1000 lines. You can specify from 100 to 2000 lines on one screen.
Help Menu
Suppose you try to select the JOB_ID column but mistakenly enter it as JO_ID. Enter
the following command, purposely misspelling JOB_ID in the first line:
Examine the error message; it indicates an invalid column name in line 1 of the query.
The asterisk shows the point of error—the mis-typed column JOB_ID.
Instead of re-entering the entire command, you can correct the mistake by editing the
command in the buffer. The line containing the error is now the current line. Use the
CHANGE command to correct the mistake. This command has three parts, separated
by slashes or any other non-alphanumeric character:
The CHANGE command finds the first occurrence in the current line of the character
sequence to be changed and changes it to the new sequence. You do not need to use
the CHANGE command to re-enter an entire line.
To change JO_ID to JOB_ID, change the line with the CHANGE command:
CHANGE /JO_ID/JOB_ID
RUN
DESCRIBE
The description for tables, views, types and synonyms contains the following information:
whether or not null values are allowed (NULL or NOT NULL) for each column
When you do a DESCRIBE, VARCHAR columns are returned with a type of VARCHAR2.
DESCRIBE EMP_DETAILS_VIEW
FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)
SALARY NUMBER(8,2)
STATE_PROVINCE VARCHAR2(25)
COUNTRY_NAME VARCHAR2(40)
REGION_NAME VARCHAR2(25)
COLUMN
{column | expr}
The above query displays column1 with heading First Name, the width of that column is upto 15
characters.
2) The COLUMN FORMAT command was used above to determine the width of the
columns.
The size of a number is defined using the number nine and zero. The number nine
says if there is a digit in that location then print it, if not then print nothing. The
number zero says that if there is a digit in that location then print it, otherwise print a
zero.
Format 9999.00
2345 prints 2345.00
2345.432 prints 2345.43
Element Examples Description
GET
GET file_name[.ext]
To load a file called YEAR_END_RPT with the extension SQL into the buffer, enter
GET YEAR_END_RPT
Example
Edit Command
SQL*Plus does not have a built-in full-screen editor, but it does have the EDIT command.
The SQL*Plus EDIT command allows you to invoke the text editor of your choice to use in
editing SQL statements.
The specific editor invoked depends on the operating system, and on whether or not you’ve
changed the default.
The default editor under Windows NT/95 is Notepad, while under Unix it is vi.
You may, however, configure SQL*Plus to use another editor of your choice.
Do this by defining the user variable named _EDITOR to point to executable of the editor you
want to use.
You invoke the editor with the EDIT command. The syntax looks like this:
ED[IT] [filename]
where:
SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
The list of Dataypes are
1. Binary Datatype
2. Approximate Numeric Datatype
3. Exact Numeric Datatype
4. Character String Datatype
5. Date and time Datatype
1. Binary Datatypes
There are Three types of binary Datatypes which are given below:
timestamp It stores the year, month, day, hour, minute, and the second value.
Applications of SQL
Allows users to define the data in a database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries & pre-compilers.
SELECT Command
The most commonly used SQL command is SELECT statement. It is used to query the
database and retrieve selected data that follow the conditions we want.
[GROUP BY Clause] : Groups rows that share a property so that the aggregate function can be
applied to each group.
[HAVING Clause] : It selects among the groups defined by the GROUP BY clause.
From the above example, select the first name of all the students. To do so, query should be like
this:
Note: the SQL commands are not case sensitive. We can also write the above SELECT
statement as:
Amar
Akbar
Anthony
We can also retrieve data from more than one column. For example, to select first name and last
name of all the students, you need to write
Amar Sharma
Akbar Khan
Anthony Milton
We can also use clauses like WHERE, GROUP BY, HAVING, ORDER BY with SELECT
statement.
SQL Operators
Operator is a reserved word or a character used primarily in an SQL statement WHERE clause to
perform operations, such as comparisons and arithmetic operations.
Unary Operators
A unary operator uses only one operand. A unary operator typically appears with its
operand in the following format.
operator operand
Binary Operators
A binary operator uses two operands. A binary operator appears with its operands in
the following format.
Set Operators
Set operators combine sets of rows returned by queries, instead of individual data
items. All set operators have equal precedence. Oracle Database Lite supports the
following set operators.
UNION
UNION ALL
INTERSECT
MINUS
Arithmetic Operators
Arithmetic operators manipulate numeric operands. The '-' operator is also used in date
arithmetic.
Arithmetic Operators
Character Operators
Character Operators
|| Concatenates character SELECT 'The Name of the employee is: ' || ENAME
FROM EMP;
strings
CONCAT(CONCAT(ENAME
-------------------------
KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
FORD is a ANALYST
SCOTT is a ANALYST
6 rows selected.
Comparison Operators
Comparison operators used in conditions that compare one expression with another.
The result of a comparison can be TRUE, FALSE, or UNKNOWN.
Comparison Operators
ANY/ SOME Compares a value to each value in a list or SELECT * FROM DEPT
WHERE LOC = SOME
returned by a query. Must be preceded by =,
('NEW
!=, >, <, <= or >=. Evaluates to FASLE if the YORK','DALLAS');
query returns no rows.
'DALLAS');
ALL Compares a value with every value in a list or SELECT * FROM emp
WHERE sal >= ALL
returned by a query. Must be preceded by =,
(1400, 3000);
!=, >, <, <= or >=. Evaluates to TRUE if the
query returns no rows.
[NOT] [Not] greater than or equal to x and less than or SELECT ENAME, JOB
FROM EMP WHERE SAL
BETWEEN x and y equal to y.
BETWEEN 3000 AND
5000;
EXISTS TRUE if a sub-query returns at least one row. SELECT * FROM EMP
WHERE EXISTS (SELECT
ENAME FROM EMP WHERE
MGR IS NULL);
x [NOT] TRUE if x does [not] match the pattern y. SELECT * FROM EMP
WHERE ENAME LIKE
LIKE y [ESCAPE z] Within y, the character "%" matches any string
'%E%';
of zero or more characters except null. The
character "_" matches any single character.
Any character following ESCAPE is interpreted
literally, useful when y contains a percent (%)
or underscore (_).
IS [NOT] NULL Tests for nulls. This is the only operator that SELECT * FROM EMP
WHERE COMM IS NOT
should be used to test for nulls.
NULL AND SAL > 1500;
Logical Operators
Logical Operators
Operator Description Example
NOT Returns TRUE if the following condition is FALSE. SELECT * FROM EMP WHERE NOT
(job IS NULL)
Returns FALSE if it is TRUE. If it is UNKNOWN, it
remains UNKNOWN. SELECT * FROM EMP WHERE NOT
(sal BETWEEN 1000 AND 2000)
AND Returns TRUE if both component conditions are TRUE. SELECT * FROM EMP WHERE
job='CLERK' AND deptno=10
Returns FALSE if either is FALSE; otherwise
returns UNKNOWN.
OR Returns TRUE if either component condition is TRUE. SELECT * FROM emp WHERE
job='CLERK' OR deptno=10
Returns FALSE if both are FALSE. Otherwise,
returns UNKNOWN.
Set Operators
Set operators which combine the results of two queries into a single result.
Set Operators
UNION
UNION
INTERSECT and INTERSECT Returns all distinct rows SELECT * FROM orders_list1
Set Operation
The set operators are availed to combine information of similar type from one or more than one
table.
There are distinct types of set operators in SQL. The SQL Set operation is used to combine the
two or more SQL SELECT statements.
1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in both the
tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.
Syntax
Example:
The First table The Second table
ID NAME
ID NAME
1 Jack
3 Jackson
2 Harry
3 Jackson 4 Stephan
5 David
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
Example:
Using the above First and Second table.
Intersect query will be:
ID NAME
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
Example
Using the above First and Second table.
Minus query will be:
ID NAME
1 Jack
2 Harry
SQL EXPRESSION
An SQL expression is a combination of one or more values, operators.
These expressions are further classified into three types −
Boolean Expressions
Numeric Expressions
Date and time Expressions
SQL Boolean Expressions are SQL expressions that return only Boolean Datatype as a
result. They return either TRUE, FALSE or UNKNOWN as the result. If the condition is met,
these expressions return TRUE; and FALSE otherwise. UNKNOWN is returned when either of
the operands in the expression is a NULL value.
SQL Numeric expressions are comprised of two operands and an SQL Arithmetic Operator.
These expressions are used to perform any mathematical operation in any query. Hence, the
operands must always be numerals and the return value will always be a number as well.
Syntax
Example
SELECT 15 + 6;
Output
21
SQL Date Expressions
SQL Date Expressions are used to compare date related values with current system date and time
values.
SELECT CURRENT_TIMESTAMP;
Output
Current_Timestamp
2009-11-12 06:40:23
Functions
SQL Server has many built-in functions.
This reference contains string, numeric, date, conversion, and some advanced functions in SQL
Server.
1) Numeric Functions:
Numeric functions are used to perform operations on numbers. They accept numeric values as
input and return numeric values as output. Few of the Numeric functions are:
Function Name Return Value
ABS (x) Absolute value of the number 'x'
CEIL (x) Integer value that is Greater than or equal to the number 'x'
FLOOR (x) Integer value that is Less than or equal to the number 'x'
TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places
ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal
places
The following examples explains the usage of the above numeric functions
Function Name Examples Return Value
ABS (x) ABS (1) 1
ABS (-1) -1
CEIL (x) CEIL (2.83) 3
CEIL (2.49) 3
CEIL (-1.6) -1
FLOOR (x) FLOOR (2.83) 2
FLOOR (2.49) 2
FLOOR (-1.6) -2
TRUNC (x, y) ROUND (125.456, 1) 125.4
ROUND (125.456, 0) 125
ROUND (124.456, -1) 120
ROUND (x, y) TRUNC (140.234, 2) 140.23
TRUNC (-54, 1) 54
TRUNC (5.7) 5
TRUNC (142, -1) 140
These functions can be used on database columns.
For Example: Let's consider the product table used in sql joins. We can use ROUND to round off
the unit_price to the nearest integer, if any product has prices in fraction.
SELECT ROUND (unit_price) FROM product;
2) Character or Text Functions:
Character or text functions are used to manipulate text strings. They accept strings or characters
as input and can return both character and number values as output.
Few of the character or text functions are as given below:
Function Name Return Value
LOWER (string_value) All the letters in 'string_value' is converted to lowercase.
ROUND (x,date_format) Returns the date 'x' rounded off to the nearest century, year, month,
date, hour, minute, or second as specified by the 'date_format'.
Returns the date 'x' lesser than or equal to the nearest century, year,
TRUNC (x, date_format) month, date, hour, minute, or second as specified by the
'date_format'.
NEXT_DAY (x, Returns the next date of the 'week_day' on or after the date 'x' occurs.
week_day)
LAST_DAY (x) It is used to determine the number of days remaining in a month from
the date 'x' specified.
SYSDATE Returns the systems current date and time.
NEW_TIME (x, zone1, Returns the date and time in zone2 if date 'x' represents the time in
zone2) zone1.
The below table provides the examples for the above functions
Function Name Examples Return
Value
ADD_MONTHS ( ) ADD_MONTHS ('16-Sep-81', 3) 16-Dec-81
MONTHS_BETWEEN( ) MONTHS_BETWEEN ('16-Sep-81', '16-Dec-81') 3
NEXT_DAY( ) NEXT_DAY ('01-Jun-08', 'Wednesday') 04-JUN-08
LAST_DAY( ) LAST_DAY ('01-Jun-08') 30-Jun-08
NEW_TIME( ) NEW_TIME ('01-Jun-08', 'IST', 'EST') 31-May-08
4) Conversion Functions:
These are functions that help us to convert a value in one form to another form. For Ex: a null
value into an actual value, or a value from one datatype to another datatype like NVL,
TO_CHAR, TO_NUMBER, TO_DATE.
Few of the conversion functions available in oracle are:
Function Name Return Value
TO_CHAR (x [,y]) Converts Numeric and Date values to a character string value. It
cannot be used for calculations since it is a string value.
TO_DATE (x [, Converts a valid Numeric and Character values to a Date value.
date_format]) Date is formatted to the format specified by 'date_format'.
NVL (x, y) If 'x' is NULL, replace it with 'y'. 'x' and 'y' must be of the same
datatype.
DECODE (a, b, c, d, e, Checks the value of 'a', if a = b, then returns 'c'. If a = d, then
default_value) returns 'e'. Else, returns default_value.
The below table provides the examples for the above functions
Function Name Examples Return Value
TO_CHAR () TO_CHAR (3000, '$9999') $3000
TO_CHAR (SYSDATE, 'Day, Month YYYY') Monday, June 2008
TO_DATE () TO_DATE ('01-Jun-08') 01-Jun-08
NVL () NVL (null, 1) 1
SQL COUNT (): This function returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. If the WHERE condition is not specified, then the
query returns the total number of rows in the table.
For Example: If you want the number of employees in a particular department, the query would
be:
SELECT COUNT (*) FROM employee WHERE dept = 'Electronics';
The output would be '2' rows.
If you want the total number of employees in all the department, the query would take the form:
SELECT COUNT (*) FROM employee;
The output would be '5' rows.
SQL DISTINCT(): This function is used to select the distinct rows.
For Example: If you want to select all distinct department names from employee table, the
query would be:
SELECT DISTINCT dept FROM employee;
To get the count of employees with unique name, the query would be:
SELECT COUNT (DISTINCT name) FROM employee;
SQL MAX(): This function is used to get the maximum value from a column.
To get the maximum salary drawn by an employee, the query would be:
SELECT MAX (salary) FROM employee;
SQL MIN(): This function is used to get the minimum value from a column.
To get the minimum salary drawn by an employee, he query would be:
SELECT MIN (salary) FROM employee;
SQL AVG(): This function is used to get the average value of a numeric column.
To get the average salary, the query would be
SELECT AVG (salary) FROM employee;
SQL SUM(): This function is used to get the sum of a numeric column
To get the total salary given out to the employees,
SELECT SUM (salary) FROM employee;
SQL Transactions
A transaction is a unit or sequence of work that is performed on a database.
Transactional Control Commands
COMMIT − to save the changes.
ROLLBACK − to roll back the changes.
SAVEPOINT − creates points within the groups of transactions in which to
ROLLBACK.
SET TRANSACTION − Places a name on a transaction.
The COMMIT command is the transactional command used to save changes invoked by a
transaction. It saves all the transactions occurred on the database since the last COMMIT or
ROLLBACK.
COMMIT;
Example
Following query would delete those records from the table which have AGE as 25 and then
COMMIT the changes in the database.
Verification
The two rows from the table would be deleted and if you verify the contents of the
CUSTOMERS table using the SELECT statement as −
The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database. This command can only undo transactions since the last
COMMIT or ROLLBACK.
ROLLBACK;
Example
Following query would delete those records from the table where
the AGE value is 25 and then ROLLBACK the changes in the
database.
ROLLBACK;
Verification
The delete operation would not impact the table and the SELECT
statement would produce the following result.
The SAVEPOINT Command
Usually, when you execute the ROLLBACK command, it undoes the changes until the last
COMMIT. But, if you create save points you can partially roll the transaction back to these
points. You can create multiple save points between two commits.
SAVEPOINT savepoint_name;
Then, to roll back to the SAVEPOINT created, you can use the following syntax −
ROLLBACK TO savepoint_name;
The SET TRANSACTION Command
The SET TRANSACTION command can be used to initiate a database transaction. This
command is used to specify characteristics for the transaction that follows. For example, you can
specify a transaction to be read only or read write.
Syntax