0% found this document useful (0 votes)
51 views33 pages

ORACL

SQL*Plus is a client terminal software that allows users to interact with an Oracle server to manipulate data and data structures. It includes menus for file, edit, search, options, and help. The file menu allows users to open, save, spool, run, cancel, and exit scripts. The edit menu allows users to copy, paste, clear, and define an editor. The search menu allows users to find and find next text. The options menu allows users to set environment variables. The help menu displays SQL*Plus version and copyright information. SQL*Plus also supports standard SQL commands to edit scripts and correct errors, and the DESCRIBE command describes tables, views, columns, and data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views33 pages

ORACL

SQL*Plus is a client terminal software that allows users to interact with an Oracle server to manipulate data and data structures. It includes menus for file, edit, search, options, and help. The file menu allows users to open, save, spool, run, cancel, and exit scripts. The edit menu allows users to copy, paste, clear, and define an editor. The search menu allows users to find and find next text. The options menu allows users to set environment variables. The help menu displays SQL*Plus version and copyright information. SQL*Plus also supports standard SQL commands to edit scripts and correct errors, and the DESCRIBE command describes tables, views, columns, and data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

SQL * PLUS

SQL is a language, SQL*Plus is a tool.


SQL*Plus is a client terminal software allowing users to interact with Oracle server to
manipulate data and data structures.
MENUS
SQL * plus interface includes following menus:
 File
 Edit
 Search
 Options
 Help
File Menu:
The File menu has the following options:
Option Description of File Menu Option
Open The Open option retrieves a previously stored script

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

The Help menu has the following option:


Option Description of Help Menu Option
About SQL*Plus Displays the SQL*Plus version number and copyright information.

STANDARD SQL COMMANDS

Command Abbreviation Purpose


APPEND text A text adds text at the end of a line
CHANGE /old/new C /old/new changes old to new in a line
CHANGE /text C /text deletes text from a line
CLEAR BUFFER CL BUFF deletes all lines
DEL (none) deletes the current line
DEL n (none) deletes line n
DEL * (none) deletes the current line
DEL n * (none) deletes line n through the current line
DEL LAST (none) deletes the last line
DEL m n (none) deletes a range of lines (m to n)
DEL * n (none) deletes the current line through line n
INPUT I adds one or more lines
INPUT text I text adds a line consisting of text
LIST L lists all lines in the SQL buffer
LIST n L n or n lists line n
LIST * L* lists the current line
LIST n * Ln* lists line n through the current line
LIST LAST L LAST lists the last line
LIST m n Lmn lists a range of lines (m to n)
LIST * n L*n lists the current line through line n
EDITING THE COMMAND LINE:

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:

SELECT EMPLOYEE_ID, LAST_NAME, JO_ID, SALARY


FROM EMP_DETAILS_VIEW
WHERE JOB_ID='SA_MAN';

You see this message on your screen:

SELECT EMPLOYEE_ID, LAST_NAME, JO_ID, SALARY


*
ERROR at line 1:
ORA-00904: invalid column name

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 word CHANGE or the letter C


 the sequence of characters you want to change
 the replacement sequence of characters

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.

Correcting the Error

To change JO_ID to JOB_ID, change the line with the CHANGE command:

CHANGE /JO_ID/JOB_ID

The corrected line appears on your screen:

1* SELECT EMPLOYEE_ID, FIRST_NAME, JOB_ID, SALARY


Now that you have corrected the error, you can use the RUN command to run the
command again:

RUN

SQL*Plus correctly displays the query and its result:

1 SELECT EMPLOYEE_ID, LAST_NAME, JOB_ID, SALARY


2 FROM EMP_DETAILS_VIEW
3* WHERE JOB_ID='SA_MAN'

EMPLOYEE_ID LAST_NAME JOB_ID MONTHLY SALARY


----------- ------------------------- ---------- --------------
145 Russell SA_MAN $14,000
146 Partners SA_MAN $13,500
147 Errazuriz SA_MAN $12,000
148 Cambrault SA_MAN $11,000
149 Zlotkey SA_MAN $10,500

DESCRIBE

The description for tables, views, types and synonyms contains the following information:

 each column's name

 whether or not null values are allowed (NULL or NOT NULL) for each column

 datatype of columns, for example, CHAR, DATE, LONG, LONGRAW, NUMBER,


RAW, ROWID, VARCHAR2 (VARCHAR), or XMLType

 precision of columns (and scale, if any, for a numeric column)

When you do a DESCRIBE, VARCHAR columns are returned with a type of VARCHAR2.

DESCRIBE EMP_DETAILS_VIEW

Name Null? Type

----------------------------------------- -------- ----------------

EMPLOYEE_ID NOT NULL NUMBER(6)

FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)

SALARY NUMBER(8,2)

CITY NOT NULL VARCHAR2(30)

STATE_PROVINCE VARCHAR2(25)

COUNTRY_NAME VARCHAR2(40)

REGION_NAME VARCHAR2(25)

COLUMN

{column | expr}

Specifies display attributes for a given column, such as

 text for the column heading

 format for numeric columns

1)COLUMN C1 heading “First Name” FORMAT a15

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.

The following are examples of COLUMN FORMAT with numbers:


Format 9999
2345 prints 2345
2345.432 prints 2345
23456 prints #### too large.

Format 9999.00
2345 prints 2345.00
2345.432 prints 2345.43
Element Examples Description

, 9,999 Displays a comma in the specified position.


(comma)

. 99.99 Displays a period (decimal point) to separate the integral and


(period) fractional parts of a number.

$ $9999 Displays a leading dollar sign.

0 0999 Displays leading zeros


9990
Displays trailing zeros.

GET

GET file_name[.ext]

If you want to load a script the above command is used.

To load a file called YEAR_END_RPT with the extension SQL into the buffer, enter

GET YEAR_END_RPT

Starting and Shutting Down a Database with SQL*Plus

To start a database, enter:

SQL> STARTUP [PFILE=path\filename]

This command uses the initialization parameter file specified in path\filename.

Example

SQL> STARTUP PFILE=C:\app\username\product\11.2.0\admin\orcl\pfile\init2.ora

To stop a database, enter:

SQL> SHUTDOWN [mode]

The mode is normal, immediate, or abort.


In a normal shutdown, Oracle Database waits for all currently connected users to
disconnect and disallows any new connections before shutting down. This is the default mode.
In an immediate shutdown, Oracle Database terminates and rolls back active transactions,
disconnects clients, and shuts down.
In an abort shutdown, Oracle Database terminates active transactions and disconnects
users; it does not roll back transactions. The database performs automatic recovery and rollback
the next time it is started. Use this mode only in emergencies.

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.

Invoking the Editor

You invoke the editor with the EDIT command. The syntax looks like this:

ED[IT] [filename]

where:

ED[IT] May be abbreviated ED.


Filename: an argument indicating a specific file you want to edit. The default extension is .SQL,
but you may supply a different extension if you like.

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:

Data Type Description

Binary It has a maximum length of 8000 bytes. It contains fixed-length binary


data.

Varbinary It has a maximum length of 8000 bytes. It contains variable-length binary


data.

Image It has a maximum length of 2,147,483,647 bytes. It contains variable-


length binary data.

2. Approximate Numeric Datatype :


The subtypes are given below:

Data From To Description


type
float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value
e.g. 6.2, 2.9 etc.

real -3.40e + 38 3.40E + 38 It specifies a single precision floating point


number

3. Exact Numeric Datatype


The subtypes are given below:

Data type Description

int It is used to specify an integer value.

smallint It is used to specify small integer value.

bit It has the number of bits to store.

decimal It specifies a numeric value that can have a decimal number.

numeric It is used to specify a numeric value.

4. Character String Datatype


The subtypes are given below:

Data type Description

char It has a maximum length of 8000 characters. It contains Fixed-length non-


unicode characters.

varchar It has a maximum length of 8000 characters. It contains variable-length non-


unicode characters.

text It has a maximum length of 2,147,483,647 characters. It contains variable-


length non-unicode characters.

5. Date and time Datatypes


The subtypes are given below:
Datatype Description

date It is used to store the year, month, and days value.

time It is used to store the hour, minute, and second values.

timestamp It stores the year, month, day, hour, minute, and the second value.

SQL Language Basics


SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in a relational database.

Applications of SQL

 Allows users to access data in the relational database management systems.

 Allows users to describe the data.

 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.

 Allows users to create and drop databases and tables.

 Allows users to create view, stored procedure, functions in a database.

 Allows users to set permissions on tables, procedures and views.

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.

Syntax of select statement.

SELECT expressions FROM tables WHERE conditions;


Here, expression is the column that we want to retrieve.

Tables indicate the tables, we want to retrieve records from.


Optional clauses in SELECT statement

There are some optional clauses in SELECT statement:

[WHERE Clause] : It specifies which rows to retrieve.

[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.

[ORDER BY Clause] : It specifies an order in which to return the rows.

For example, let a database table: student_details;

ID First_name Last_name Age Subject Hobby

1 Amar Sharma 20 Maths Cricket

2 Akbar Khan 22 Biology Football

3 Anthony Milton 25 Commerce Gambling

From the above example, select the first name of all the students. To do so, query should be like
this:

SELECT first_name FROM student_details;

Note: the SQL commands are not case sensitive. We can also write the above SELECT
statement as:

Select first_name from student_details;

Now, you will get following data:

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

SELECT first_name, last_name FROM student_details;

Now, you will get following data:

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.

operand1 operator operand2

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

Operator Description Example

+ (unary) Makes operand positive SELECT +3 FROM DUAL;

- (unary) Negates operand SELECT -4 FROM DUAL;

/ Division (numbers and dates) SELECT SAL / 10 FROM EMP;

* Multiplication SELECT SAL * 5 FROM EMP;

+ Addition (numbers and dates) SELECT SAL + 200 FROM EMP;


Operator Description Example

- Subtraction (numbers and dates) SELECT SAL - 100 FROM EMP;

Character Operators

Character operators used in expressions to manipulate character strings are listed


in Table 2-3.

Character Operators

Operator Description Example

|| Concatenates character SELECT 'The Name of the employee is: ' || ENAME
FROM EMP;
strings

Concatenating Character Strings


 SELECT CONCAT (CONCAT (ENAME, ' is a '),job) FROM EMP WHERE SAL > 2000;

This returns the following output.

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

Operator Description Example

= Equality test. SELECT ENAME


"Employee" FROM EMP
WHERE SAL = 1500;

!=, ^=, <> Inequality test. SELECT ENAME FROM EMP


WHERE SAL ^= 5000;

> Greater than test. SELECT ENAME


"Employee", JOB
"Title" FROM EMP
WHERE SAL > 3000;

< Less than test. SELECT * FROM PRICE


WHERE MINPRICE < 30;

>= Greater than or equal to test. SELECT * FROM PRICE


WHERE MINPRICE >= 20;

<= Less than or equal to test. SELECT ENAME FROM EMP


WHERE SAL <= 1500;

IN "Equivalent to any member of" test. Equivalent SELECT * FROM EMP


WHERE ENAME IN
to "=ANY".
('SMITH', 'WARD');

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.

NOT IN Equivalent to "!=ANY". Evaluates to FALSE if SELECT * FROM DEPT


WHERE LOC NOT IN
any member of the set is NULL.
('NEW YORK',
Operator Description Example

'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 which manipulate the results of conditions

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

Operator Description Example

UNION Returns all distinct rows SELECT * FROM

selected by either query.


(SELECT ENAME FROM EMP WHERE
JOB = 'CLERK'

UNION

SELECT ENAME FROM EMP WHERE


JOB = 'ANALYST');

UNION ALL Returns all rows selected by SELECT * FROM

either query, including all


(SELECT SAL FROM EMP WHERE
Operator Description Example

duplicates. JOB = 'CLERK'

UNION

SELECT SAL FROM EMP WHERE


JOB = 'ANALYST');

INTERSECT and INTERSECT Returns all distinct rows SELECT * FROM orders_list1

ALL selected by both queries.


INTERSECT

SELECT * FROM orders_list2

MINUS Returns all distinct rows SELECT * FROM (SELECT SAL


FROM EMP WHERE JOB =
selected by the first query but
'PRESIDENT'
not the second.
MINUS

SELECT SAL FROM EMP WHERE


JOB = 'MANAGER');

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.

Types of Set Operation

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

SELECT column_name FROM table1


UNION
SELECT column_name FROM table2

Example:
The First table The Second table

ID NAME
ID NAME
1 Jack
3 Jackson
2 Harry

3 Jackson 4 Stephan

5 David

Union SQL query will be:

SELECT * FROM First


UNION
SELECT * FROM Second;
The result set table will look like:

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:

SELECT column_name FROM table1


UNION ALL
SELECT column_name FROM table2;

Example: Using the above First and Second table.


Union All query will be like:

SELECT * FROM First


UNION ALL
SELECT * FROM Second;

The resultset table will look like:

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

SELECT column_name FROM table1


INTERSECT
SELECT column_name FROM table2;

Example:
Using the above First and Second table.
Intersect query will be:

SELECT * FROM First


INTERSECT
SELECT * FROM Second;
The result set table will look like:

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:

SELECT column_name FROM table1


MINUS
SELECT column_name FROM table2;

Example
Using the above First and Second table.
Minus query will be:

SELECT * FROM First


MINUS
SELECT * FROM Second;

The resultset table will look like:

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

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.

SELECT column1, column2, columnN FROM table_name

WHERE BOOLEAN EXPRESSION;

SQL Numeric Expressions

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

Following is the syntax −

SELECT numerical_expression as OPERATION_NAME


FROM table_name
WHERE NUMERICAL EXPRESSION ;

Here, the numerical_expression is used for a mathematical expression or any formula.

Example

Following is a simple example showing the usage of SQL Numeric Expressions −

SELECT 15 + 6;

Output

The output table is retrieved as −

21
SQL Date Expressions

SQL Date Expressions are used to compare date related values with current system date and time
values.

SELECT column_name(s) FROM table_name WHERE DATE EXPRESSION ;

SELECT CURRENT_TIMESTAMP;

Output

The output table is displayed as −

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.

UPPER (string_value) All the letters in 'string_value' is converted to uppercase.


INITCAP (string_value) All the letters in 'string_value' is converted to mixed case.
LTRIM (string_value, All occurrences of 'trim_text' is removed from the left of
trim_text) 'string_value'.
RTRIM (string_value, All occurrences of 'trim_text' is removed from the right of
trim_text) 'string_value' .
TRIM (trim_text FROM All occurrences of 'trim_text' from the left and right of
string_value) 'string_value' , 'trim_text' can also be only one character long .
SUBSTR (string_value, Returns 'n' number of characters from 'string_value' starting from
m, n) the 'm' position.
LENGTH (string_value) Number of characters in 'string_value' in returned.
LPAD (string_value, n, Returns 'string_value' left-padded with 'pad_value' . The length of
pad_value) the whole string will be of 'n' characters.
RPAD (string_value, n, Returns 'string_value' right-padded with 'pad_value' . The length of
pad_value) the whole string will be of 'n' characters.
For Example, we can use the above UPPER() text function with the column value as follows.
SELECT UPPER (product_name) FROM product;
The following examples explains the usage of the above character or text functions
Function Name Examples Return Value
LOWER(string_value) LOWER('Good Morning') good morning
UPPER(string_value) UPPER('Good Morning') GOOD
MORNING
INITCAP(string_value) INITCAP('GOOD MORNING') Good Morning
LTRIM(string_value, trim_text) LTRIM ('Good Morning', 'Good) Morning
RTRIM (string_value, trim_text) RTRIM ('Good Morning', ' Good
Morning')
TRIM (trim_text FROM TRIM ('o' FROM 'Good Morning') Gd Mrning
string_value)
SUBSTR (string_value, m, n) SUBSTR ('Good Morning', 6, 7) Morning
LENGTH (string_value) LENGTH ('Good Morning') 12
LPAD (string_value, n, pad_value) LPAD ('Good', 6, '*') **Good
RPAD (string_value, n, pad_value) RPAD ('Good', 6, '*') Good**
3) Date Functions:
These are functions that take values that are of datatype DATE as input and return values of
datatypes DATE, except for the MONTHS_BETWEEN function, which returns a number as
output.
Few date functions are as given below.
Function Name Return Value
ADD_MONTHS (date, Returns a date value after adding 'n' months to the date 'x'.
n)
MONTHS_BETWEEN Returns the number of months between dates x1 and x2.
(x1, x2)

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 GROUP Functions


Group functions are built-in SQL functions that operate on groups of rows and return one value
for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT

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

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.

The syntax for the COMMIT command is as follows.

COMMIT;
Example

Following query would delete those records from the table which have AGE as 25 and then
COMMIT the changes in the database.

DELETE FROM CUSTOMERS WHERE AGE = 25;


COMMIT;

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 −

SELECT * FROM CUSTOMERS;

The table will be displayed as follows −


The ROLLBACK Command

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.

The syntax for a ROLLBACK command is as follows −

ROLLBACK;

Example

Consider the CUSTOMERS table having the following records −

Following query would delete those records from the table where
the AGE value is 25 and then ROLLBACK the changes in the
database.

DELETE FROM CUSTOMERS WHERE AGE = 25;

ROLLBACK;

Verification

The delete operation would not impact the table and the SELECT
statement would produce the following result.
The SAVEPOINT Command

A SAVEPOINT is a logical rollback point in a transaction.

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.

The syntax to create a SAVEPOINT among the transactions is as shown below.

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

The syntax for a SET TRANSACTION command is as follows.

SET TRANSACTION [ READ WRITE | READ ONLY ];

You might also like