SQL - Sas Notes PDF
SQL - Sas Notes PDF
www.irctc.co
m
(or)
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
What is a table?
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Column
Column
Column
First_Name
Last_Name
DOB
John
Smith
2/4/1968
Steven
Goldfish
4/4/1974
Paula
Brown
5/24/1978
James
Smith
20/10/1980
What is SQL?
SQL (pronounced "ess-que-el") stands for Structured Query Language.
The standard SQL commands such as "Select", "Insert", "Update", "Delete",
"Create", "Alter" and "Drop" can be used to accomplish almost everything that one
needs to do with a database.
DDL Data Definition Language
Used to CREATE or ALTER Tables, Views, Indexes etc.
DML Data Manipulation Language
Used to SELECT, INSERT, UPDATE, DELETE data from tables
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
ORDER BY CLAUSE:
Order by clause can be used to sort the rows.
Syntax: Select column1, column2. From table name
[Where conditions]
Order by columns ASC/DESC;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
ASC:
DESC: Descending order, this command will display the output in descending oder.
Example: Select EMP _NAME, EMP _ID from EMP _SAMPLE
ORDER BY EMP _ID;
Example: Select FIRST_NAME, EMPLOYEE_ID, PHONE from EMPLOYEE
ORDER BY EMPLOYEE_ID DESC;
Example: Select emp _id, emp _name from emp _sample
Order by 2;
*It will sort based on emp _name because emp _name position is 2.
Rules:
The ORDER BY clause must be the last clause of the sql statement.
An expression, an alias, column position can be used as the sort
Condition, but the position value must be existing in the select list.
The default order is ascending order.
HAVING CLAUSE:
The having clause is used to filter data is associated with group function.
Syntax: Select [column], group _function (column)
From table name
[Where condition]
[Group by group _by _expression]
[Having having _expression]
[Order by column/alias];
Example: Select EMP _NAME, EMP _ID, count (EMP_ID) from EMP_SAMPLE
Group by EMP_ID having count (EMP_ID)>3;
NOTE: We can use count/group function in having clause, but group function
Cannot be used in where clause.
Example: select EMP _NAME, EMP _ID, count (EMP_ID) from EMP_SAMPLE
Group by EMP_ID where count (EMP_ID)>3;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
*It gives Error, we need to use having clause in place of where clause to avoid
errors.
Rules:
The column which is used in having clause must be used in group by clause.
when having clause condition false it returns no rows selected, when where
Condition returns zero.
DISTINCT keyword:
The DISTINCT keyword is used to eliminate the duplicate rows in the result.
We can specify multiple columns after the distinct keyword , it effects all the selected
columns.
Syntax : Select DISTINCT column1,column2. From table name.
Eg : select FIRST_NAME from EMPLOYEES;
CONSTRAINTS:
At table level:
Syntax: CREATE table table name (column1 Data _type (),
Column2 Data _type (), Column3 Data _type (),
Constraint Constraint _name UNIQUE (column1, column2);
Example:
CREATE table customer (c_id number number (4) NOT NULL, c_name
varchar2 (30) ,email varchar2(20),
Constraint name_email_un UNIQUE ( c_name, email));
PRIMARY KEY Constraint:
Rules:
Only one primary key or composite primary key is allowed per table.
A composite PRIMARY KEY cannot have more than 32 columns.
PRIMARY KEY cannot support in Nested objects.
Composite PRIMARY KEY cannot be defined at column level.
You cannot designate the same column or combination of columns
as both a primary key and a unique key.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Step 2:
CREATE TABLE EMP(empno number(4) constraint empno_pk PRIMARY KEY,
ename varchar2(20) constraint ename_nn NOT NULL
CHECK(substr(ename,1,1)
between A AND Z) AND
ename=upper(ename)),
job varchar2(15) constraint job_chk CHECK(job IN(ANALYST, CLERK,
MANAGER, PRESIDENT, SALESMAN)),
Mgr number(4) constraint mgr_fk_self REFERENCES emp(empno) ON DELETE
SET NULL,
Hiredate date DEFAULT SYSDATE,
sal number(8,2) constraint sal_nn NOT NULL
constraint CHK(sal between 1000 and 10000),
comm Number(8,2),
deptno number(2) constraint deptno_fk
REFERENCES dept(deptno), ON DELETE CASCADE);
CHECK:
Rules:
This cannot be include are
If values are not provided for the table column default value will be considered.
The default value can be a literal, an expression, or a SQL function.
The default expression must match the data type of column.
Syntax:
Create table table name(column1 data_type(), column2 data_type() DEFAULT
expression/value,column3 data_type());
Example:
CREATE table school(sid number PIMARY KEY, name varchar2(20) NOT NULL,
Fee number(6,2) default 5000, fee_due number(6,2));
Adding Constraints to a Existing Table:
Syntax : Alter table table name ADD constraint constraint_name
Constraint type (column names);
Example: ALTER table emp add constraint emp_pk primary key(empno);
* NOT NULL and DEFAULT added to existing column by using the MODIFY clause
Of the ALTER TABLE statement.
Example: ALTER table emp modify hiredate date DEFAULT sysdate;
DROPPING CONSTRAINTS:
Syntax:
VIEWING Constraints:
All constraints can be stored in USER_CONSTRAINTS table
The code that they contained is
P-primary
U-unique
R-references
C-check& not null
Syntax: SELECT owner, constraint _name, constraint _type from user _constraints
WHERE table _name= <table name>;
Example: SELECT owner, constraint _name, constraint _type from user _constraints
WHERE table _name= EMP;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Note: When we drop the table all corresponding integrity constraints will dropped
Automatically.
INDEXES:
Index is a schema object, which a pointer locates the physical address of Data
Index is used by Oracle server ti speed up the retrieval,manipulate the rows.
Specification of INDEXES:
Users can create non unique indexes on columns to speed up access to the rows
Any number of Indexes can be created on one table.
USER_INDEXES holds the details of Indexes.
*When index is created it forms two dimensional matrix which is independent of the
table, it will hold the sorted data, extracted from table columns and address field
identifies the location of the record in Oracle Database(ROWID).
Note: The records in the index are stored in the ascending order of the INDEX column.
COMPOSITE INDEX:
Example:
UNIQUE INDEX:
Unique indexes guarantee that no two rows of a table have duplicate values in
the columns that define the index.
Unique index is automatically created when primary key or unique constraint is
created.
Non-Unique indexes do not impose the above restriction on the column values.
The default type of index used in an oracle database is the btree index.
A btree index is designed to provide both rapid access to individual rows and
quick access to groups of rows within a range.
The btree index does this by performing a succession of value comparisons.
Each comparison eliminates many of the rows.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
DESCENDING INDEX:
The order used by B-tree indexes has been ascending order. You can categorize
data in B-tree index in descending order as well.
This feature can be useful in applications where sorting operations are required.
Two data base objects are created at the time of UNIQUE (they are UNIQUE and
DEFAULT INDEX)
At the time of UNIQUE INDEX Only one database will be created.
UNIQUE will give the REFERENCE to the other table, where as UNIQUE INDEX
cannot give any reference.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
2. Numeric functions
3. Date functions
4. Miscellaneous functions
5. Conversion functions
String/Character functions:
Accept character input and can return both character and number values.
UPPER:
This will convert the string into uppercase.
Syntax: upper (string)
Example: Select upper('computer') from dual;
UPPER
----------COMPUTER
LOWER:
This will convert the string into lowercase.
Syntax: lower (string)
Ex: Select lower(GOLDENGATE);
Output: goldengate.
CONCAT:
Syntax : CONCAT(COLUMN1/EXPRESSION1,COLUMN2/EXPRESSION2);
Example: Select CONCAT(golden, gate) from Dual;
OUTPUT: goldengate
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
We can find the LENGTH of the String or expression, we may use column names
also in this function.
RPAD:
This will allows you to pad/add the right side of a column/expression with any set of
characters.
Syntax: rpad (string, length [padding _char])
Example: Select rpad('goldengate',15,'*'), rpad('golden',15,'*#') from dual;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
OUTPUT: goldengate*****
golden#########
When adding the character to given string it includes the no. of characters
present in the string
Default padding character was blank space.
LPAD:
This will allows you to pad/add the left side of a column with any set of characters.
Syntax : lpad(string,length,[adding character]);
Example: select lpad(goldengate,20, %) from dual;
OUTPUT: %%%%%%%%%%goldengate
Example: Select Lpad(ename,10, $) from EMP;
OUTPUT: $$$$$smith
$$$$$$john
$$$$$$king
All 14 rows will be displayed by adding $ on left side of each employee.
Example: select lpad(sal,12,@) from emp;
OUTPUT: @@@@@@@@@sal, here sal is taken as string.
LTRIM:
This will remove/cut off unwanted characters from the left end of string.
Syntax: ltrim (string [,unwanted _chars]);
Example: Select ltrim('goldengate, golden') from dual;
OUTPUT: gate
If you havent specified any unwanted characters it will display entire string.
RTRIM:
It will remove all the right most characters appear in the set.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
SOUNDEX:
This will be used to find words that sound like other words, exclusively used in
where clause.
It searches for a character in a string/column from its Mth character and Nth
number of occurrence it displays the position of character.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
It returns a string with the first letter of each word in upper case, keeping all other
in lower case.
Example:
select initcap('golden gate') from dual;
INITCAP('GOLDEN GATE)
----------Golden Gate
SELECT upper('goldengate'), lower('GOLDENGATE'), initcap('golden gate') from dual;
UPPER ('GOL LOWER('GOL INITCAP('GO
---------- ---------- ----------GOLDENGATE goldengate Golden Gate
DECODE:
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Decode will act as value by value substitution. For every value of field, it checks
for a match in a series of if/then tests.
If the number of parameters are odd and different then decode will display
nothing.
If the number of parameters are even and different then decode will display last
value.
If all the parameters are null then decode will display nothing.
If all the parameters are zeros then decode will display zero
Examples:
SQL> select decode(1,1,3,2,2,5) from dual;
DECODE (1,1,3,2,2,5)
------------------3
SQL> select decode(2,2,5,1,1,3) from dual;
DECODE(2,2,5,1,1,3)
------------------5
SQL> select decode(2,3,5,5) from dual;
DECODE(2,3,5,5)
--------------5
SQL> select decode(2,3,5) from dual;
DECODE(2,3,5)
------------SQL> select decode(3,4,5,6,7,4) from dual;
DECODE(3,4,5,6,7,4)
------------------______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
4
SQL> select decode(3,4,5,6,7) from dual;
DECODE(3,4,5,6,7)
----------------SQL> select decode(1,1,2,2,3,3,3,3,5) from dual;
DECODE(1,1,2,2,3,3,3,3,5)
------------------------GREATEST:
This will give the greatest string, number from the given strings, numbers.
Syntax: greatest (strng1number1, string2/number2, string3/number3 stringn)
Example:
Select greatest (10, 20, 12, 30) from dual;
GREATEST (10, 20, 12, 30)
--------------------30
SQL> select greatest (12, 35, 23, 32) from dual;
GREATEST (12, 35, 23, 32)
--------------------35
SQL> select greatest ('golden','hyderabad','india') from dual;
GREAT
----india
SQL> select greatest ('golden, gate') from dual;
GREATE
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
-----golden
SQL> select greatest ('gate, golden') from dual;
GREATE
-----Golden
If any of the parameters is null it will display nothing.
LEAST:
This will give the least string/number
.
Syntax: LEAST (strng1/number1, string2/number2, string3/number3 stringn)
Example:
SQL> select least('smith','john','scott') from dual;
LEAST
---John
SQL> select least (121,111,123,321,234,431,102) from dual;
LEAST (121,111,123,321,234,431,102)
---------------------------------102
COALESCE:
This will give the first non-null string/expression.
Syntax: coalesce (strng1, string2, string3 stringn);
Example:
SQL> select coalesce('ab','xy','rt'),coalesce('','as','xy') from dual;
COALESCE COALESCE
-- -------ab
as
SQL> select coalesce(100,null,120),coalesce(null,100,120),coalesce(null,'aw','fh') from
dual;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Example:
select ROUND (123.34,1) from dual;
ROUND (123.34,1)
--------------123.3
select round (-122.236,2) from dual;
ROUND (-122.236,2)
-----------------122.24
Select round(345.37,1) from dual;
ROUND (345.37,1)
--------------345.4
select round (237.385,-2) from dual;
ROUND(237.385,-2)
----------------200
TRUNC:
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
ABS (5)
---------5
SIGN:
SIGN (NULL)
----------
SQRT:
This will give the square root of the given value.
Syntax: sqrt (value)
Here value must be positive.
Example:
Select sqrt(4),sqrt(12),sqrt(16),sqrt(28) from dual;
SQRT(4) SQRT(12) SQRT(16) SQRT(28)
---------- ---------------------------2
3.46410162
4
5.29150262
Select sqrt(1),sqrt(null),sqrt(0) from dual;
SQRT(1) SQRT(NULL) SQRT(0)
---------- ---------- ---------1
0
MOD
This will give the remainder.
Syntax: mod (value, divisor)
Ex: select mod(7,4), mod(1,5), mod(null,null), mod(0,0), mod(-7,4) from dual;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
MOD(7,4) MOD(1,5)
------------ ---------3
1
MOD(NULL,NULL)
---------------------
MOD(0,0)
----------0
MOD(-7,4)
-------------3
NVL
This will substitutes the specified value in the place of null values.
This is used to convert a NULL value to an actual value.
Syntax: nvl (null _col/exp1, replacement _value/exp2)
Exp1: Is the source value or expression that may contain NULL.
Exp2: is the target value for converting NULL.
Select nvl(100,200) from dual;
NVL (100,200)
-----------100
Select nvl(null,100) from dual;
NVL (NULL, 100)
------------100
Select 1000+null from dual;
1000+NULL
---------Select 1000+nvl (null, 0) from dual;
1000+NVL (NULL, 0)
---------------1000
POWER
Power is the ability to raise a value to a given exponent.
Syntax: power (value, exponent)
select power(2,5),power(-2,3),power(0,0),power(1,1) from dual;
POWER (2,5)
POWER(-2,3)
POWER(0,0)
POWER(1,1)
-------------------------------------32
-8
1
1
EXP
This will raise e value to the give power.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
EXP (1)
---------2.71828183
EXP (-1)
---------367879441
EXP (5)
---------148.413159
LN
This is based on natural or base e logarithm.
Syntax: ln (value)
Here value must be greater than zero which is positive only.
Select ln(2),ln(5) from dual;
LN(2)
---------.693147181
LN(5)
---------1.60943791
CEIL(-5.1)
CEIL(0)
CEIL(NULL)
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
--------5
----------6
----------5
------------5
-------0
--------------
FLOOR
This will produce a whole number that is less than or equal to the specified value.
Syntax: floor (value)
Select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0), floor(null) from dual;
FLOOR(5)
----------5
FLOOR(5.1) FLOOR(-5)
-----------------------5
-5
BITAND
This will perform bitwise and operation.
Syntax: bitand (value1, value2)
select bitand(2,3), bitand(0,0), bitand(1,1), bitand(null,null), bitand(-2,-3) from dual;
BITAND(2,3) BITAND(0,0) BITAND(1,1)
BITAND(NULL,NULL)
----------------------------------------------2
0
1
-4
GREATEST
This will give the greatest number.
BITAND(-2,-3)
-------------
LEAST
This will give the least number.
Syntax: least (value1, value2, value3 valuen)
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Select least (1, 2, 3), least (-1, -2, -3) from dual;
LEAST (1, 2, 3)
-------------------1
LEAST (-1,-2,-3)
-----------------------3
COALESCE
This will return the first not null value.
Syntax: coalesce (value1, value2, value3 valuen)
Select coalesce(1,2,3), coalesce(null,2,null,5) from dual;
COALESCE(1,2,3)
--------------1
COALESCE(NULL,2,NULL,5)
----------------------2
DATE FUNCTIONS:
Example:
Select sysdate from dual;
Select Sysdate, Sysdate+48/24 from dual;
CURRENT_DATE
This will returns the current date in the sessions timezone.
select current_date from dual;
CURRENT_DATE
-----------------25-NOV-11
CURRENT_TIMESTAMP
This will returns the current timestamp with the active time zone information.
Select current_timestamp from dual;
CURRENT_TIMESTAMP
-----------------------------------------------------25-NOV-11 03.42.41.383369 AM +05:30
SYSTIMESTAMP
This will returns the system date, including fractional seconds and time zone of the
database.
Select systimestamp from dual;
SYSTIMESTAMP
-----------------------------------------------------______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
MONTHS_BETWEEN(SYSDATE,'25-DEC-04')
----------------------------------83
Select months_between('22-DEC-2010',sysdate) from dual;
MONTHS_BETWEEN('22-DEC-2010',SYSDATE)
-------------------------------------11.128056
NEXT DAY FUNTION:
Syntax: Next_day(D,Char)
It returns the date of the first week day named by char, that is later than the data D.
DAYSLEFT
--5
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
ROUNDING OF DATES:
Syntax: Round (date, format)
Returns date rounded to the unit specified by the format.
If format is omitted, date is rounded to the nearest day.
select round(sysdate,'month') from dual;
ROUND (SYSDATE.
--------01-DEC-11
TRUNCATING DATES:
Syntax: Trunc(Date, format)
Returns date with the time portion of the day truncated to the specified unit.
Select round (sysdate,'DAY'),Trunc(sysdate,'DAY') from dual;
ROUND (SYS TRUNC (SYS
--------- --------27-NOV-11 20-NOV-11
Select round (sysdate,'MONTH'),trunc(sysdate,'MONTH') from dual;
ROUND (SYS TRUNC(SYS
--------- --------01-DEC-11 01-NOV-11
CONVERSION FUNCTION:
The conversion functions convert a value from one data type to another.
Conversion in Oracle is two types.
Implicit conversion.
It works according to the convention specified by the Oracle.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
CHAR to NUMBER conversion succeed only if the character string represents a valid
NUMBER.
CHAR to DATES conversion succeed only if the character string represents the default
format of DD-MON-YY.
Explicit conversion.
SQL provided three conversion functions to convert one data type to another.
The explicit conversion functions are
TO_ CHAR To Character function.
TO_DATE To Date conversion
TO_NUMBER To Number conversion.
TO_CHAR Conversion:
This function is used in two ways.
1. TO_CHAR (Number Conversion)
2. TO_CHAR (Date Conversion)
TO_CHAR(Number Conversion):
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
$1234
SQL> select to_char(23765,'L99G999D99', 'NLS_CURRENCY=IndRupees') from dual;
TO_CHAR (23765,'L99G9
-------------------IndRupees 23, 765.00
TRAILING MINUS INDICATOR: MI9999MI
$12,000.00
ROMAN NEGATIVE INDICATOR:
RNreturns upper roman number
rn returns lower roman number.
The value can be an integer between 1 and 3999.
SQL> select 12,to_char(12,'RN'),to_char(12,'rn') from dual;
12 TO_CHAR (12,'RN' TO_CHAR(12,'RN'
---------- --------------- --------------12
XII
xii
HEXADECIMAL INDICATOR: XXXXX
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
TO
-48
AGGREGATE/GROUP FUNCTIONS:
Group functions operate on set of rows to give one result per each group.
Group functions can appear in select lists and in ORDER BY and HAVING clauses.
Syntax: group_function(distinct/all column);
Rules:
The data types for the arguments can be CHAR, VARCHAR2, NUMBER, or DATE.
All group functions ignore null values except COUNT (*).
Average function:
It returns the average value of column.
It ignores NULL values.
Syntax: avg(distinct/all column)
select avg(sal), avg(DISTICT sal) from employees;
Sum Function:
It returns the SUM value of column.
Syntax: sum(distinct/all Column)
Select SUM(comm.), SUM(distinct comm) from employees;
Maximum Function:
It returns the maximum value of column
Syntax: max(distinct/all column)
Select max(sal) from employees;
Minimum Function:
It returns the minimum value of column.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Count Function:
It gives the no of rows in the Query.
If * used to returns all rows, it includes duplicated and NULLs.
Syntax: Count (distinct/all column)
Select count (employee _name) from employees;
Select count (*) from employees;
MISCELLANEOUS FUNCTIONS:
UID:
This will returns the integer value corresponding to the user currently logged in.
select uid from dual;
UID
---------319
USER:
This will returns the logins user name.
select user from dual;
USER
---------------scott
VSIZE:
This will returns the number of bytes in the expression.
Select vsize(123), vsize('computer'), vsize('12-jan-90') from dual;
VSIZE(123) VSIZE('COMPUTER')
----------------------------------3
8
VSIZE('12-JAN-90')
---------------------9
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
RANK:
This will give the non-sequential ranking.
Select rownum,sal from (select sal from emp order by sal desc);
ROWNUM SAL
---------- ---------1
5000
2
3000
3
3000
4
2975
5
2850
6
2450
select rank(2975) within group(order by sal desc) from emp;
RANK(2975)WITHINGROUP(ORDERBYSALDESC)
--------------------------------------------------------4
DENSE_RANK:
This will give the sequential ranking.
select dense_rank(2975) within group(order by sal desc) from emp;
DENSE_RANK(2975)WITHINGROUP(ORDERBYSALDESC)
----------------------------------------------------------------3
OPERATORS:
Arithmetic Operators:
Arithmetic operators can be used to create expressions on NUMBER and DATE data.
Arithmetic operators are +, - , *, /.
Operator precedence *, /, +, Arithmetic operators can be used in any clause of SQL statements, except the FROM
clause.
Select empno, ename, sal,sal+500 from employees;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
NVL(NULL,100)
------------100
NVL2 FUNCTION:
Syntax : NVL2(exp1,exp2,exp3)
NULLIF FUNCTION:
Syntax: NULLIF (exp1, exp2)
Compares two expressions and returns null if they are equal.
Returns first if they are not equal.
select nullif(100,200) from dual;
NULLIF(100,200)
--------------______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
100
SQL> select nullif(300,300) from dual;
NULLIF(300,300)
--------------SQL> select nullif('smith','smith') from dual;
NULLI
----SQL> select nullif('smith','john') from dual;
NULLI
----Smith
Relational or Comparison operators:
<>, ^=,! = these three are not equal operators.
>, >=
<, <=
=
Select ename,sal from employees where sal>2000;
Select ename,sal from employee where sal<=1500;
Logical operators:
A logical condition combines the result of two component conditions to produce a single
result.
Three logical operators available in Oracle
AND Operator:
LIKE Operator:
The set operators allow you to combine rows returned by two or more queries
The number of columns and the column types returned by the queries must
match, although the column names may be different.
All set operators have equal precedence, if a SQL statements contains multiple
SET operators, the Oracle server evaluates them from left(top) to right(bottom) if
no parentheses explicitly another order.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Returns all the rows retrieved by the queries, including duplicate rows.
UNION
INTERSECT
MINUS
Returns the remaining rows when the rows retrieved by the second
query are subtracted from the rows retrieved by the first query.
Examples:
1) Select job from EMP where deptno=10;
UNION
Select job from EMP where deptno=20;
2)
When data from more than one table in the database is required, a join condition
is used.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
A join is a query that combines rows from two or more tables, views, or
materialized views. a join is performed whenever multiple table appear in the
quires FROM clause.
Join Conditions:
A column in the join condition need not be part of the SELECT list.
When writing a SELECT statement that joins tables, precede the column name
with the table name for clarity and to enhance database access.
Syntax:
Select col1,col2,col3. From <table1>,<table2>
Where <table>.<common col name>=<table2>.<column col name>
And..
Example:
Syntax:
Select col1,col2. From <table A>,<table B>
Where <table A>.<col1> between <table B>.<col1> and <table B>.<col2>;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Example:
Select e.ename,e.sal,s.grade from emp e.salgrade s
Where e.sal between 1000 and 3000;
SELF JOIN:
Syntax:
Select columns from table1 t1,table1 t2
Where t1.column1=t2.column2;
Example:
Select e.ename employee name,m.ename manager name from emp e,emp m
Where e.mgr=m.empno;
OUTER JOIN:
Is used to retrieve all the rows from one table but matching rows from other table.
An outer join extends the result of a simple or inner join.
It is use an operator (+), it called join operator.
(+) used with table which missing the data.
Syntax:
Select table1.column, table2.column from table1, table2
Where table1.column (+) =table2.column;
Rules:
(+) operator can appear only in the where clause.
(+) used only with one table.
Example:
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
This will display the all the records from the left side table and only matching
records from the right side table
Example:
Select empno, ename, job, dname, loc from emp e left outer join dept d
On (e.deptno=d.deptno);
Or
Select empno, ename, job, dname, loc from emp e,dept d where
e.deptno=d.deptno (+);
RIGHT OUTER JOIN:
This will display all the records from right side of the table and only matching
records from left side of the table.
To perform a right outer join, the WHERE clause is,
WHERE table1.column1(+)= table2.column2;
Example:
Select empno, ename, job, dname, loc from emp e right outer join dept d
On (e.deptno=d.deptno);
Or
Select empno, ename, job, dname, loc from emp e,dept d where
e.deptno(+)=d.deptno;
FULL OUTER JOIN:
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
This will display the all matching records and the non-matching records from both
tables.
CROSS JOIN:
ON CLAUSE
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Example:
select empno,ename,job,dname,loc from emp e join dept d
on(e.deptno=d.deptno);
SUBQUERIES:
Sub queries are used to retrieve data from tables that depend on the values in
the table itself.
Root query: the query which is not depend on any other query for its
Conditions value.
Or
Independent query .
Example:
Parent query: the query which depend on any other query for its condition value.
Sub query:
1. Single-row operator
2. Multiple-row operators
1. Single-row operator:
A single-row subquery is one that returns either zero rows or one row to the outer
SQL statement.
A subquery can be placed in the WHERE clause of another query.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Example: select * from emp where sal > (select sal from emp where empno = 7566);
we can use other comparison operators, such as <>, <, >, <=, and >=,
with a single-row subquery.
Example:
SELECT product_id, name, price FROM products
WHERE price >(SELECT AVG(price)FROM products);
If a sub query is placed in FROM clause these types of sub queries are called as
INLI NE views, because the sub query provides data in line with the FROM
clause.
Example:
A sub query may not contain an ORDER BY clause. Instead, any ordering must
be done in the Outer query.
Example:
SELECT product _id, name, price FROM products WHERE price > (SELECT
AVG (price)FROM products) ORDER BY product_id DESC;
2 . Multiple-row operators:
A multiple-row sub query can return one or more rows to an outer SQL
statement.
To handle a sub query that returns multiple rows, outer query may use the IN,
ANY, or ALL operator.
1. Select ename,deptno from emp where sal IN(select max(sal) from emp group
by deptno);
2. Select ename,ename,sal,deptno from emp where
1sal <SOME(1250,3000,2500);
3. Select ename,job,sal from emp where sal<ANY(select sal from emp where
job=CLERK);
4. Select ename,job,sal from emp where sal>ANY(select sal from emp where
deptno=10);
Note: < ANY/SOME Means less than the maximum value in the list.
>ANY/SOME Means more than the minimum value in the list.
Example:
1. Select ename,job from emp where sal>ALL(select sal from emp where
deptno=30);
2. Select ename,job,sal from emp where sal<ALL(select avg(sal) from emp group
by deptno);
Note: > ALL means more than the maximum in the list.
< ALL means less than the minimum value in the list.
Sub SELECT statements:
Example:
Select ename,sal,(select sum(sal) from emp total salary,(select MIN(sal)
from emp) lowest salary from emp;
Co-related Sub query:
It is another way of performing queries upon the data with a simulation of joins.
Syntax:
select column1,column2 from table1 alias1 where column1 operator(select
column1,column2 from table2 alias2 where table1.column operator
table2.column);
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Example:
Select deptno,ename,sal from emp e where deptno=(select deptno from dept d
where e.deptno=d.deptno);
VIEWS:
ADVANTAGES:
Syntax:
CREATE [OR REPLACE] [FORCE| NOFORCE] VIEW view _name[(alias name)] as
Sub query/select statement [with (check option/read only) CONSTRAINT <constraint
name>;
OR REPLACE: Re creates the view if it is already exists.
FORCE: creates a view even the base table does not exists.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
WITH CHECK OPTION: specifies that only rows accessible to the view can be
INSERTED or UPDATED or DELETED.
WITH READ ONLY: Ensures that no DML operations can be performed on this view.
TYPES OF VIEWS:
1. Simple view
2. Complex view
1 . Simple view: A simple view can be created on single table.
Example:
1. Create view emp_view as select *from employees;
2. Create view student_view as select name student name,sid studentid, marks
from student;
2 . Complex view: The view which is created with following clauses
Join condition
Group by
Having clause
Set operators
Distinct
Group function
Example:
1. Create view emp_info as select e.empno employeeno,e,ename name,d.deptno
departmentid,d.dname from emp e,dept d Where d.deptno=e.deptno order by
d.deptno;
2. Create or replace view select e.ename,e.job,d.deptno from emp e,dept d where
e.deptno=d.deptno
UNION
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Dropping a view has no affect on the tables upon which the view is created.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
HIERARCHICAL Queries:
Example:
1. Select ename,empno,mgr,job from emp CONNECT BY PRIOR empno=mgr;
2. Select ename,empno,mgr,job from emp START WITH JOB= PRESIDENT
CONNECT BY PRIOR empno=mgr;
PSEUDO COLUMNS:
The available pseudo columns are
CURRVAL
NEXTVAL
LEVEL
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
ROWID
ROWNUM
Currval and Nextval:
SEQUENCE:
A sequence is a schema object that can generate sequential values.
For sequence in other schema the qualifying syntax is
SCHEMANAME.SEQUENCENAME.CURRVAL
SCHEMANAME.SEQUENCENAME.NEXTVAL.
Creating sequence:
CREATE SEQUENCE <SEQUENCENAME>
[INCREMENT BY n]
[START WITH n]
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
[MAXVALUE n|NOMAXVALUE]
[MINVALUE n|NOMINVALUE]
[CYCLE |NOCYCLE]
[CACHE n|NOCACHE]
ORDER/NOORDER;
If the above parameters are not specified by default
START WITH will be 1
INCREMENT BY will be 1
SEQUENCE is NOCYCLE
The CACHE value will be 20
SEQUENCE is ORDER
Example: Create sequence deptno
INCREMENT BY 10
START WITH 10
MINVALUE 0
MAXVALUE 9999
NOCACHE
NOCYCLE;
Modifying a sequence:
Alter sequence <sequence name>
[INCREMENT BY n]
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
[MAXVALUE n|NOMAXVALUE]
[MINVALUE n|NOMINVALUE]
[CYCLE |NOCYCLE]
[CACHE n|NOCACHE];
Example:
Alter sequence deptno
INCREMENT BY 10
MAXVALUE 500
NOCACHE
NOCYCLE;
*You must be the owner or alter privilege for the sequence to modify it.
START WITH option cannot be changed using alter sequence statement.
To see the present value of sequence after creating currval execution not possible,
atleast one time nextval statement must be execute on the sequence.
Select dept.currval from dual;
It will give error;
Select dept.nextval from dual;
Now we can see the current value.
DROPPING sequence:
Syntax: drop sequence <sequence name>;
DROP sequence dept;
LEVEL:
This LEVEL pseudo column returns 1 for root row,2 for a child of a root,and so on.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Example:
1. select rownum,empno,ename,deptno from emp;
2. Select rownum,empno,ename,sal from emp where rownum<=5;
3. Select rownum,ename from emp group by ronum,ename having
mod(ronum,2)=0;
ROWID:
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
CUBE grouping produces a result set containing the rows from ROLLUP and
cross tabulation rows.
It is extension similar to ROLLUP.
Locks are the mechanisms cued to prevent destructive interaction between users
accessing the same resources simultaneously.
A resource can either table or a specific row in a table.
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
In row level lock ,a row is locked exclusively so that other users cannot modify
the row until the transaction holding the lock is committed or rollback.
a. Share lock:
A share lock locks the table allowing other users to only query but not
INSERT, UPDATE or DELETE rows in a table.
Example: lock table emp in share mode;
b. Share update lock:
It locks rows that are to be updated in a table.
It permits other users to concurrently query,insert,update or delete even
lock other rows in the same table.
It prevents the other users from updating the row that has been locked.
Example:
c. Exclusive lock:
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
when it is issued by the user ,it allows the other user to only query but not
insert,delete or update rows in a table.
It is almost similar to share lock but only one user can place an exclusive
lock on a table at a time, where as many users can place a share lock on
the same table at the same time.
Example: lock table emp in exclusive mode;
ROLES IN ORACLE:
It is a named group of related privileges that can be granted to the user.
Rather than assigning privileges one at a time directly to USER, we can CREATE a
ROLE, assign PRIVILEGES to that ROLE, and then GRANT that ROLE to multiple
USERS and ROLES.
Syntax : CREATE ROLE <rolename> IDENTIFIED BY <password>;
Example: create role sales_manager identified by manager;
Note: we can alter the ROLE for password and new password;
Granting Role to user:
Example:
Grant sales_manager to Scott;
Granting multiple roles to another ROLE:
Grant ROLE1,ROLE2. TO <target rolename>;
Revoking ROLE:
Revoke sales_manager from scott;
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]
Dropping a ROLE:
Syntax : Drop ROLE <rolename>
Example: drop role sales_manager;
SYNONYMS:
______________________________________________________________________
STANSYS SOFTWARE SOLUTIONS
#7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,
S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]