Sunteți pe pagina 1din 40

RDBMS :-

=> Relational Database Management System


=> Introduced by E.F.CODD
=> E.F.CODD introduced 12 rules called codd rules
=> oracle supports all codd rules so oracle is called perfect
rdbms.

Information rule :-

=> according to information rule data must be organized in


tables i.e. rows and columns.

DB = COLLECTION OF TABLES
TABLE = COLLECTION OF ROWS & COLS
ROW = COLLECTION OF FIELD VALUES
COLUMN = COLLECTION OF VALUES ASSIGNED TO ONE FIELD

=> Every table must contain a primary key to uniquely


identify records.

=> one table is related to another table by using foreign key

foreign key
key of foreign
pk of some other table

RDBMS softwares :-

oracle
mysql open source
sql server
db2
teradata
postgresql open source

ORDBMS :-

=> Object Relational DBMS


=> It is combination of RDBMS & OOPS

ORDBMS = RDBMS + OOPS (reusability)

=> RDBMS doesn't support resuability and ORDBMS supports reusability. ORDBMS
supports reusability by using UDT.
(user define type).

RDBMS :-

EMP
EMPID ENAME SAL HNO STREET CITY STATE

CUST
CID NAME HNO STREET CITY STATE

ORDBMS :-

UDT :- ADDR(HNO,STREET,CITY,STATE)
EMP
EMPID ENAME ADDR
HNO STREET CITY STATE

CUST
CID CNAME ADDR
HNO STREET CITY STATE

ORACLE UPTO 7 VER RDBMS


ORACLE FROM 8 VER ORDBMS

what is oracle ?

=> DBMS software


=> RDBMS software
=> ORDBMS software

OODBMS :- object oriented dbms

=> based on oops


=> data stored in objects

DB DEVELOPMENT LIFE CYCLE :-

Analysis
Design
Development
Testing
Implementaion
Maintenance

=> DB is designed by designers or architects by using

1 ER model (Entity Relationship)


2 Normalization

=> DB is developed by developers & DBAs by using any rdbms


tools like ORACLE.

Developers DBA

creating tables installation of oracle


creating views creating database
creating synonyms creating userids
creating sequences db backup & restore
creating materialized views db export & import
creating indexes db upgradation & migration
creating procedures performance tuning
creating functions
creating triggers
writing queries

=> db is tested by QA(quality assurance) team by using some


tools called testing tools.

=> Implementation means moving DB from DEV server to PROD server


ORACLE 12C/18C/19C

What is oracle 12c ?

=> dbms software


=> rdbms software
=> ordbms software

What for oracle 12c ?

=> Organizations uses oracle 12c to maintain database.

What are features of oracle ?

1 easy to access & manipulate data


2 more security
3 supports data integrity i.e. data quality
4 supports data sharing
5 supports transactions (ACID properties)

A atomocity
C consistency
I isolation
D durability

6 supports XML (extensible markup lang)

Versions of Oracle ?

1,2,3,4,5,6,7,8,8i,9i,10g,11g,12c,18c,19c

i => internet
g => grid
c => cloud

=> from 8i onwards oracle supports internet applications

=> from 10g onwards oracle db can be accessed through mutliple


server. Grid improves availability.

=> from 12c onwards oracle db can be delivered in two ways

1 on premises
2 on cloud

=> in on premises db is deployed server managed by client

=> in on cloud db is deployed in server managed by cloud service


provider for ex amazon,oracle corp

=> the following components installed after installing oracle

1 SERVER
2 CLIENT

server :-

=> server is a system where oracle software is installed and


running.

=>server manages two components

1 DB
2 INSTANCE

=> db is created in HD and acts as permanent storage and instance


is created in ram and acts as temporary storage.

CLIENT :-

=> using client system users

1 connects to server
2 submits requests to server
3 recieve response from server

client tools :-

SQLPLUS (CUI)
SQL DEV (GUI)
TOAD (GUI)

SQL

=> structured query language


=> language used to communicate with oracle
=> users communicates with oracle by sending commands called
queries.
=> a query is command/request/question submitted to oracle to
perform some operation over db.
=> SQL is originally introduced by IBM and initial name of this
lang was "SEQUEL" and later it is rename to SQL.
=> based on operations over db SQL is categorized into following
sublanguages.

1 DDL (DATA DEFINITION LANG)


2 DML (DATA MANIPULATION LANG)
3 DQL (DATA QUERY LANG)
4 TCL (TRANSACTION CONTROL LANG)
5 DCL (DATA CONTROL LANG)

EMPID ENAME SAL => DATA DEFINITION / METADATA


1 A 5000 => DATA

SQL

DDL DML DQL TCL DCL

create insert select commit grant


alter update rollback revoke
drop delete savepoint
truncate insert all
rename merge
flashback
purge
schema :-

=> a user in oracle database is called schema

SERVER
DATABASE
USERS
TABLES

SERVER
ORCL
SYSTEM/MANAGER (ADMIN)

How to connect to oracle server :-

=> to connect to oracle server open sqlplus and enter username


& password

USERNAME :- UNAME
PASSWORD :- PWD

OR

USERNAME :- UNAME/PWD

Creating user/schema/account in oracle database :-

=> only admin can create new account

1 conn as SYSTEM/MANAGER

2 create user :-

CREATE USER <NAME> IDENTIFIED BY <PWD>


DEFAULT TABLESPACE USERS
QUOTA UNLIMITED ON USERS;

SQL>CREATE USER BATCH8PM IDENTIFIED BY ORCL


DEFAULT TABLESPACE USERS
QUOTA UNLIMITED ON USERS ;

3 grant permissions to user :-

SQL>GRANT CONNECT,RESOURCE TO BATCH8PM ;

CONNECT => to connect to database


RESOURCE => to create tables
DBA => all permissions

SQL>GRANT DBA TO BATCH8PM;

=> if CONNECT,RESOURCE granted then user is called normal user


=> if DBA granted then user is called ADMIN.

SERVER
ORCL
SYSTEM/MANAGER
BATCH8PM/ORCL
Datatypes in Oracle :-

=> Datatype specifies

1 type of data allowed into a column


2 amount of memory allocated for column

DATATYPES

char Numeric Date BINARY

char Number(p) DATE BFILE


varchar Number(p,s) TIMESTAMP BLOB
nchar
nvarchar
LONG
CLOB

CHAR(size) :-

=> allows character data upto 2000 chars


=> recommended for fixed length char fields

ex :- NAME CHAR(20)

SACHIN-----------------
wasted

RAVI-------------------
wasted

=> in the above example extra bytes are wasted so there is a


memory wastage.so don't use char for variable length fields
use char for fixed length fields.

ex :- state_code CHAR(2)

AP
TS
MH

country_code CHAR(3)

IND
AUS

VARCHAR2(SIZE) :-

=> allows character data upto 4000 chars


=> recommended for variable length fields

ex :- NAME VARCHAR2(20)

SACHIN--------------------
released

=> char/varchar2 allows ASCII characters (a-z,A-Z,0-9,special chars 256)

PANNO CHAR(10)
VEHICLE_NO VARCHAR2(20)

NCHAR / NVARCHAR2 :-

=> N => national

=> allows UNICODE characters(65536 chars). that includes characters of different


languages.

LONG :- allows character data upto 2GB.

CLOB :- allows character data upto 4GB.

(CHARACTER LARGE OBJECT)

Number(p) :-

=> allows numeric data upto 38 digits


=> allows numbers without decimal part

ex :- EMPID NUMBER(4)
10
100
1000
10000 => INVALID

NUMBER(P,S) :-

=> allows numbers with decimal part

P => precision => total no of digits


S => scale => no of digits after decimal

EX :- SALARY NUMBER(7,2)

5000
5000.50
50000.50
500000.50 => INVALID

DATE :-

=> allows DATE & TIME


=> but TIME is optional , if not entered then oracle stores
12:00 AM.
=> default date format is DD-MON-YY / YYYY

EX :- DOB DATE

10-OCT-15 => 10-OCT-2015

05-JAN-95 => 05-JAN-2095

05-JAN-1995 => 05-JAN-1995

TIMESTAMP :-

=> allows date,time and also milliseconds


EX :- T TIMESTAMP

30-AUG-19 21:03:10.123
--------- ------- ---
DATE TIME MS

BFILE,BLOB :-

BFILE => binary file


BLOB => binary large object

=> both allows binary data that includes audio,video,images


upto 4GB.

CREATING TABLES IN ORACLE DB :-

CREATE TABLE <TABNAME>


(
COLNAME DATATYPE(SIZE),
COLNAME DATATYPE(SIZE),
--------) ;

Rules :-

1 tabname should start with alphabet


2 tabname should not contain spaces & special chars
but allows _ , $,#
3 tabname can be upto 128 chars
4 table can have max 1000 cols
5 table can have unlimited rows

EMP123 => valid


123EMP => INVALID
EMP 123 => INVALID
EMP*123 => INVALID
EMP_123 => VALID

"EMP 123" => VALID


123 => INVALID
"123" => VALID

Example : create table with following structure

EMP
EMPID ENAME JOB SAL HIREDATE

CREATE TABLE EMP


(
EMPID NUMBER(4),
ENAME VARCHAR2(10),
JOB VARCHAR2(10),
SAL NUMBER(7,2),
HIREDATE DATE);

DESC :- command to see the structure/definition/metadata of the table

syntax :- DESC <tabname>


example :- SQL>DESC EMP

INSERTING DATA INTO TABLE :-

=> "INSERT" command is used to insert row into the table


=> using INSERT command we can insert

1 single row
2 multiple rows

inserting single row :-

INSERT INTO <TABNAME> VALUES(V1,V2,V3,---);

EX :-

1 INSERT INTO EMP VALUES(1,'sachin','clerk',4000,'03-SEP-19');


2 INSERT INTO EMP VALUES(2,'vijay','manager',8000,sysdate);

inserting multiple rows :-

=> we can execute insert command multiple times with different


values using variables prefixed with "&".

INSERT INTO EMP VALUES(&EMPID,&ENAME,&JOB,&SAL,&HIREDATE);

INSERTING NULLS :-

=> a null means blank / empty


=> it is not equal to 0 or space
=> nulls can be inserted in two ways

1 explicit (by user)


2 implicit (by system)

explicitly :-

=> for numeric column specify NULL


=> for char/date column specify ''

INSERT INTO EMP VALUES(5,'satish','',null,sysdate)

implicitly :-

INSERT INTO EMP(EMPID,ENAME,HIREDATE) VALUES(6,'kumar',sysdate);

Displaying Data :-

=> use "SELECT" command to display data from table


=> we can display all rows & all columns
=> we can display specific rows & specific columns

SELECT COLUMNS/* FROM TABNAME

FROM clause => specify tabname


SELECT clause => specify column name

SQL = ENGLISH
queries = sentences
clauses = words

display all the data from emp table ?

SELECT * FROM EMP

* => all columns

display employee names and salaries ?

SELECT ENAME,JOB,SAL FROM EMP

Operators in Oracle :-

Arithmetic Operators => + - * /


Relational Operators => > >= < <= = <>
Logical Operators => AND OR NOT
Special Operators => BETWEEN
IN
LIKE
IS
ANY
ALL
EXISTS
PIVOT (11g)
set operators => UNION
UNION ALL
INTERSECT
MINUS

WHERE clause :-

=> used to get specific row/rows from table based on a condition

SELECT columns
FROM tabname
WHERE condition

condition :-

COLNAME OP VALUE

=> OP must be any relational operator like = > >= < <= <>

TRUE => record is selected


FALSE => record is not selected

Display employee details whose empid=3 ?

SELECT * FROM EMP WHERE EMPID=3 ;

Display employee details whose name = satish ?

SELECT * FROM EMP WHERE ENAME='satish';

employees working as clerk ?


SELECT * FROM EMP WHERE JOB='CLERK' ;

Employees earning more than 2000 ?

SELECT * FROM EMP WHERE SAL > 2000 ;

Employees joined after 1981 ?

SELECT * FROM EMP WHERE HIREDATE > 1981 ; => ERROR

SELECT * FROM EMP WHERE HIREDATE > '31-DEC-1981'

Joined before 1981 ?

SELECT * FROM EMP WHERE HIREDATE < '01-jan-1981'

compound condition :-

=> multiple conditions combined with AND / OR operators is


called compound condition.

WHERE COND1 AND COND2


T T T
T F F
F T F
F F F

WHERE COND1 OR COND2


T T T
T F T
F T T
F F F

employees working as clerk,manager ?

SELECT * FROM EMP WHERE job='CLERK' OR job='MANAGER'

employees earning more than 2000 and less than 5000 ?

SELECT * FROM EMP WHERE SAL>=2000 AND SAL<=5000

Employees working for dept 10,20 ?

SELECT * FROM EMP WHERE DEPTNO=10 OR DEPTNO=20

IN operator :-

=> use IN operator when comparision based on multiple values

WHERE COL=V1 OR COL=V2 OR COL=V3

WHERE COL IN (V1,V2,V3,--)

Employees working for dept 10,20 ?

SELECT * FROM EMP WHERE DEPTNO IN (10,20)


Employees not working for 10,20 ?

SELECT * FROM EMP WHERE DEPTNO NOT IN (10,20)

Employees whose id = 7499,7844,7566 ?

SELECT * FROM EMP WHERE EMPNO IN (7499,7844,7566)

BETWEEN operator :-

=> use BETWEEN operator when comparision based on range

WHERE COL >= V1 AND COL <= V2

WHERE COLNAME BETWEEN V1 AND V2

=> employees earning between 2000 and 5000 ?

SELECT * FROM EMP WHERE SAL BETWEEN 2000 AND 5000

SELECT * FROM EMP WHERE SAL NOT BETWEEN 2000 AND 5000

=> Employees joined in 1981 YEAR ?

SELECT * FROM EMP


WHERE HIREDATE BETWEEN '01-JAN-1981' AND '31-DEC-1981'

Employees working as clerk,manager and earning between 2000 and


5000 and joined in 1981 year and not working for dept 10,20 ?

SELECT *
FROM EMP
WHERE job IN ('CLERK','MANAGER')
AND
SAL BETWEEN 2000 AND 5000
AND
HIREDATE BETWEEN '01-JAN-1981' AND '31-DEC-1981'
AND
DEPTNO NOT IN (10,20)

OCA Question :-

SELECT * FROM EMP WHERE SAL BETWEEN 5000 AND 2000 ;

A ERROR
B NO ROWS
C RETURNS ROWS
D NONE

LIKE operator :-

=> use LIKE operator when comparision based on patterns.

WHERE COLNAME LIKE 'PATTERN'


WHERE COLNAME NOT LIKE 'PATTERN'

=> PATTERN consists of alphabets,digits,special chars and also


wildcard chars.
wildcard chars :-

% => zero or many chars


_ => exactly 1 char

employees name starts with 'S' ?

SELECT * FROM EMP WHERE ENAME LIKE 'S%'

employees name ends with 'S' ?

SELECT * FROM EMP WHERE ENAME LIKE '%S'

name contains 'S' ?

SELECT * FROM EMP WHERE ENAME LIKE '%S%' ;

3rd char 'A' ?

SELECT * FROM EMP WHERE ENAME LIKE '__A%'

2nd char 'E' from last ?

SELECT * FROM EMP WHERE ENAME LIKE '%E_';

joined in JAN month ?

dd-mon-yy

SELECT * FROM EMP WHERE HIREDATE LIKE '___JAN___' ;

SELECT * FROM EMP WHERE HIREDATE LIKE '%JAN%'

joined in 1981 year ?

SELECT * FROM EMP WHERE HIREDATE LIKE '%81' ;

IS operator :-

=> use IS operator when comparision based on NULL / NOT NULL

WHERE COL IS NULL


WHERE COL IS NOT NULL

Employees not earning commission ?

SELECT * FROM EMP WHERE COMM IS NULL;

Employees earning comm ?

SELECT * FROM EMP WHERE COMM IS NOT NULL;

WHERE COL BETWEEN V1 AND V2


WHERE COL IN (V1,V2,V3--)
WHERE COL LIKE 'PATTERN'
WHERE COS IS NULL / NOT NULL
display ENAME,ANNUAL SAL ?

SELECT ENAME,SAL*12 FROM EMP ;

ALIAS :-

=> alias means another name or alternative name


=> aliases are 2 types

1 column alias
2 table alias

column alias :-

=> another name to column or expression is called column alias


=> used to change column heading

COLNAME / EXPR [AS] ALIAS

Ex :- 1 SELECT ENAME,SAL*12 AS ANNSAL


FROM EMP

2 SELECT ENAME,SAL*12 AS "ANNUAL SAL"


FROM EMP

3 SELECT ENAME,(SYSDATE-HIREDATE)/365 AS EXPERIENCE


FROM EMP

4 SELECT ENAME,SAL AS BASIC,COMM AS BONUS


FROM EMP

TABLE ALIAS :-

=> another name to the table is called table alias

TABNAME <ALIAS>

SQL>SELECT * FROM EMP E ;

ORDER BY clause :-

=> order by clause used to sort rows based on one or more


columns either in ascending or in descending order

SELECT COLUMNS
FROM TABNAME
[WHERE COND]
ORDER BY <COL> [ASC/DESC]

=> default order by ASC , for descending order use DESC

arrange emplist name wise asc order ?

SELECT *
FROM EMP
ORDER BY ENAME ASC ;

arrange emp list sal wise desc order ?


SELECT *
FROM EMP
ORDER BY SAL DESC ;

=> in ORDER BY we can use column name or column number

SELECT *
FROM EMP
ORDER BY 6 DESC ;

=> order by number is not according to table it is according


to SELECT list.

SELECT EMPNO,ENAME,HIREDATE,SAL,DEPTNO
FROM EMP
ORDER BY 5 ASC ;

arrange emp list dept wise asc and with in dept sal wise desc ?

SELECT EMPNO,ENAME,HIREDATE,SAL,DEPTNO
FROM EMP
ORDER BY 5 ASC ,4 DESC ;

1 A 5000 10 4 D 6000 10
2 B 4000 20 1 A 5000 10
3 C 3000 30 => 5 E 5000 20
4 D 6000 10 2 B 4000 20
5 E 5000 20 3 C 3000 30

STUDENT
SNO SNAME M P C
1 A 80 90 70 80
2 B 60 50 40 50
3 C 90 70 80 80
4 D 90 80 70 80

arrange list avg wise desc ,m desc,p desc ?

SELECT *
FROM STUDENT
ORDER BY (M+P+C)/3 DESC,M DESC,P DESC ;

4 D 90 80 70
3 C 90 70 80
1 A 80 90 70
2 B 60 50 40

List of tables ?

SELECT * FROM TAB ;

List of users ?

SELECT username from all_users ;

List of users name starts with 'S' ?

SELECT username
from all_users
where username like 'S%'

DML commands :-

INSERT
UPDATE
DELETE

=> these commands acts on data.


=> these commands acts on instance (RAM).
=> to save these operations execute COMMIT
=> to cancel these operations execute ROLLBACK

UPDATE command :-

=> command used to modify data in a table.

UPDATE <TABNAME>
SET COLNAME = VALUE,------
[WHERE COND]

update all employees comm to 500 ?

UPDATE EMP
SET COMM = 500 ;

update employees comm to 500 whose comm = null ?

UPDATE EMP
SET COMM = 500
WHERE COMM IS NULL ;

Incr sal by 20% and comm by 10% those working as salesman


and joined in 1981 year ?

UPDATE EMP
SET SAL=SAL + (SAL*0.2) ,
COMM=COMM + (COMM*0.1)
WHERE JOB='SALESMAN'
AND
HIREDATE LIKE '%81' ;

DELETE command :-

=> command used to delete row/rows from table


=> we can delete all rows or specific rows

DELETE FROM <TABNAME> [WHERE COND]

=> delete all rows from table ?

SQL> DELETE FROM EMP ;

=> delete employee list whose expr > 38 ?

SQL>DELETE FROM EMP


WHERE (SYSDATE-HIREDATE)/365 > 38 ;
FLASHBACK :-

=> using flsahback we can view the data that exists sometime
back.

=> a query that returns past data is called flashback query

=> used to recover data after commit.

the following query display 5 mins back data in emp table ?

SQL>SELECT * FROM EMP


AS OF TIMESTAMP(SYSDATE - INTERVAL '5' MINUTE);

recovering data after commit :

SQL>DELETE FROM EMP ;


SQL>COMMIT ;

=> to recover data , get the data that exists 5 mins back and
insert into current emp table

SQL>INSERT INTO EMP


SELECT * FROM EMP
AS OF TIMESTAMP(SYSDATE-INTERVAL '5' MINUTES)

DDL commands :-

CREATE
ALTER
DROP
TRUNCATE
RENAME
FLASHBACK
PURGE

=> ddl commands acts on structure


=> DDL commands are auto committed

DDL command = DDL command + commit

create table x(x number(2));


insert into x values(10);
insert into x values(20);
create table y(y number(2));
insert into x values(30);
insert into x values(40);
rollback ;

ALTER command :-

=> command used to modify table structure


=> using ALTER command we can

1 add columns
2 drop columns
3 rename column
4 modify column
incr / decr field size
changing datatype

Adding columns :-

ALTER TABLE <TABNAME>


ADD(COLNAME DATATYPE(SIZE),----) ;

add column gender to emp table ?

ALTER TABLE EMP


ADD(GENDER CHAR(1));

=> after adding to insert data into new the column use UPDATE
command.

UPDATE EMP
SET GENDER = 'M'
WHERE EMPNO = 7369 ;

UPDATE EMP
SET GENDER='&GENDER'
WHERE EMPNO = &EMPNO

Droping Column :-

ALTER TABLE <TABNAME>


DROP (COLNAME);

Drop column gender from emp table ?

ALTER TABLE EMP


DROP (GENDER);

Renaming a column :- (changing column name)

ALTER TABLE <TABNAME>


RENAME COLUMN <OLDNAME> TO <NEWNAME> ;

rename column comm to bonus ?

ALTER TABLE EMP


RENAME COLUMN COMM TO BONUS ;

SELECT EMPNO,ENAME,SAL,COMM AS BONUS FROM EMP ;

diff b/w alias & rename ?

ALIAS RENAME

1 changes only changes name of the column


column heading in the in table
select stmt output

2 not permanent permanent

Modifying column :-

1 incr / decr field size


2 changing datatype

ALTER TABLE <TABNAME>


MODIFY (COLNAME DATATYPE(SIZE) );

incr size of ename to 20 ?

ALTER TABLE EMP


MODIFY (ENAME VARCHAR2(20));

decreasing :-

ALTER TABLE EMP


MODIFY (ENAME VARCHAR2(6));

ALTER TABLE EMP


MODIFY (ENAME VARCHAR2(5)); => ERROR

=> char field size can be decreased upto the max length

ALTER TABLE EMP


MODIFY (SAL NUMBER(6,2)); => ERROR

=> numeric field must be empty to decrease size

ALTER TABLE EMP


MODIFY (EMPNO VARCHAR2(10)); => ERROR

=> column must be empty to change datatype.

DROP COMMAND :-

=> used to drop table from database.


=> drops table structure along with data.

DROP TABLE <TABNAME>

SQL>DROP TABLE EMP ;

TRUNCATE :-

=> deletes all the data from table but keeps structure
=> will empty the table
=> releases memory allocated for table

Syntax :- TRUNCATE TABLE <TABNAME>

Example :- SQL>TRUNCATE TABLE DEPT ;

diff among DROP,DELETE,TRUNCATE ?

DROP DELETE TRUNCATE

1 DDL command DML command DDL command

2 drops table deletes only data deletes only data


structure but keeps but keeps structure
with data structure
3 can't rolledback can be rolledback can't be rolledback

4 we can delete deletes only


specific rows all rows but
cannot delete
specific rows

5 deletes row-by-row deletes all rows


at a time

6 slower faster

7 will not release memory releases memory

RENAME :- used to change name of the table

RENAME <OLDNAME> TO <NEWNAME>

SQL>RENAME DEPT TO DEPARTMENTS ;

SQL
commands operations objects
DDL Filtering tables
DML sorting views
DQL functions synonyms
TCL grouping sequences
DCL merging indexes
analyzing materialized views
clusters
types

Built-in functions in Oracle :-

=> a function is block of code that accepts some input and


performs some calculation and returns one value.

Types of functions :-

1 string
2 date
3 mathematical
4 conversion
5 special
6 analytical
7 group

string functions :-

UPPER() :- converts string to uppercase

UPPER(arg1)

SQL>SELECT UPPER('hello') FROM DUAL ;

DUAL :- it is a dummy table provided by oracle used to select


non db values.
LOWER() :- converts string to lowercase

LOWER(arg)

SQL>SELECT LOWER('HELLO') FROM DUAL ;

display EMPNO,ENAME,SAL ?
display names in lowercase ?

SQL>SELECT EMPNO,LOWER(ENAME) AS ENAME,SAL FROM EMP ;

in table convert names to lowercase ?

SQL>UPDATE EMP SET ENAME=LOWER(ENAME) ;

SQL>COMMIT;

INITCAP() :- converts initials into capitals

INITCAP(str)

SQL>SELECT INITCAP('sachin tendulkar') FROM DUAL ;

Sachin Tendulkar

LENGTH() :- returns string length i..e no of chars

LENGTH(arg)

SQL>SELECT LENGTH('hello') FROM DUAL ; => 5

display employee list name contains 6 chars ?

SQL>SELECT * FROM EMP


WHERE ENAME LIKE '______' ;

SQL>SELECT * FROM EMP


WHERE LENGTH(ENAME) = 6 ;

SUBSTR() :- used to extract part of the string

SUBSTR(string,start,[len])

SUBSTR('hello welcome',7,4) => welc


SUBSTR('hello welcome',7) => welcome

SUBSTR('hello welcome',-4,3) => com


SUBSTR('hello welcome',-4) => come

employees name starts with 's' ?

SELECT * FROM EMP WHERE ENAME LIKE 's%';

SELECT * FROM EMP WHERE SUBSTR(ENAME,1,1) = 's' ;

name ends with 's' ?

SELECT * FROM EMP WHERE ENAME LIKE '%s' ;


SELECT * FROM EMP WHERE SUBSTR(ENAME,-1,1) = 's'

name starts with and ends with same char ?

SELECT * FROM EMP WHERE ENAME LIKE 'a%a'


OR
ENAME LIKE 'b%b'

SELECT * FROM EMP


WHERE SUBSTR(ENAME,1,1) = SUBSTR(ENAME,-1,1)

generate emailids for employees ?

EMPNO ENAME EMAILID


7369 smith smi736@tcs.com
7499 allen all749@tcs.com

|| => concatenation operator

'a'||'b' => ab

'a'||' '||'b' => a b

SELECT EMPID,ENAME,SUBSTR(ENAME,1,3)||
SUBSTR(EMPNO,1,3)||
'@tcs.com' AS EMAILID
FROM EMP

store emailids in db ?

1 add emailid column to emp table ?

ALTER TABLE EMP


ADD (EMAILID VARCHAR2(30));

2 update the column with emailids ?

UPDATE EMP SET EMAILID = SUBSTR(ENAME,1,3)||


SUBSTR(EMPNO,1,3)||
'@tcs.com' ;

3 commit;

LPAD & RPAD :-

=> used to fill string with a char for given no of times

LPAD(str,len,char) => fills on left side


RPAD(str,len,char) => fills on right side

LPAD('hello',10,'*') => *****hello


RPAD('hello',10,'*') => hello*****
RPAD('hello',10,'5') => hello55555
RPAD('*',10,'*') => **********

display ENAME, SAL ?


***
****
*****

SELECT ENAME,RPAD('*',LENGTH(SAL),'*') AS SAL


FROM EMP

smith ***
allen ****

scenario :-

ACCOUNTS
ACCNO BAL
12345678987 10000

your a/c no XXXX8987 debited ??????

RPAD('X',4,'X')||SUBSTR(ACCNO,-4,4)

LTRIM,RTRIM :-

=> used to remove spaces and unwanted chars

LTRIM(str1,[str2]) => removes left side


RTRIM(str2,[str2]) => remove right side

LTRIM(' hello ') => 'hello '


RTRIM(' hello ') => ' hello'
TRIM(' hello ') => 'hello'

LTRIM('$$$hello$$$','$') => 'hello$$$'


RTRIM('$$$hello$$$','$') => '$$$hello'

RTRIM('helloABCABCABC','ABC') =>

REPLACE() :- used to replace one string with another string

REPLACE(str1,str2,str3)

=> in str1 , str2 replaced with str3

REPLACE('hello','ell','abc') => habco


REPLACE('hello','l','abc') => heabcabco

REPLACE('$$he$$llo$$','$','') => hello

TRANSLATE() :- used to translate one char to another char

TRANSLATE(str1,str2,str3)

TRANSLATE('hello','elo','abc') => habbc

e=>a
l=>b
o=>c

=> used to encrypt data


SELECT ENAME,TRANSLATE(SAL,'0123456789',
'$bH*f@R^u#') as sal
FROM EMP ;

2975 => H#^@

Conversion :-

=> conversion means converting one type to another type

=> conversion is 2 types

1 implicit
2 explicit

implicit conversion :-

=> if conversion performed by oracle then it is called implicit


conversion.

Example 1 :-

SQL>SELECT 1000 + '1000' FROM DUAL ; => 2000

=> string '1000' automatically converted to number by oracle.

Example 2 :-

SQL>CREATE TABLE D(D DATE);

SQL>INSERT INTO D VALUES('13-SEP-19');

=> string '13-SEP-19' automatically converted to date by oracle

=> implicit conversion is not recommended because it degrades


performance , better to use explicit conversion.

Explicit Conversion :-

=> conversion performed by user is called explicit conversion

=> the following functions provided by oracle for explicit


conversion

1 TO_CHAR
2 TO_DATE
3 TO_NUMBER

converting date to char type :-

=> dates converted to char type to display dates in different


formats.

TO_CHAR(date,[format])

year formats :-

YYYY 2019
YY 19
CC 21
AD/BC AD YEAR/ BC YEAR

SELECT TO_CHAR(SYSDATE,'YYYY YY CC BC')


FROM DUAL ;

Months formats :-

MM 09
MON/mon SEP/sep
MONTH/month SEPTEMBER/september

Day formats :-

DDD day of the year (1-365)


DD day of the month (1-31)
D day of the week (1-7)
Day day of the week name
dy day of the week name

SELECT
TO_CHAR(SYSDATE,'DDD DD D day DY')
FROM DUAL ;

display employees joined on sunday ?

SELECT *
FROM EMP
WHERE TO_CHAR(HIREDATE,'dy')='sun'

time formats :-

HH hour part
HH24 hour part in 24 hrs format
MI minute
SS seconds
AM/PM AM time or PM time

display date & time ?

SELECT
TO_CHAR(SYSDATE,'DD month YY HH:MI:SS AM')
FROM DUAL ;

Week formats

W week of the month (1-5)


WW week of the year (1-52)

Quarter : -

Q Quarter

1 jan-mar
2 apr-jun
3 jul-sep
4 oct-dec

S-ar putea să vă placă și