Вы находитесь на странице: 1из 43

COMPLETE SQL NOTES

SQL- Structured Query Language


Definition:
▪ SQL is a query language used for accessing and modifying information in one
or more data tables and rows of a database.

SQL Design:
▪ IBM first developed SQL in 1970s. Also, it is an ANSI/ISO standard.
▪ It is a standard universal language.
▪ It is used by most of the RDMS (Relational Database Management Systems) such as Oracle,
MySQL, MS-SQL, Sybase etc.

Relational Database Concepts:

▪ It is the collection of relations or two-dimensional tables.


▪ Dr. E.F Codd proposed the relational model for database System in 1970.
▪ Relational model consists of the following
1. Collections of objects or relations.
2. Set of operators to act on the relations.
3. Data integrity for accuracy and consistency.

Data integrity:
▪ It means which maintains the correct data in the database.
▪ Data integrity: - it means which maintains the correct data in the database
▪ We can preserve data integrity by two types.
1. Data Types
2. Constraints

1. Data types:
Which ensures the type of data which you can store in each column.
Examples: Int, Varchar, Text, Date etc.
2. Constraints.
These are the restrictions or conditions that are used on the col of the table to preserve
data correctness.
There are 7 constraints present in all RDMS
1. NOT NULL
2. UNIQUE
3. PRIMERY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
7. INDEX

1. NOT NULL: Ensure that a column can not have a null value.
2. UNIQUE: Ensures that all values in a column are different.
3. PRIMERY KEY: A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in
a table.
4. FOREIGN KEY: Uniquely identifies a row/ record in another table.
5. CHECK: Ensures that all values in a column satisfies a specific function.
6. DEFAULT: sets a default value for column when no values specified.
7. INDEX: used to create and retrieve data from the database very quickly.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

Basic Commands In SQL:


1. Clear Screen or cl scr
2. Show
3. Set
4. Describe or desc

1. CL SCR : it is used to clear screen


2. SHOW: This is used to view the default settings and also the user information of the databases.
3. SET: This is used to change the default settings of SQL * Plus Tool
Example . set pagesize 100, Set lines 100
4. DESC: this is used to view or display structure of the table object. (structure means col, data
types applied on each col and only the NOT NULL constraints).

Tables Present In Oracle SQL Database:

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

1. Employee Table

2. Department Table:

3. Salary Grade Table:

SQL Statements: SQL Statements are divided into 5 categories

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

1. DDL- Data Definition Language


DDL are used to define the database structure or table
Statements Description
Create Create a new Database/ table
Alter Modifies the structure of database/ table
Drop Deletes a database/table
Truncate Remove all table records including allocated
table spaces
Rename Rename the database/table

2. DML- Data Manipulation Language:


DML are used for managing data within table object.

Statements Description
Select Retrieve data from the table
Insert Insert data into a table
Update Update existing data with new data within a
table
Delete Deletes the records/ rows from the table
Merge Merge( also called UPSERT) statements to
insert new records or update existing records
depending on condition matches or not
Lock table Lock table statements to lock one or more
tables in a specified mode. Table access
denied to a other users for the duration of
table creation.
Call explain plan Statements are supported in PL/SQL only for
executed dynamically. Call a PL/SQL
program or EXPLAIN PATH access the data
path.

3. DCL:- Data Control Language


DCL are used to give privileges to access limited data
Statements Description
Grant Gives privileges to user for accessing
database data.
Revoke Take back for given privileges
Analyze Analyze statements to collect statics
information about index, cluster, table
Audit To track the occurrence of a specific SQL
statements or all SQL statements during the
user sessions.
Comment Write comments to the data table

4. TCL: Transaction Control Language:


TCL are used to apply the changes permanently save into database
Commit Permanent work save into database
Rollback Restores database to original form since the
las COMMIT
Savepoint Create SAVEPOINT for later use
ROLLBACK

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

Set transaction SET TRANSACTION command set the


transaction properties such as read-write/
read only access.

Autcommit True or false

5. SCS: Session Control Statements


SCS are used to manage properties dynamically of a user session.
Statements Description
Alter session Alter session statements to modify
conditions or parameters that are affect to
database connection
Set role SET ROLE statements to enable or disable
the roles that are enabled for the session

Note:
SQL is not case sensitive.
But SQL Data is a case sensitive.

1. Number Datatypes:

Data Type Description


NUMBER data type use to store numeric data.
NUMBER data type have precision and scale.
Storage Range : Precision range(p) : 1 to 38 and Scale range(s) : -84 to
127
NUMBER Subtypes : This sub type supported ANSI, DB2, and SQL
data type define different type storage range.
Maximum
ANSI, DB2 Datatypes Oracle Data types
Precision
INTEGER 38 digits
NUMBER [ ( precision [, INT 38 digits NUMBER(p,0)
scale ] ) SMALLINT 38 digits
FLOAT [ (size) ] 126 binary digits FLOAT(126)
DOUBLE
126 binary digits FLOAT(126)
PRECISION
REAL 63 binary digits FLOAT(63)
DECIMAL[(precision
38 digits
[, scale ])]
NUMBER(p,s)
NUMERIC[(precision
38 digits
[, scale ])]

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

FLOAT data type is subtype of NUMBER datatype.


FLOAT [ ( precision ) ] Storage Range : Precision range(p) : 1 to 126
Example : col1 FLOAT(2)
BINARY_FLOAT datatype use binary precision (32-bit).
This data type requires 5 bytes including length byte.
BINARY_FLOAT
Advantages : Arithmetic calculations fast and reduces the storage
requirements.

BINARY_DOUBLE datatype use double binary precision (64-bit).


BINARY_DOUBLE
This data type requires 9 bytes including length byte.

2. Character Datatypes

Data Type Description Storage(Maximum)


CHAR data type use to store character data within
CHAR [ (size) ] 2000 bytes
predefined length.

NCHAR data type use to store national character data


NCHAR [ (size) ] 2000 bytes
within predefined length.

VARCHAR2 data type use to store variable strings data


within predefined length.
You have to must specify the size of VARCHAR2
datatype.
VARCHAR2(size) VARCHAR2 Subtypes : This sub type define same 4000 bytes
length value.
Sub Datatype Description
You can also use this data
VARCHAR(size)
type.

NVARCHAR2 data type use to store Unicode string data


within predefined length.
NVARCHAR2(size) 4000 bytes
You have to must specify the size of NVARCHAR2
datatype.

3. LONG and ROW Datatypes


LONG and ROW data type store variable strings data within predefined length, This datatype
use for backward compatibility. following are LONG and ROW datatypes in Oracle SQL:

Data Type Description Storage(Maximum)


RAW data type use to store binary data such as image,
RAW(size) graphics etc. 2000 bytes
You have to must specify the size of RAW column data type.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

LONG data type use to store variable strings data within


LONG predefined length, This data type use for backward upto 2 gigabytes
compatibility. Please use CLOB instead of LONG type.

LONG RAW data type same as LONG type use to store


variable strings data within predefined length, This data type
LONG RAW upto 2 gigabytes
use for backward compatibility. Please use BLOB instead of
LONG RAW type.

4. ROWID Datatypes
ROWID data type represent actual storage address of a row. following are ROWID datatypes
in Oracle SQL:

Data Type Description Storage(Maximum)


ROWID data type represent actual storage address of a row. and table index
ROWID identities as a logical rowid. This data type use for backward compatibility.
Recommended to use UROWID data type.

UROWID data type identify as universal rowid. Same as


ROWID type and use newer developing applications use
UROWID[(size)] 4000 bytes
UROWID data type.
You can specify optional size of UROWID column type.

5. Date/Time Datatypes
Variable that has date/time data type hold value call datetimes. Oracle SQL automatically
converts character value in to default date format ('DD-MON-YY') TO_DATE values.
Following are Date/Time data types in Oracle SQL:

Data Type Description Range


Jan 1, 4712 BC
DATE data type to store valid date-time format with fixed length. to
DATE
Starting date from Jan 1, 4712 BC to Dec 31, 9999 AD. Dec 31, 9999
AD

TIMESTAMP data type to store valid date (year, month, day) with time (hour,
minute, second).
Type TIMESTAMP Type

TIMESTAMP Syntax : TIMESTAMP [(fractional_seconds_precision)]


Example : TIMESTAMP '2014-04-13 18:10:52.124'
1 fractional_seconds_precision optionally specifies the number of
digits in the fractional part of the SECOND datetime field. Range
0 to 9. The default is 6.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

Syntax : TIMESTAMP [(fractional_seconds_precision) ] WITH TIME


ZONE
Example : TIMESTAMP '2014-04-13 18:10:52.124 +05:30'
WITH TIME ZONE specify the UTC time zone. Following two
2 values represent same instant in UTC.
TIMESTAMP '1999-04-15 8:00:00 -8:00' (8.00 AM Pacific
Standard Time) or
TIMESTAMP '1999-04-15 11:00:00 -5:00' (11:00 AM Eastern
Standard Time) both are same.
Syntax : TIMESTAMP [(fractional_seconds_precision) ] WITH LOCAL
TIME ZONE
Example : COL_NAME TIMESTAMP(3) WITH LOCAL TIME ZONE;
WITH LOCAL TIME ZONE specify when you insert value into
3
database column, value is store to the database time zone, and
the time-zone displacement is not stored in the column. When you
retrieve value oracle database returns it in your UTC local time
zone.
Example :
CREATE TABLE time_table(
start_time TIMESTAMP,
time1 INTERVAL DAY (6) TO SECOND (5),
time2 INTERVAL YEAR TO MONTH
);

Variable that has interval data type hold value call intervals. Following are Interval data types
in SQL:
Data Type Description
INTERVAL YEAR TO MONTH data type to store and manipulate intervals of year
and month.
INTERVAL
Syntax : INTERVAL YEAR [ (year_precision) ] TO MONTH
YEAR TO
Note : precision specifies number of digits in years field range from 0 to 9 and
MONTH
default is 2.
Size of datatype 5 bytes fixed.

INTERVAL DAY TO SECOND data type to store and manipulate intervals of days,
hours, minutes, and seconds.
INTERVAL Syntax : INTERVAL DAY[(day_precision)] TO
DAY TO SECOND[(fractional_seconds_precision)]
SECOND Note : day_precision specifies number of digits in days field range from 0 to 9. The
default is 2.
fractional_seconds_precision specifies number of digits in days field range from 0

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

to 9. The default is 6.
Size of datatype 11 bytes fixed.

4. Large Object Datatypes (LOB types)


LOB data types use to store large object such as image, video, graphics, text, audio. Maximum
size up to 4 Gigabytes. following are LOB data types in SQL:

Data
Description Storage(Maximum)
Type
Size: up to 4GB (232 - 1
BFILE data type to store large binary object into Operating bytes)
System file. This data type variable store full file locator's path Directory name: 30
BFILE
which point to a stored binary object with in server. BFILE data character
type read only, you can't modify them. File name: 255
characters

BLOB data type same as BFILE data type to store unstructured Size: 8 TB to 128 TB
BLOB binary object into Operating System file. BLOB type fully (4GB - 1) *
supported transactions are recoverable and replicated. DB_BLOCK_SIZE

CLOB data type to store large blocks of character data into


Size: 8 TB to 128 TB
Database. Store single byte and multi byte character data.
CLOB (4GB - 1) *
CLOB type fully supported transactions are recoverable and
DB_BLOCK_SIZE
replicated.

NCLOB data type to store large blocks of NCHAR data into


Size: 8 TB to 128 TB
Database. Store single byte and multi byte character data.
NCLOB (4GB - 1) *
NCLOB type fully supported transactions are recoverable and
DB_BLOCK_SIZE
replicated.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

QUERIES:

1. Display emp no, emp name, sal as monthly salary and annual salary for all the employees.

2. Display ename, sal as old salary and salary increase with 300 as new salary from emp table.

3. Display emp name , his job hired date , monthly salary and annual salary along with commission
of 360.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

4. DISPLAY EMP NAME ,JOB , MONTHLY SALARY WITH QUARTERLY COMMISSION OF 560.

5. Display emp name, monthly salary , monthly commission, annual salary along with commission of
300 given to 2 quadrants .

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

CONCATANATION:
|| is represented by double vertical line and is used to concatenate columns or col with a string

6. Display the following string for all the employees


Allen is a salesman

7. Display the following the string for all the employees


SMITH is a CLERK and His salary is 800

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

8. Display tag line for Accenture company from emp table

Operators Supported by SQL:


1. Arithmetic operators: +, -, *, /, %
2. Relational Operators: ==, = , <>, <, >, <=, >=
3. Logical operators: AND, OR , NOT
4. Special Operators: IN, LIKE, BETWEEN, IS

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

Oder of evaluation Operators


1. Arithmetic operates
2. Concat
3. Comparison
4. IS, LIKE, IN
5. BETWEEN
6. NOT
7. AND
8. OR

Where clause:

• It is used to restrict the no of records to be written based on the specified condition.


• Where clause checks the condition for each and every records once.
• If the condition is true , it returns the records
• If the condition fails it discards the records and checks the condition for next record in
the table.

SQL WHERE clause is basically use for fetching specific criteria matched data only return.
SQL WHERE clause is optionally clause in DML statement.

SQL WHERE clause we can use with SELECT, UPDATE, DELETE statements. SELECT
statement with WHERE clause execute, fetching all table rows and apply WHERE clause
filtering and finally return the result data.

Notes: You can't use INSERT statement with WHERE clause. But you can use INSERT
Statement with WHERE cause only when you get the filter data from another TABLE.

WHERE clause use with SELECT Statement


When you get table data with specific filtered data, you should use where clause,

Syntax
Considering following syntax that help you to understanding WHERE clause,
SELECT * FROM table_name WHERE condition;

WHERE clause use with UPDATE Statement


When you want to update specific table data you should use UPDATE statement with where
clause. You can update/set more than one columns value.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

Syntax
Considering following syntax that help you to understanding WHERE clause,
UPDATE table_name SET column_name=value1, ... WHERE condition;

WHERE clause use with DELETE Statement


When you want to delete specific table row(s) you should use DELETE statement with
WHERE clause,

Syntax
Considering following syntax that help you to understanding WHERE clause,
DELTE FROM table_name WHERE condition;

WHERE clause use with INSERT Statement


When you want to insert filter data from another table, you should use INSERT statement with
WHERE clause,

Syntax
Considering following syntax that help you to understanding WHERE clause,
INSERT INTO table_name (column_name1, column_name2, ...)
SELECT column_name1, column_name2, ...
FROM another_table_name
WHERE condition;

9. Display the manager no for all the employees who are working in dept no 10.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

10. . Display all the employees whose job is salesman .

11. Display all the employees whose salary is >1600

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

12. display employee number , job for all the employees whose manager number is 7698

13. Display all the employees who doesn’t belongs to deptno 20.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

14. Display all the employees who are working in dept. no 20 or job is Manger

15. Display all the employees whose manager number is 7839 or job is analyst

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

16. Display all the employees whose commission is >= 100 and job is salesman

17. Display all the employees whose manager number is 7698 and joined from 20-feb-81

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

18. Display all the employees who doesn’t belongs to deptno 20 and getting commission
from emp table.

19. Display all the employees who doesn’t belongs to deptno 30 and not getting some
commission from the employee table .

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

SQL IN Condition
SQL IN condition used to allow multiple value in a WHERE clause condition. SQL IN
condition you can use when you need to use multiple OR condition.

SQL IN condition allow only specific value in INSERT, UPDATE, DELETE, SELECT
statement.

Syntax
WHERE column_name IN (value1, value2, ...);

SQL NOT IN Condition


SQL NOT IN condition used to exclude the defined multiple value in a WHERE clause
condition. SQL NOT IN condition also identify by NOT operator.

Syntax
NOT IN condition use with WHERE clause to exclude defined multiple values from record
data.
WHERE column_name NOT IN (value1, value2, ...);

SQL NOT condition used with BETWEEN condition or LIKE condition.


NOT BETWEEN condition;
NOT LIKE condition

20. Display all the employees who are working in deptno 10 or 20 and job is manager or
salesman.

21. Display all the employees whose manager number is either 7698 or 7839 or job is
manager or joined from 20-SEP-81

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

22. Display all the employees who doesn’t belongs to deptno 30 and 40 and job is salesman,
clerk or president .

23. Display all the employees who are working in deptno 30 or 60 or 90 and getting some
commission and manager no is 7698 or 7839

NOT OPERATOR:
• If the condition is true it returns false or vice-verse

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

24. Display all the employees who joined before 23-JAN-82 and the mgr is not as 7566, 7839
and salary is <=3000.

25. Display all the employees whose job is president , manager or analyst and salary is >=
300 and working in deptno 10 or 40

26. Display all the employees whose emp no is 7499,7934 and working as clerk or manager
in deptno 10 or 20 with a salary of 1300 or 1600

27. Display all the information from the emp table if the location is DALLAS ,CHICAGO

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

IS OPERATOR: Is operator is used to evaluate null value in a col.

28. Display all the employees who are working in deptno 30 or 60 or 90 and getting some
commission and manager no is 7698 or 7839

29. Display all the employees who joined before 23-JAN-82 and the mgr is not as 7566, 7839
and salary is <=3000.

30. Display all the employees whose job is president , manager or analyst and salary is >=
300 and working in deptno 10 or 40

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

31. Display all the employees whose emp no is 7499,7934 and working as clerk or manager
in deptno 10 or 20 with a salary of 1300 or 1600

32. Display all the employees who are not getting commission from the employees table .

33. Display all the employee whose job is analyst or manager and not working in deptno 30 or
10 from the emp table

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

34. Display all the employees whose manager no is 7566 or 7788 and not getting commission
with designation as analyst or president .

SQL BETWEEN Clause Statement


SQL BETWEEN clause used for fetching within range data. SQL BETWEEN is simply a
shorthand way of expressing an inclusive range comparison.

SQL Between clause support only range type value like number, dates, character. But not
supporting boolean, string value range.

Syntax
Considering following syntax that help you to understanding BETWEEN clause,
SELECT * FROM table_name
WHERE column_name

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

BETWEEN lower_bound_value AND upper_bound_value;

When SQL query with BETWEEN clause parse into SQL Buffer, it will automatically expand
out into separate comparison clauses.
SELECT * FROM table_name
WHERE column_name <= lower_bound_value
AND column_name >= upper_bound_value;

35. Display all the employee whose salary is in the range of 800 and 3000. And getting some
commission with manager no 7698 or 7782.

36. Display all the employees whose emp no in the range of 7566 and 7840 with designation
as manager, analyst , salesman

37. Display all the employees whose salary is not in the range of 2500 and 5000 and getting
some commission with deptno 30,40, or 20

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

38. Display all the employees whose manager No not b/w 7699 and 7788 and sal is not in the
range of 1600 and 2500 with comm >=500

SQL LIKE Condition (SQL Wildcards


Characters)
SQL Wildcards Characters
SQL Wildcards characters used for searching string pattern. SQL Wildcard character use with
LIKE condition for searching pattern string from database table.

SQL Wildcards Character


Following Wildcard characters pattern use for certain type expression,

Wildcard Description
_ Underscore sign matches any exactly single character with in string.
(underscore sign) Example. 'Op_l Kole', '_pal Kole', 'Opal Kol_'

% Percentage sign matches any number of characters (0 or more characters).


(Percentage sign) Example. 'Op%', '%Kole', 'Opal%'

SQL LIKE Condition


HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

SQL LIKE Condition used with WHERE clause to matches specific pattern. SQL LIKE
condition apply on table column data.

Syntax
Considering following SQL LIKE condition syntax,
SELECT * FROM table_name
WHERE column_name LIKE 'pattern';

Pattern write inside opening or closing single delimit characters (''). Do not use double delimit
characters ("") because double delimit use as delimiter identifier.
...WHERE column_name LIKE 'pattern'; -- Correct way
...WHERE column_name LIKE "pattern"; -- Incorrect way

39. Display all the employees whose name ends with R

40. Display all the employees whose name having char E last char but 1 char from the emp .
41. Display all the employees whose job having substring MAN in it
42. Display all the employees whose job having L as 3rd char and M as last but 2nd char

43. Display all the employees whose name having exactly 5 char

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

44. Display all the employee who are not getting some commission and name doesn’t start with
S and salary is not in the range of 3000 and 5000.

45. Display all the employees whose job having char A and manager no is not as
7902,7788,7782 and salary is in the range of 800 and 3000 .

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

46. Display all the employee Whose salary is in the range 7499 and 7840 and name start with
K as firs char and don’t have manager

47. Display all the employees whose job is manager and who don’t have a manager with
salary >= 3000 from the employee table.

SQL ORDER BY Clause


• SQL ORDER BY clause used to sorting SQL result set either ascending or
descending order.
• SQL ORDER BY clause default record set sorting ascending order. Using DESC
keyword to result set sorting in descending order.
• By default, the data will be sorted in ascending order
• If we want to sort the data in ascending order then we have to explicitly specify the
sorting technique after the col name in order by clause.
• asc :- it sorts the data in ascending order.
• desc:- it sorts the data in descending order.

SQL ORDER BY Clause Syntax


Considering following syntax that help you to understanding ORDER BY clause,
SELECT
column_name1, column_name2, ...
FROM table_name
[ WHERE condition ]
ORDER BY column_name1, column_name2 [ ASC | DESC ];

48. Display all the rocords of the tables by sorting the sal in descending order for those who
are working in deptno 20 and 30.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

49. Display all the records of the table and sort employee name in ascending order for those
employees, whose job is salesman, clerk, or analyst.

NOTE:
• We can pass more than one column in the order by clause to sort the data either in
ascending/descending
• If we pass more than one column in the order by clause, always the first priority will
be given to first column, if we have same values or duplicates values in the first
column, then only those two duplicate values adjacent column data will be sorted
based on sorting technique specified.
50. D

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

51. H

NOTE:

• The data can be sorted using number literal only if the order by item(col name
specified in the order by clause ) must be the number of a SELECT list expression

52. H

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

FUNCTIONS
• Are reusable program, which is a very powerful future in SQL.
• In SQL, function may or may not take the inputs but always return the output.
• It is used to perform the following
i. Calculation
ii. Modifying the o/p for each n every record
iii. Modifying the o/p for group of records.
• Functions are classified into
a. Predefined functions
b. User defined functions

I/P1
I/P2 FUNCTION
O/P
I/P3

1.
Oracle SQL provide buit-in SQL functions. SQL Functions take some values as a arguments,
perform some function logic and returning some values. SQL inbuit function are so many that
all are help us for no need to implementing your own logic.

Oracle SQL built-in functions are following,


1. SQL Numeric Functions
2. SQL String Functions

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

SQL String Functions


SQL numeric function take numeric value (maximum 38 digit) and return numeric
value (maximum 38 digit). SQL numeric function return single row single column
values. Following are some SQL numeric function.

Function Function Parameter Description


ABS ABS(n) Function return absolute value of n values.

Function return average value of


AVG AVG(expression)
expression.

Function take bitwise vector value and


BITAND BITAND
return the bitwise AND vector value.

Function take any number of bit values.


every value is must be either 0 or 1. This
BIN_TO_NUM BIN_TO_NUM(n, ...)
all bit values convert to a hexadecimal
numeric value.

Function return smallest integer round


CEIL CEIL(n) value that is greater then or equal to a
parameter value (n).

COUNT(*) Function return the number of rows in a


COUNT
COUNT(expression) SELECT statement.

Function return largest integer round value


FLOOR FLOOR(n) that is equal to or less then to a parameter
value (n).

Function return exact log value (natural


LN LN(n)
logarithm value).

Function return log value (base on n1


LOG LOG(n1,n2)
value of n2 value).

Function return maximum value of


MAX MAX(expression)
expression.

Function return minimum value of


MIN MIN(expression)
expression.

Function return the reminder value of n1


MOD MOD(n1,n2) divide by n2. Where n1 and n2 is natural
value.

Function return the alternative value if the


NANVL NANVL(value,alternative_value) specified value is NaN (Not a number). If
value not NaN then return original value.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

Function return n1 raised to a n2 power. n1


POWER POWER(n1,n2)
is base value and n2 is any numbers.

Function generate random number


between 0 to 1, but no longer support.
RAND RAND()
Optionally use Rownum to fetch random
record from database table.

Function return the remainder value of n1


REMAINDER REMAINDER(n1,n2) divide by n2. Where n1 and n2 is natural
value.

Function return the round number of


ROUND ROUND(n, decimal_number)
specified nth number of decimal place.

SIGN SIGN(n) Function return the sign of the n number.

Function return the square root of the n


SQRT SQRT(n) number. SQRT function return the real
number.

SUM SUM(expression) Function return the sum of expression.

Function return the truncated number of


TRUN TRUNC(n, decimal_number)
specified nth number of decimal place.

SQL String Functions


SQL String function take some value and return string value. Function return data
type VARCHAR2 if parameter argument CHAR or VARCHAR2 data type. Following
are some SQL String function.

Function Function Parameter Description


Function return the ASCII values of
ASCII ASCII( character )
given argument.

Function return the ASCII value of the


CHR CHR( number )
given argument value.

Function concatenated string1 with


CONCAT CONCAT( string1, string2 ) string2 and return to a concatenated
string.

Function return capitalize string/char


INITCAP INITCAP( char/string )
(capitalize first letter of each word).

INSTR( original_string, Function return sub string position


INSTR
sub_string ) from the original string.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

LENGTH LENGTH( string ) Function return the length of string.

Function return lowercase character


LOWER LOWER( char/string )
in every word.

Function remove all specified trim


LTRIM LTRIM( string, trim_char )
char from left side of the string.

Function return the ASCII value of the


NCHR NCHR( ascii_number )
given argument value.

Function return the string/char of


REPLACE( string, match_string,
REPLACE every matched string replace with
replace_string )
new string.

REGEXP REGEXP_REPLACE( Function original string represent to a


REPLACE original_string, pattern ) regular expression pattern.

Function return substring from the


REGEXP_SUBSTR(
REGEXP_SUBSTR original string using regular
original_string, pattern )
expression pattern.

Function same as like condition but


REGEXP_LIKE( original_string,
REGEXP_LIKE matching regular expression pattern
pattern )
to perform like condition.

Function remove all specified trim


RTRIM RTRIM( string, trim_char )
char from right side of the string.

SUBSTR( string, start_position, Function return a selected string


SUBSTR
substr_length ) character from a full string.

Function return the string/char of


TRANSLATE( string,
TRANSLATE every matched character replace with
match_char, replace_char )
new character.

Function remove all specified trim


TRIM TRIM( string ) char from beginning and ending of
the string.

Function return uppercase character


UPPER UPPER( char/string )
in every word.

DUAL TABLE:

• It is a dummy table present in all the partitions of the databases.


• It is used for the purpose of calculation without using user table.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

NESTED FUNCTION:

• Function inside a function is known as nested function


• In nested function, the inner most function will be executed first. The result of the
innermost function will ques as an i/p arg. for the outer function.
• F2((F1(arg1,arg2),arg3))

SQL INITCAP, LOWER, UPPER Function

SQL INITCAP Function


SQL INITCAP function return capitalize string/char (capitalize first letter of each
word).

Syntax :
INITCAP(string)

Example :

Consider following example return the capitalize string of given string argument.
SQL> SELECT INITCAP('hanumanth') "INITCAP" FROM DUAL;

INITCAP
---------
Hanumanth

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

SQL LOWER Function


SQL LOWER function return lowercase character in every word.

Syntax :
LOWER(char/string)

Example :

Consider following example return the lowercase string of given string argument.
SQL> SELECT LOWER('HDB') "LOWER" FROM DUAL;

LOWER
---------
hdb

SQL UPPER Function


SQL UPPER function return uppercase character in every word.

Syntax :
UPPER(char/string)

Example :

Consider following example return the uppercase string of given string argument.
SQL> SELECT UPPER('hdb') "UPPER" FROM DUAL;

UPPER
---------
HDB

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

53. Display all the employees names in upper case , job in lower case and display the first
character of each in upper case and rest of the character in lower case.

54. Display all the employees whose names having 5 characters.

55. Display all the employees whose job having more than 6 characters.

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

SQL CONCAT Function


• SQL CONCAT function concatenated string1 with string2 and return to a
concatenated string.
• CONCAT function support any of the character data types CHAR, NCHAR,
VARCHAR2, NVARCHAR2, CLOB, NCLOB.
• You can concat two different data types. if any one of the argument data type is
national type (NCHAR, NVARCHAR2). then returning value is a national data type.

Syntax :
CONCAT(string1, string2)

CONCAT function you can use nested by following way,


CONCAT(CONCAT(CONCAT(string1, string2),string3), string4)

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

SQL REPLACE, TRANSLATE Function

SQL REPLACE Function


SQL REPLACE function return the string/char of every matched string replace with
new string.

Syntax :
REPLACE(string, match_string, replace_string)

Parameters :

• string is original string.


• match_string is find string from original string.
• replace_string is if match_string found replace to replace_string string.

Example :

Consider following example return the every matched string replace with new string.
SQL> SELECT REPLACE('hanumanth d b','h','happa') "REPLACE" FROM DUAL;

REPLACE
-----------
happaanumanthappa d b

SQL TRANSLATE Function


SQL TRANSLATE function return the string/char of every matched character replace
with new character. TRANSLATE function replace individual character at a time.

Syntax :
TRANSLATE(string, match_char, replace_char)

Parameters :

HANUMANTAPPA D B 9590410403
COMPLETE SQL NOTES

• string is original string.


• match_char is find string from original string.
• replace_char is if match_char character found, replace to replace_char character.

Example :

Consider following example return the every matched character replace with new
character.
SQL> SELECT REPLACE('hanumanth d b ','b','v') "TRANSLATE" FROM DUAL;

TRANSLATE
---------
hanumanth d v

56. Display the count of no of L’s present in each employee name.

HANUMANTAPPA D B 9590410403

Вам также может понравиться