Sie sind auf Seite 1von 37

DBMS: A database management system (DBMS) is a software package with computer

programs that control the creation, maintenance, and use of a database.


To open Oracle in Command prompt just type sqlplus in RUN.
RDBMS: RDBMS stands for relational database management system. A relational database is
the one in which data is stored in the form of tables i.e. rows and columns. And a system that
manages this database is known as database management system. The major functions performed
by RDBMS are creating, editing and deleting tables and inserting, deleting and editing data into
that tables.
The data items are recognized by a unique entry known as primary key. The main examples of
RDBMS are Oracle, SQL server, DBase.
SQL(Structured query language)
1. It is non procedural language which is used to communicate any type of database such as
Oracle DB2, SQL server e.t.c.,
2. This language was developed by a German scientist MR MF Codd in 1968. ANSI
approved this language in 1970 and it was released at 1972.
Query: Query is a mechanism by using query we can perform language operations. Those are
DML,DDL,DRL,DCL,TCL.
Features of SQL:
1. Sql is not a case sensitive language because all the commands of SQL we can write in
capital letters or small letters.
2. Every command of SQL should ends with semicolon.
3. SQL can also Pronounced as SEQUEL (Structured English query language).
4. SQL can call as NLI(Natural language interface) because every command of SQL almost
similar reassembles to normal English language.
5. SQL can be called as common language interface because this is the only language to
communicate with any type of database such as Oracle, Sybase, DB2, Teradata e.t.c.,
6. Structure query language was mainly subdivided into five sublanguages those are
fallowing types.
Data
Definition
Language
(DR CAT)
DROP
Rename
CREATE
ALTER
TRUNCATE

Data
Manipulation
Language

Data
Retrieval
Language

Transition
Control
Language(Three)

Data Control
Language(Double)

INSERT
DELETE
UPDATE

SELECT

COMMIT
ROLLBACK
SAVEPOINT

GRANT
REVOKE

Data types in Oracle 10g:


These data types are totally divided into two types.
1. Number
2. Alphabet.
1. NUMBER: This data type allows us to enter numeric values such as integer values or
decimal values. In SQL these data types further divided into
(1) NUMBER(SIZE)-to store integers
(2)NUMBER(P,S) (P=Precision, S= Scale)-to store decimal values
I.

NUMBER(SIZE): This data type allows us to enter only integer values student roll
numbers employee numbers e.t.c., Here size represents no of digits.

EX: EID NUMBER(3)


1. NUMBER(P,S) : This data type allows us to enter decimal values such as Employee
salaries student average marks e.t.c., Here p represents precision and s represents scale.
Here Precision means no of digits including decimal points where as scale means no of
decimal places.
EX:
ESAL NUMBER(6,2)
AM NUMBER(3,2)
II.

Alphabets: The data type allows us to enter character values such as student names
employee names e.t.c., this data type is further divided into three types 1. Char(Size)
2. Varchar(Size), 3. Varchar2(Size)

Char(Size): This data type allows us to enter character values the maximum length of this data
type is 1 to 2000 bytes of characters this data type always allocates the memory in a static
fashion.
EX:Ename char(15)
Varchar(Size)/Varchar2(Size): This data type also allows us to enter character values such as
student names, employee names e.t.c., The maximum length of this data type is 1 to 4000
characters or bytes. It always allocates the memory in a dynamic fashion.
Note: The difference between varchar data type and varchar2 data type is Varchar data type is
developed along with SQL where as varchar2 data type developed by Oracle corporation

varchardata type always allocates the memory in a dynamic fashion where as varchar2 data type
supports garbage values.
DATE: The data type allows us to enter date values such as student joining date employee
hiring data e.t.c., the default date format is Oracle is DD/MM/.YYYY.
Ex:Jdate date
Timestamp: The data type allows to enter both date and time values. The default format of
timestamp is DD/MM/YYYY HH/MM/SS.
EX:Logintime timestamp
Miscelluniousdatatypes: These data types are further divided into three types CLOB, BLOB,
Bfile.
i)

CLOB(Character Large Object): This datatype allows us to all types of characters


and the minimum length of this datatype is 1 to 4GB.
Whenever we need to enter employee history student conduct e.t.c., then we need to
use this data type.
ii)
BLOB(Binary large Object): This datatype allows us to enter any type of photos,
graphical picturesclippings, sounds, multimedia messages e.t.c., the minimum length
of this data type is 1 to 4 GB.
iii)
BFILE: This data type also allows us to enter BLOB types of values and also binary
data, XML data e.t.c., the minimum length of data type is 1 to 4 GB.
1. Data definition Language: This is the first sub language in SQL which is used to define
the database objects such as table, view, synonym, index and sequence. This language
contains five commands those are
i)CREATE ii) ALTER iii) RENAME iv) TRUNCATE v)DROP.
i) CREATE: This command is used to creating the database objects such as Table, View e.t.c.,
Syntax: create table <table name>
(col1datatype(Size),
col2datatype(Size),
colndatatype(size));
ex: create table emp(eidvarhcar(3), ename varchar2(12), sal number(6,2));
Rules for naming a table:

1. Table name should start with alphabets which contains minimum 1 and maximum 30
characters it should not allows any spaces or any special characters such as except _# and
0 to 9.
2. A table can have minimum 1 column maximum thousand columns.
3. A table can have 0 no of records and maximum n no of records up tohard disk capacity.
4. Oracle reserved keywords and words should not be used column names or table names.
5. The rules which we are following for table name the same rules are applicable for column
names.
6. The numeric precision for column must be 1 to 38.
I)
ALTER: This command is used to modify the structure of the table. Using this
command we can perform four different operations. This command contains four
subprograms those are

ALTER Modify
ALTER ADD
ALTER RENAME
ALTER DROP
ALTER Modify: This command is used to increase or decrease the size of the data type and
also we can use the data type from all data type to new data type.
Syntax: ALTER TABLE <Table name> MODIFY <Column name> data type(size)
EX:ALTER TABLE EMP MODIFY ENAMEVARCHAR2(20);
Syntax for modify more than one column:
ALTER TABLE <Table name> MODIFY (col1 data type(size), col2 data type(size)----,coln data
type(size))
EX: Alter table emp modify (eidnumber(5), ename char(10));
ALTER ADD: This command is used to add a new column to the existing table.
Syn: ALTER TABLE<Table name>add column name datatype(size)
EX: ALTER TABLE EMP ADD DEPTNO NUMBER(3)
Syntax to add more than one column:
ALTER TABLE<table name> add (col1 datatype(size), col2
datatype(size)----,colndatatype(size))
4

EX: ALTER TABLE EMP ADD(mbnno number(10), addrs varchar2(10))


Note:When ever we add a new column to a table the new column is always added to the end of
the table only.
ALTER RENAME: This command is used to change the column name from old column name
to new column name.
Syn: ALTER TABLE<table name> rename column<old column name> to <new column name)
EX: ALTER TABLE EMP RENAME COLUMN SAL TO SLARY.
Syntax change table name:
ALTER TABLE<old table name> RENAME TO <New table name>
EX: ALTER TABLE EMP RENAME TO EMP1;
ALTER DROP: This command is used to remove the column from the existing table.
Syn: ALTER TABLE< table name>DROP COLUMN COLUMN NAME.
EX: ALTER TABLE EMP DROP COLUMN DEPTNO.
Syntax to drop more than one column:
ALTER TABLE EMP DROP(eid, ename, salary, mbno, addrs)// Here we cant drop all columns.
II)

RENAME: This command is used to change the table name from old table name to
new table name.

Syn: RENAME <old table name> to <new table name>


EX: RENAME EMP TO EMP1;
III)

TRUNCATE: This command is use delete records permanently from the existing
table.

Syn: TRUNCATE TABLE<table name>


Syn: TRUNCATE TABLE EMP;
IV)

DROP: This command is used to drop entire data from database.

Syn: DROP TABLE< table name>


EX: DROP TABLE EMP;
Difference between TRUNCATE and DELETE:
5

1. TRUNCATE is DDL command, DELETE is DML command.


2. We can delete data permanently through TRUNCATE; Through DELTE it is temporarily.
3. We cant delete single record Through TRUNCATE, but it is possible through DELTE.
Recycle bin: To retrieve data from recycle bin
Syn: Select * from recycle bin
2. Data Manipulation Language: This is the second sub language in SQL which contain
four commands those are INSERT, UPDATE, SELECT, DELETE and which is used for
manipulate the data within database.
INSERT: This command is used to insert the records in the table using this command we can
insert the data into the table in two methods
1. Explicit method 2. Implicit method
i)
Explicit Method: In this method user need to enter all the values into the columns
without left any column data.
Syn: INSERT INTO <TABLE NAME>VALUES (Val1, Val2,------,Valn)
EX: INSERT INTO EMP Values(101,RAJU,500)
Note: We can use &&in front of any column. Byplacing like this the use is It takes
particular column values as default for remaining all values.
Syntax to insert the records into the table using insertion operation:
INSERT INTO<Table name>VALUES(&col1,&col2,--------,&coln)
EX: INSERT INTO EMP Values(&Eid,&Ename,&Sal)
Implicit method: This method we can enter the values at required columns in the table.
EX: INSERT INTO < Table name> (Col1,Col2,------,Coln) values(Val1, Val2,--------,Valn)
EX: INSERT INTO EMP(EID,SAL) VALUES(115,9800)
Syntax to insert record using & Symbol:
INSERT INTO < TABLE NAME>(col1,col2,-------,coln) values(&col1,&col2------,&coln)
EX: INSERT INTO EMP(Eid,Sal) VALUES(&Eid,&Sal) VALUES(&Eid,&Sal)
UPDATE: This command is used to modify the data existing table. Using this command we can
modify all the records in the table also we can modify specific records in the table using WHERE
clause.
6

Syn: UPDATE <Table name> SET COLUMN NAME = VALUE


Syn: UPDATE EMP SET ENAME = RAJU
Syntax to modify more than one column data at a time:
UPDATE <Table name> SET COL1=VALUE,COL2=VALUE,-------,COLN=VALUE
EX: UPDATE EMP SET EID = 007, ENAME = JAMES
DELETE: This command is used to delete the records from the existing table. Using this
command we can delete all the records and also we can delete specific records from the table.
Syn: DELETE FROM <Table Name><Column Name>
EX: delete from rose no;
EX: delete from rose where name='UPASANA';
EX3: delete rose name where name='upasana' or name='vijay';

3. Data Retrieval Language:


SELECT: This command is used to retrieve the data from the existing table. Using this
command we can retrieve all records and also we can retrieve some specific records in the
table(Using where clause).
Syn: SELECT * FROM < Table Name>
EX: SELECT * FROM EMP;
Here * represents all columns.
SELECT with DISTINCT:
The DISTINCT keyword can be used to return only distinct (different) values.
SELECT DISTINCT column_name,column_name
FROM table_name;

ALIASES: Alias is duplicate name or an alternative name for the original column name or table
name or expression name. Whenever we need to submit meaningful or understanding reports
then we need to use alias names.
We can provide the alias names in two levels i) Column level ii) Expression level.
7

i)

Column level Alias: Providing the alias name for the columns is called column level
alias.

Syn: SELECT COL1 AS ALIAS NAME, COL2 AS ALIAS NAME ,---------,COLUMN


NAME N AS ALIAS NAME FROM <Table name>
EX: SELECT EID AS EMPLOYEEID, ENAME AS EMPLOYEE NAME FROM
EMP;
In the above example the keyword as is an optional keyword.
Syn: SELECT COL1 ALIAS NAME, COL2 ALIAS NAME, -------,COLN ALIAS
NAME FROM <Table name>
EX: SELLECT EID EMPLOYEEID, ENAME EMPLOYEE NAME FROM EMP;
In the above example we no need to use double quotation.
Syn: SELECT COL1 ALIASNAME, COL2 ALIASNAME,--------,COLN ALIASNAME FROM
<Table name>
EX: SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME FROM EMP;

ii)

Expression Level alias:

Providing the alias names for expressions is known as expression level alias.
EX: SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL SALARY, SAL*12
ANNUALSALARY FROM EMP;
EX:SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL ANNUALSALARY,
SAL*12 ANNUALSALARY FROM EMP WHERE ANNUALSALARY>150000
O/P: ANNUAL SALARY in valid identifier because Alias names are not identifiers. Identifier
means column name.
Note: The above example the fallowing error message- Annual salary invalid identifier. So we
cant check the conditions of Alias names.
EX: SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL SALARY, SAL*12
ANNUALSALARY FROM EMP WHERE SAL*12>150000
8

EX: SELECT EMP.*, SAL*12 ANNUALSALARY FROM EMP WHERE SAL*12>150000


Where clause: This clause is used to check the condition based on the condition we can retrieve,
we can modify, and we can remove some specific records in the table.
Operators in SQL:Operator means special symbol which performs some specific operations on
operators.
1. Arithmetic operator: +, -,*, /, MOD
2. Logical: AND, OR, NOT.
3. Relational: > ,< ,>= ,<= ,!=,<>,=

The SQL IN condition (sometimes called the IN operator) allows you to easily test if an
expression matches any value in a list of values.
The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition
in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.

The SQL BETWEEN condition allows you to easily test if an expression is within a range of
values (inclusive). It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
The Oracle SQL TO_DATE function converts a string to a date.
The SQL LIKE condition allows you to use wildcards to perform pattern matching in a query.
The LIKE condition is used in the WHERE clause of a SELECT, INSERT, UPDATE, or
DELETE statement.

Wildcard

Explanation

Allows you to match any string of any length (including zero length)

Allows you to match on a single character

SQL Subquery
Subquery or Inner query or Nested query is a query in a query. SQL subquery is usually added in
the WHERE Clause of the SQL statement. Most of the time, a subquery is used when you know
how to search for a value using a SELECT statement, but do not know the exact value in the
database.

Ex:
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');

The SQL EXISTS condition is used in combination with a subquery and is considered to be
met, if the subquery returns at least one row. It can be used in a SELECT, INSERT,
UPDATE, or DELETE statement.

10

Update Where Clause:


Q) Write a query that changes the employees salary as 2500 whose empno is 7788.
A) updateemp set sal = 2500 where empno=7788;
Q) write a query change the employees salaries as 5000 who are working under 10 th
department.
A) updateemp set sal=5000 where deptno in(10);
(OR)
updateemp set sal=5000 where deptno = 10;
Q) write the query hike the employees salaries 30% who are working in the 10th Department.
A) updateemp set sal=sal+sal*0.3 where deptno in(20);
(OR)
updateemp set sal=sal+sal*(30/100) where deptno in(20);
Q) write the query increase the employees salaries 1000 whose names start with A.
A) updateemp set sal=sal+1000 where ename like 'A%';
Q) Write a query increases the employees salary 1000/- whose name is SCOTT working under
20th DEPT.
A) updateemp set sal=sal+1000 where ename='SCOTT' and deptno = 20;
Q) Increase the employee salary by 1000 whose name starts with S and ends with T and third
letter is O.
A) updateemp set sal=sal+1000 where ename like 'S_O%T';
Q) Change deptno=30 whose empsal between 1500 to 3000
A) updateemp set deptno=30 where sal between 1500 and 3000;
(OR)
updateemp set deptno=30 where sal>=1500 and sal<=3000
Q) Change job as clerk whose job is manager are joined before 1982.
Update emp set job = 'CLERK' where job = 'MANAGER' and hiredate< '01-JAN-1982';
11

Q) Write a query to increase the employees salaries 1000 who are having more than 10 years.
A) updateemp set sal = sal+1000 where (sysdate-hiredate)/365>10;
Q) Write a query change the employees salaries as 7000 who are having commission.
A) updateemp set sal=sal+7000 where comm>=0;
Q) Write a query change the employees salary 10000 who are not working under anybody.
A) updateemp set sal = sal+10000 where mgr is null;
Q) Write a query change employee name as Srinivas and Salary 9000 whose empno=7566.
A) update emp set ename = 'SRINIVAS' and sal = 9000 where empno =7566;
Q) Write a query change the employees salary 5000 whose name contain more than 6 Character.
A) updateemp set sal = 5000 where length(ename)>6;
Q) Change employee salary 2344 where employee name ending with K.
A) updateemp set sal = 2344 where ename like '%K';
Q) Change employee salary 4000 whose hiredate is 23rd MAY 87.
A) updateemp set sal =4000 where hiredate = 23-MAY-87
Q) Change the employee salary as 6000 whose joining month in start with M.
A) Update emp set sal=6000 where hiredate like ___M%;
Q) Change employee salary 1234 where hiredate is in the month MAY or which starts with M
and ends with Y
A) update employee2 set salary=1234 where hiredate like '___M%';
Q)Change the employee salary 4567 where hiredate is 23rd.
A) updateemp set sal=4567 where hiredate like '2%3%';

Delete with where clause:


Syn: DELETE FROM <Table name> where <condition>
EX: DELETE FROM EMP WHERE EMPNO=7788

12

Q) Write a query delete employee details who are working under 10th DEPT.
A) delete from emp where deptno in (10);
Q) Write a query delete the employee details who are working under 10th and 20th DEPT.
A) delete from emp where deptno =10 or deptno =20;
NOTE: Here we didnt use and because an employee doesnt work in two departments. So we
can write this query two ways.
deleteemp where deptno in(10,20);
Q) Write a query delete the employee who joined in the month april?
A) delete from emp where hiredate like '%APR%';
(OR)
delete from emp where hiredate like '___A%P%';
Q) Write a query to delete the emp details whose salary not in range of 2000 and 3000
A) delete from emp where sal not between 20000 and 30000;
Q) find all of the records from the customers table where there is at least one record in
the orders table with the same customer_id
A) select *from customers where exists(select *from order1 where customers.id=cusid)
Order By:
This clause is used to arrange the data either ascending or descending order. By default order
by clause will arrange the data in ascending order.
If we want to arrange the data in descending order then we use an option called DESC stands
for descending order.
We use order by clause on character columns then it will arrange the data in alphabetic order.
We can apply the order by clause on more than one column in the same table.
We can apply the order by clause only with the select command.
Syntax by applying order by clause
SEELCT * FROM EMP ORDER BY <Column name><ASCE><DESC>
EX: Select * from xyz order by ename salary desc;
13

Functions:

A function is a self contained block which is use to perform some task.


The main advantage of function is code reusability.
Then it automatically reduces the redundancy of the instructions so that reduces the
maintenance cost and increase the system performance.
Function always returns only one value.

Functions are dividing into two types.


1. System/predefined functions
2. User defined functions
1. System defined functions:A function which is defined by the system comes along with
the software those functions can be called as System defined functions.
2. User defined functions: A function which is defined manually and programmatically
those functions are called used defined functions.
In SQL predefined functions are further divided into two types.
i)
ii)

i.

Single row functions


Multiple row functions
Single row functions: Single row functions are those functions will work on each
and every record in the table and returs one value.
Multiple row functions: Multiple row functions are those functions will work on the
entire table and returns only one value.

Single row functions are further divided into following types.


1. STRING/CHAR
2. MATH/NUMERIC
3. DATE
Multiple row functions are divided into 5 types.
1.
2.
3.
4.
5.

MAX
MIN
SUM
AVG
COUNT

Tables: It can be defined as collection of columns and rows tables are divided into two types.
i) Database Tables ii) NON database tables.
i.
Database Tables: A database table is a table which contains actual information.
14

ii.

Non Database Tables: A non database table is a table which doesnt contain any
information.

EX: DUMMY or DUAL.


STRING/CHAR FUNCTIONS:
1. ASCII(): This function returns the ASCII value of a character.
EX: select ASCII('a') from dual;
2. Chr(): This function return the high level language value from ASCII code.
EX: SQL> select chr(97) from dual;
3. CONCAT( ): This function is used to concatenate two strings
EX: select concat('Sathya','Technologies') from dual;
4. INITCAP( ): This function allows first letter of every word into the Capital letter.
EX: select initcap('sivabhargava reddy') as name from dual;

5. LENGTH( ): This function returns the length of the String.


EX: SQL> select length('Sathya technologies') from dual;
EX2: SQL> select ename , length(ename) from emp;
6. LOWER( ):function converts the String into the small letters.
EX: select lower('BHARGAV') from dual;
7. UPPER(): This function converts the String into the capital letters.
EX: select upper('bhargav') from dual;
8. LTRIM(): This function allows us to remove the blank spaces from the left hand side of
the string.
EX: select ltrim('

Bhargav') from dual;

9. RTRIM(): This function allows us to remove the blank spaces from the right hand side
of the string.
EX: select rtrim('BAHRGAV

') from dual;


15

Select rtrim(BHARGAV,AV) from dual;


10. TRIM(): This function trims both sides of values.
EX: select trim( '

ifrom indian

') from dual;

11. REPLACE(): This function is used to replaces more than a one character.
EX: select replace('jaack and jaar','ja','bl') from dual;
12. REVERSE(): This function allows us to reverse a word.
EX: select reverse('bhargav') from dual;
13. SUBSTR(): This function is use to returns the path of the string from the main string.
EX: select substr('Sathya technologies','7') from dual;

Math functions:
1. ABS( ): This function is used to convert VE values into +VE values.
EX: select abs(-9.5) from dual;
2. CEIL( ):This function is used to round the given number to highest number.
EX: select ceil(9.4) from dual;
1. Greatest( ): This function is used to returns the maximum value from list of numbers.
EX: select greatest(5,6,7,8) from dual;
2. Least():This function is used to returns the minimum value from list of numbers.
EX: select least(5,6,7,8) from dual;
3. MOD(): this function returns reminder value from given number.
EX: select mod(10,2) from dual;
4. ROUND(): This function round converts given number to nearest number.
EX: Select round(-9.4) from dual;
EX: Select round(-9.5) from dual;
The above example shows the output -10 because round treats 9.5 as 10.
16

5. SIGN(): This function returns the sign of the given value.


EX: select sign(-9.4) from dual;
6. SIN(): This function give sin value of given number.
EX: select sin(12) from dual;
We can get cot,tan,,sec,cosec also.
7. SQRT(): This function square roots the given function.
EX: select sqrt(16) from dual;

Date functions: These functions are classified into four types


1.
2.
3.
4.
1.

MONTHS_BETWEEN
ADD_MONTHS
LAST_DAY
NEXT_DAY
MONTHS BETWEEN(): This function is used to find out months between two dates.

EX: select MONTHS_BETWEEN(sysdate, '12-FEB-11') from dual;


2. ADD_MONTHS: This function is used to add the no of months to the given date.
EX: select ADD_MONTHS(sysdate, 12) from dual;
3. LAST_DAY(): This is used to display last day of the month from current day or other
days.
EX:select last_day(sysdate) from dual;
4. NEXT_DAY(): This function is used to find the next date of the same day which is
specified as second parameter .
EX: select NEXT_DAY('01-Aug-16', 'monday') from dual;
Multiple rows functions
Group or Aggregate functions: These functions are classified into five types those are
SUM(), MAX(), MIN(), AVG(), COUNT().
1. SUM(): This function is used to find out sum of the all values of a particular column in
the table.

17

EX: select sum(sal) from emp;


2. AVG(): This function is used to find out an average value of tables column
EX: Select avg(sal) from dual;
3. MAX(): This function is used to find maximum value of particular tables column
EX: select MAX(SAL) from emp;
4. MIN(): This function is used to find minimum value of particular columns value.
EX: select MIN(SAL) from emp;
5. COUNT(): This function is used to count the no of records in the given table. It contains
the sub functions COUNT(*), COUNT(exp), COUNT(dis exp).
i)
Count(): This function is used to count the no of records in the given table including
duplicate and null values.
EX: select count(*) from emp;
ii)

Count(exp): This function is used to count the no of records in the given table
including duplicate values but excluding null values.

EX: select count(mgr) from emp;


iii)

Count(distinct): This function is used to count no of records in the given table


excluding duplicate and null values.

EX: select count(distinct mgr) from emp;


TO_NUMBER: This will convert a char or varchar to number.
EX: SQL> select to_number('10') from dual;

TO_NUMBER('10')
--------------10
TO_CHAR
This will be used to extract various date formats.
The available date formats as follows.
18

Syntax: to_char (date, format)


D

--

No of days in week

DD

--

No of days in month

DDD

--

No of days in year

MM

--

No of month

MON

--

Three letter abbreviation of month

MONTH

--

Fully spelled out month

DY

--

Three letter abbreviated day

DAY

--

Fully spelled out day

--

Last one digit of the year

YY

--

Last two digits of the year

YYY

--

Last three digits of the year

YYYY

--

Full four digit year

SQL> select to_char(sysdate,'dd month year') from dual;


TO_CHAR(SYSDATE,'DDMONTHYEAR')
TO_DATE
This will be used to convert the string into date format.
Syntax: to_date (date)
select to_date('24/dec/2006','dd/mon/yyyy')from dual;
Ex:

19

SQL> select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd *


month * day')

from dual;

1GROUP BY AND HAVING


GROUP BY
Using group by, we can create groups of related information.
Columns used in select must be used with group by, otherwise it was not a
group by expression.
Ex:
select deptno,sum(salary) as totalsalary from employee2 group by deptno;
SQL> select deptno, sum(sal) from emp group by deptno;
DEPTNO

SUM(SAL)

---------- ---------10

8750

20

10875

30

9400

SQL> select deptno,job,sum(sal) from emp group by deptno,job;


DEPTNO JOB

SUM(SAL)

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

----------

20

10

CLERK

1300

10

MANAGER

10

PRESIDENT

5000

20

ANALYST

6000

20

CLERK

1900

20

MANAGER

30

CLERK

30

MANAGER

2850

30

SALESMAN

5600

2450

2975
950

HAVING
This will work as where clause which can

be used only with group by

because of absence of where clause in group by.


On top of the Group by if we want to filter the groups then we use having
clause.
Ex:
SQL> Select empno, name,address,count (*) from EMP group by empno,
name,address

having count (*)>1;


EMPNO

NAME

ADDRESS

---------- --------200
300

SHAM

HYD

MOHAN

BANG

21

COUNT

----------

-----3
2

SQL> select deptno,job,sum(sal) tsal from emp group by deptno,job


having sum(sal) > 3000 order by job;

DEPTNO

JOB

TSAL

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

20

----------

ANALYST

6000

10

PRESIDENT

5000

30

SALESMAN

5600

ORDER OF EXECUTION
First apply grouping mechanism and do the required calculations on the
group then apply having on group values not on individual values
Group the rows together based on group by clause.
Calculate the group functions for each group.
Choose and eliminate the groups based on the having clause.
Order the groups based on the specified column.

To copy a table from another without data:


create table student1 as select *from student where 1=0;
To copy a table from one table to another table with data:
SYN: CREATE TABLE<Target table name> AS SELECT * FROM <Source Table name>
Syntax to copy a table to another table with specific columns only
CREATE TABLE TABLE NAME<Target table name> as select col1,col2,-------,coln from
<source table name>
Insert the data from one table to another table:

22

SYN: insert into elora1 select * from elora;

Set Operators

To Combine two queries we need set operators.


TYPES
Union
Union all
Intersect
Minus
1UNION
This will combine the records of multiple tables having the same structure.
Ex:
SQL> select * from student1
Union
select * from student2;
2UNION ALL
This will combine the records of multiple tables having the same structure
but including duplicates.
Ex:
SQL> select * from student1 union all select * from student2;

23

3INTERSECT
This will give the common records of multiple tables having the same
structure.
Ex:
SQL> select * from student1 intersect select * from student2;
4MINUS
This will give the records of a table whose records are not in other tables
having the same structure.
Ex:
SQL> select * from student1 minus select * from student2;
3

Constraints

Constraints required maintaining consistence data in a database.


Constraints are categorized as follows.

Domain integrity constraints


Not null
Check
Entity integrity constraints
Unique
Primary key
Referential integrity constraints
Foreign key
Constraints are always attached to a column not a table.
24

We can add constraints in three ways.


Column level

-- along with the column definition

TABLE LEVEL
Alter level

-- after the table definition


-- using alter command

While adding constraints you need not specify the name but we should
specify the type
oracle will internally name the constraint.
If you want to give a name to the constraint, you have to use the constraint
clause.
1NOT NULL
This is used to avoid null values.
We can add this constraint in column level only.
Ex:
SQL> create table student(no number(2) not null, name varchar(10),
marks

number(3));

SQL> create table student(no number(2) constraint nn not null, name


varchar(10), marks number(3));
2CHECK
This is used to insert the values based on specified condition.
We can add this constraint in all three levels.
Ex:
COLUMN LEVEL

25

SQL> create table student(no number(2) , name varchar(10), marks


number(3) check

(marks > 300));

SQL> create table student(no number(2) , name varchar(10), marks


number(3)

constraint ch check(marks > 300));

TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10), marks
number(3), check

(marks > 300));

SQL> create table student(no number(2) , name varchar(10), marks


number(3)

constraint ch check(marks > 300));

ALTER LEVEL
SQL> alter table student add check(marks>300);
SQL> alter table student add constraint ch check(marks>300);
3UNIQUE
This is used to avoid duplicates but it allow nulls.
We can add this constraint in all three levels.
Ex:

COLUMN LEVEL
SQL> create table student(no number(2) unique, name varchar(10),
marks number(3));
SQL> create table student(no number(2) constraint un unique, name
varchar(10),

marks number(3));

26

TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10),
marks number(3),

unique(no));

SQL> create table student(no number(2) , name varchar(10), marks


number(3),

constraint un unique(no));

ALTER LEVEL
SQL> alter table student add unique(no);
SQL> alter table student add constraint un unique(no);
4PRIMARY KEY
This is used to avoid duplicates and nulls. This will work as
combination of unique and not null.
Primary key always attached to the parent table.
Primary key will create Unique index by default.
We can add this constraint in all three levels.
Ex:
COLUMN LEVEL
SQL> create table student(no number(2) primary key, name
varchar(10), marks

number(3));

SQL> create table student(no number(2) constraint abc primary key, name
varchar(10),

marks number(3));

TABLE LEVEL
SQL> create table student(cno number(2) , name varchar(10), marks
number(3),

primary key(no));
27

SQL> create table student(no number(2) , name varchar(10), marks


number(3),

constraint pk primary key(no));

ALTER LEVEL
SQL> alter table student add primary key(cno);
SQL> alter table student add constraint pk primary key(no);
5FOREIGN KEY
This is used to reference the parent table primary key column which
allows duplicates.
Foreign key always attached to the child table.
We can add this constraint in table and alter levels only.
Ex:
TABLE LEVEL
SQL> create table emp(empno number(2), ename varchar(10), deptno
number(2),

Primary

key(empno),

foreign

key(deptno)

references

dept(deptno));
SQL> create table emp(empno number(2), ename varchar(10), deptno
number(2),

constraint pk primary key(empno), constraint fk foreign

key(deptno) references

dept(deptno));

ALTER LEVEL
SQL> alter table emp add foreign key(deptno) references
dept(deptno);
SQL> alter table emp add constraint fk foreign key(deptno)
references dept(deptno);
28

Once the primary key and foreign key relationship has been created then
you can not remove any parent record if the dependent childs exists.

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);

USING ON DELETE CASCADE


By using this clause you can remove the parent record even it childs exists.
Because when ever you remove parent record oracle automatically removes
all its dependent records from child table, if this clause is present while
creating foreign key constraint.
Ex:
TABLE LEVEL

29

SQL> create table emp(empno number(2), ename varchar(10), deptno


number(2),

primary

dept(deptno) on delete

key(empno),

foreign

key(deptno)

references

cascade);

SQL> create table emp(empno number(2), ename varchar(10), deptno


number(2),

constraint pk primary key(empno), constraint fk foreign

key(deptno) references

dept(deptno) on delete cascade);

ALTER LEVEL
SQL> alter table emp add foreign key(deptno) references dept(deptno)
on delete

cascade;

SQL> alter table emp add constraint fk foreign key(deptno)


references dept(deptno) on

delete cascade;

JOINS:

SQL JOINS

SQL JOIN
An SQL JOIN clause is used to combine rows from two or more tables, based
on a common field between them.

30

The most common type of join is: SQL INNER JOIN (simple join). An SQL
INNER JOIN returns all rows from multiple tables where the join condition is
met.

Inner Join (or) Equi Join:


The INNER JOIN creates a new result table by combining column values of two tables
(table1 and table2) based upon the join-predicate.
The query compares each row of table1 with each row of table2 to find all pairs of
rows which satisfy the join-predicate. It returns rows when there is a match in both
tables.
When the join-predicate is satisfied, column values for each matched pair of rows of
A and B are combined into a result row

INNER JOIN

31

JOIN Syntax:
select c.id,name,date1,amount from customers c,orders o where c.id=o.id;
select c.id,name,date1,amount from customers c join orders o on c.id=o.id;

This would produce the following result:

Left Outer Join:


The SQL LEFT JOIN returns all rows from the left table, even if there are no matches
in the right table. This means that if the ON clause matches 0 (zero) records in right
table, the join will still return a row in the result, but with NULL in each column from
right table.
This means that a left join returns all the values from the left table, plus matched
values from the right table or NULL in case of no matching join predicate.
32

Returns all rows from the left table, even if there are no matches in the right table.

In some databases LEFT JOIN is called LEFT OUTER JOIN.

Now, let us join these two tables using LEFT JOIN as follows:

33

SQL> select c.id,name,amount,date1 from customers c left join orders o on c.id=o

.id;
Right Outer Join:
The SQL RIGHT JOIN returns all rows from the right table, even if there are no
matches in the left table. This means that if the ON clause matches 0 (zero) records
in left table, the join will still return a row in the result, but with NULL in each column
from left table.
Returns all rows from the right table, even if there are no matches in the left table.
This means that a right join returns all the values from the right table, plus matched
values from the left table or NULL in case of no matching join predicate.

In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

34

Full Outer Join:

35

6A FULL OUTER JOIN is neither "left" nor "right" it's both! It


includes all the rows from both of the tables or result sets
participating in the JOIN. When no matching rows exist for rows
on the "left" side of the JOIN, you see Null values from the
result set on the "right." Conversely, when no matching rows
exist for rows on the "right" side of the JOIN, you see Null
values from the result set on the "left." SQL FULL OUTER

JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

SQL FULL JOIN Example

The "Persons" table:


P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

The "Orders" table:


O_Id

OrderNo

P_Id

77895

44678

22456

24562

34764

15

Now we want to list all the persons and their orders, and all the orders with their persons.

36

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo


FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678

Svendson

Tove
34764

The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right table (Orders). If there are
rows in "Persons" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Persons", those
rows will be listed as well.

1.

join:
The SQL JOIN clause is used whenever we have to select data
from 2 or more tables.
To be able to use SQL JOIN clause to extract data from 2
(or more) tables, we need a relationship between certain
columns in these tables.
union:
The purpose of the SQL UNION command is to combine the
results of two queries together. In this respect, UNION is
somewhat similar to JOIN in that they are both used to
related information from multiple tables. One restriction
of UNION is that all corresponding columns need to be of
the same data type. Also, when using UNION, only distinct
values are selected (similar to SELECT DISTINCT).

37

Das könnte Ihnen auch gefallen