Академический Документы
Профессиональный Документы
Культура Документы
Database:A
Database
is
a
collection
i.e;
tables,views,indexes,stored procedure and triggers.The data
stored in a database may be related to any process such as
Inventory / Payroll System
RDBMS:A collection of related data. Some popular RDBMS
are:
Oracle Oracle Corporation
MS SQL 7.0
Microsoft Corporation
Sybase Sybase Inc.
Informix Informix Inc.
Ingress Ingress Inc.
DB/2
A Database which supports at least 6 Rules of 12 Rules of
Boyce-Codd called RDBMS otherwise DBMS
Entity:
An Entity is an object with distinct set of easily
identifiable properties.They are building blocks of a
database .An Entity can be any object,item,place,
concept or activity about which data can be stored
.In a diagramming technique entities are named and
represented by a BOX.
STUDENT
COURSE
GRADE
Attributes:
An Attribute is a properties of the Entity.An
attribute instance is a particular property of an
individual entity instance.An attribute type is
property of an Entity type .For eg; male is an
attribute instance while SEX is an attribute
type.Attributes are depicted as ellipses,labeled
with name of the property.
REG_NO
ADDRESS
STUDENT
NAME
SEMESTER
Name
Address
Phone
Reg_Date
R001
Arti
Dhanbad
NULL
10/02/2002
R002
Vivek
Kolkata
5619944
21/03/1990
R003
Preeti
Kolkata
5619944
05/10/1980
R004
Deepu
Lucknow
213456
05/05/1989
R005
Rani
Delhi
7639129
14/08/1997
RELATIONSHIPS
INSRUCTOR
TEACHES
STUDENT
Types of Relationships
One to One:
One instance of an Entity can relate to only one instance
of related instance.For one Department ,there can be only
one Department Head.One Faculty cannot head more
than one Department.
RAJ
SALES
RAJA
COMPUTER
SIMRAN
FINANCE
DEEPU
MARKETING
RANI
PRODUCTION
DEPARTMENT
ONE
HEADED BY
ONE
CITY
ONE
SALE
ONE
SALESMAN
One to Many
One instance of an Entity can relate more than one
instance of related Entity.For eg; One Salesman can
sell in many cities.
SALESMAN
ONE
SALE
MANY CITY
Kolkata
RAJ
Mumbay
Dhanbad
SIMRAN
Chennai
Ranchi
Orissa
RANI
Delhi
Many to Many
MANY
SALE
MANY CITY
Kolkata
RAJ
Mumbay
Dhanbad
SIMRAN
Chennai
Ranchi
Orissa
RANI
Delhi
Keys
To ensure data integrity (Validation) so that the data in the database is valid and
correct,Keys play important role .The various types of keys are:
Name
Rajan
Deepu
Ajeet
Deepu
Vivek
City
Lucknow
Lucknow
Mujaffarpur
Delhi
Kolkata
Fees
56000
40000
67000
12000
25000
Primary Key
The candidate key which is used to uniquely
identify each row is called Primary Key.Here
StudId is Primary Key ,choosing Fees as a Primary
Key is meaningless as there is no sequence.
Alternate Key
The candidate key which is not chosen as Primary
Key is called Alternate Key.Here, Fees is a
Alternate Key.
Composite Key
When the key that uniquely identifies the rows of table
made up of more than one attribute .
CustId
ProdId
Qty
SaleDate
C122
P002
12
14/08/76
C134
P002
13
14/08/76
C122
P005
12
10/02/75
Foreign Key
When primary key of one table is also available as
an attribute in another table,it is called Foreign Key.
It is used to relate tables.
Referential Integrity:Ensuring that all the values in
Foreign key match with the Primary Key.
PRODUCTS
ProdId(PK)
Description
Qoh
Price
CUSTOMER
CustId
ProdId(FK)
Qty
OrderValue
SQL
It is the language used to access data within
Oracle databases.
Developed by IBM in mid 1970s.
Oracle Corporation introduced the first the
commercially available implementation of
SQL.
Abbreviation
of Structured Query
Language, pronounced as see quell is
made of three sub-languages such as:
SQL *Plus
Creating Table
1 row created.
1 row created.
Alter Table
Data Integrity
Enforcing data integrity ensures the quality of the data in
the database. For example, if an employee is entered
with an employee_id value of 123, the database should
not allow another employee to have an ID with the same
value. If you have an employee_rating column intended
to have values ranging from 1 to 5, the database should
not accept a value of 6. If the table has a dept_id column
that stores the department number for the employee, the
database should allow only values that are valid for the
department numbers in the company.
Two important steps in planning tables are to identify
valid values for a column and to decide how to enforce
the integrity of the data in the column. Data integrity
falls into four categories:
Entity integrity
Domain integrity
Referential integrity
User-defined integrity
There are several ways of enforcing each type of integrity.
Entity:
Domain
DEFAULT definition
FOREIGN KEY constraint
CHECK constraint
NOT NULL
Referential
User-defined
Applying Constraints
They are part of table definition that are used to limit the
values entered into its columns
NOT NULL:Prevents column from accepting NULL values
UNIQUE:Ensures uniqueness of the values in a column
Primary Key:Same as Unique , but only one column
allowed per table
Check:Controls the value of a column(s) being inserted
Default:Assigns a default value for the column(s),at the
time of insertion when no value is given for that column
References:Used to relate two tables,maintains
Referential Integrity
NOT NULL:
This constraint is placed immediately after
the datatype of a column .Any attempts to
put NULL values in that column will be
rejected .Columns without NOT NULL
constraint allow NULL values.
Create table ItemMast
(
ITNO number(4) NOT NULL ,
Name varchar2(20),
QOH number(5)
);
UNIQUE:
This constraint ensures that the values entered into
the column are UNIQUE..
Create table ItemMast(
ITNO number(4) UNIQUE ,
Name varchar2(20),
QOH number(5));
PRIMARY KEY:
CHECK:
DEFAULT:
This is used insert a value in the column when
user is not entering any value for that column.
REFERENCES:
A foreign key is a combination of columns with values with values
based on the primary key values from another table.A foreign key
constraint, also known as Referential Integrity Constraint ,
specifies that the values of the foreign key correspond to actual
values of the primary key in another table .
Create table ItemTran(
ITNO number(4) references ITEMMAST(ITNO),
TranType char(1) check (trantype in(I,R)),
TranDate date,
Qty number(5));
Create table ItemTran(
ITNO number(4),
TranType char(1) check (trantype in(I,R)),
TranDate date,
Qty number(5),
Foreign key(ITNO) references ITEMMAST(ITNO));
Logical Operators:
AND, OR ,NOT
Special Operators:
IN,BETWEEN,LIKE
Examples:
Select * from emp where deptno=20;
Select ename,sal from emp where sal>20;
Select empno,ename from emp where job= MANAGER
Select ename from emp where job=CLERK and
deptno=20;
Select ename from emp where job=CLERK or
job=ANALYST;
Select * from emp where hiredate <= 30-SEP-81;
Select ename from emp where job <> MANAGER
Select ename from emp where enpno in(7369,7521,7839);
Select * from emp where deptno NOT IN (10,20,30);
Select enam,sal from emp where sal between 1000 and 2000
Select ename from emp where hiredate not between 30JUN-81 and 31-DEC-81;
DISTINCT Clause :
DISTINCT clause is used with
select to suppress duplicate
values if any in a column.
SELECT DISTINCT job from
emp;
NULL values:
NULL values are not 0 or a blank.
It represents an unknown or inapplicable value.
It cannot be compared using the relational and /or
logical operators.
The special operator IS is used with the keyword
NULL to locate NULL values
Select ename from emp where deptno IS NULL;
Select ename from emp where deptno IS NOT
NULL;
Select * from emp where sal > 2000 and comm is
NULL;
Order BY contd
List the empno,ename, sal in ascending
order of salary
Select empno, ename, sal from emp order by sal;
Aggregate Functions
Aggregate functions are used to
produce summarized results.
They operate on set of rows. They
return results based on groups .
By default all rows in a table are
treated as one group . The
aggregate functions produce a
single value for an entire group or
table.
COUNT:
It determines the number of rows/ noNULL column values.If * is passed , then
the total number of rows is returned.
List the no. of employees working with the
company:
SELECT COUNT(*) FROM emp;
List no. of jobs available in the emp t able:
SELECT COUNT(DISTINCT job) from
emp;
JOINS
Joins are used to combine
columns from different tables.
The connection between tables is
established through the where
clause.
Types of Joins:Equi Joins,
Cartesian Joins,Outer Joins, Self
Joins.
Syntax
EQUI JOINS:
When two tables are joined together using equality
of values in one or more columns ,they make an
Equi Join.Table prefixes are utilized to prevent
ambiguity and the where clause specifies the
columns being joined.
Example:
List the employee numbers,names , department
numbers and the department name:
SELECT empno,ename,emp.deptno ,dname from
emp , dept
where emp.deptno=dept.deptno
Table Aliases
It can be very tedious to type the table names
repeatedly.Temporary labels(or aliases) can be
used in the FROM clause .These temporary
names are valid only for the current select
statement.Table aliases should also be specified in
the select clause.Table aliases should can be up to
30 character in length , but the shorter they are
better.
The advantage of using table aliases is that it
effectively speeds up the query
SELECT e.empno,e.ename,e.deptno ,d.dname from emp
e, dept d
Where e.deptno=d.deptno
Cartesian Joins
When no join condition clause is specified in
WHERE clause, each row of one table
matches every row of the other table.This
results in a Cartesian product.
SELECT empno, ename, dname, loc from emp,
dept;
If the number of rows are 14 and 4 in emp and
dept tables respectively ,then the total number
of rows produced is 56.
Cartesian product is useful in finding out all the
possible combination of columns from different
tables.
Tab2
YEAR
RATE
10
1000
11
2000
11.5
3000
12
Outer Joins
If there are any values in one table that do not have
corresponding value(s) in the other , in an equi join
that row will not be selected.Such rows can be
forcefully selected by using the outer join symbol(+)
. The corresponding columns for that row will have
NULLs.
Example:Display the list of employees working in
each department .Display the department
information even if no employee belongs to that
department:
SELECT empno, ename, emp.deptno, dname, loc from
emp, dept where emp.deptno(+) = dept.deptno;
Self Join:
To join a table to itself means that each row of the table is
combined with itself and with every other row of the
table.The self join can be viewed as a join of two copies of
the same table .The table is not actually copied , but SQL
performs the command as though it were.
The syntax of the command for joining table to itself as
almost same as that for joining two different tables.To
distinguish the column names from one another , aliases
for the actual table name are used , since both the tables
have the same name .
Example:To list out the names of the manger with the
employee record one will have to join EMP with itself
Select Worker.ename,Manager.ename "Manager"
from emp Worker , emp Manager
where Worker.mgr=Manager.empno;
UNION:
The union clause merges the outputs of two or
more queries into single set of rows and columns.
Syntax:
Select <stmt1>
UNION
Select <stmt2>
[Order BY clause]
Display the different designations in department 20 and 30
INTERSECT
The INTERSECT operator returns the rows that
are common between two sets of rows.
Syntax:
Select <stmt1>
INTERSECT
Select <stmt2>
[Order BY clause]
Display the jobs common to department 20 and 30
MINUS:
The MINUS returns the rows unique to first query.
Syntax:
Select <stmt1>
MINUS
Select <stmt2>
[Order BY clause]
Display the jobs unique to department 20
Select job from emp where deptno=20
MINUS
Select job from emp where deptno=10
MINUS
Select job from emp where deptno=30
NESTED QUERIES
If we want List Employees belonging to department
of MILLER:
We have to use two query statements,first of all we
have to do determine the department number of
MILLER like:
SELECT deptno from emp where ename=MILLER;
Then we will use the the deptno to find out the other
Employees something like:
SELECT ename from emp where deptno=10;
We can combine the above two query statements into
single something like:
SELECT ename from emp where deptno=(SELECT
deptno from emp where ename=MILLER);
THIS IS NESTED QUERY i.e; Query inside another QUERY
Advantages:
Subqueries allows a developers to build powerful
commands out the simple one.
The nested queries is very useful when you need
to select rows from a table with a condition that
depends on the data in the table itself.
DISTINCT clause:
It use to force the query to return single
value.
Select * from dept where deptno=(select
distinct
deptno
from
emp
where
mgr=7698);
Subqueries that return more than one row:
List of employees, who earn lowest salary in
each department:
SELECT ename,sal,deptno from emp where
sal IN(SELECT MIN(sal) from emp group
by deptno);
EXISTS:
List all employees who have at least one person
reporting to them:
SELECT empno,ename,job,deptno from emp e where
EXISTS
(select
empno
from
emp
where
emp.mgr=e.empno);
List the employee detail if any and only if more than 2
employees are present in department number 10:
Select * from emp where deptno= 10 and EXISTS ( select
count(*) from emp where deptno=10 GROUP BY deptno
HAVING COUNT(*) > 2);
List all employees details who do not manage any one:
SELECT ename,job from emp e WHERE NOT EXISTS
(Select mgr from emp where mgr=e.empno);
ANY Operator:It
FUNCTIONS
They are used to manipulate data items.
Advantages:
Perform complex calculations on data
Can modify individual data items
Can very easily manipulate output for group of
rows.
Can alter date format for display
Types:
Single Row Function(Column Function)
Group Function
DUAL TABLE
DUAL table is a table with only one row
and column in it.It is owned by SYS
and can be accessed by all users.It
contains one column, DUMMY and one
row with value X.The DUAL table is
useful to return a value only once-for
instance , the value of a constant ,
psuedo_column or expression that is not
derived from a table with user data.
Desc DUAL;
Character Functions
Working with characters
CHR(x):Returns the character given to character number
Select chr(65) from DUAL;
ASCII(x):Returns the ASCII value of given character
Select ASCII(A) from DUAL;
CONCAT(str1,str2):Returns str1 concatenated with str2.
Select concat(Anu,Rag) from DUAL;
INITCAP(string):Capitalize the first character of each
word in the string.
Select initcap(anurag) from dual;
LOWER(string):Converts string to lower case.
SELECt lower(ANU) from DUAL;
SUBSTR(string,m[,n]):Returns substring, n
characters long from the string specified, starting
at position number m .If n is not specified the
string is extracted from position m to end.
Select
dname
,
SUBSTR(dname,2,4)
,
SUBSTR(dname,4) from dept;
TRANSLATE(string,from_str,to_str):This
returns string with all occurrences of each
character in from_str replaced by corresponding
character in to_str.
select
translate(abcdefghij,abcdef,123456)
from dual;
select translate('abcdefghij','abcdefghij','123456')
from dual;
Date Functions
GENERAL FUNCTIONs
TRANSLATE(char,find,new):This
function
returns
char with each find changed to new.All occurrences
of find are replaced with corresponding character in
new.If corresponding new character is not supplied,then
find char is removed.
Select dname,translate(dname,e,l) from dept;
DECODE(C,V1,S1,V2,S2,,D):This function does a ifthen-else.A default value can also be specified with
DECODE function,which is substituted,in case nothing
matches from the set.C which is either column or
expression is compared to each V and substitutes S if
C equals the search value.If no match is found , the
DECODE function returns the D which is default
value.If default value is omitted ,NULL is returned for
unmatched values.
Select ename , job , DECODE(job,CLERK,EXEC,
MANAGER,RM,job) from emp;
Syntax:
Create SEQUENCE <seq-name> INCREMENT by <n>]
Start with <m>]
MAXVALUE N|NOMAXVALE]
MINVALUE N|NOMINVALUE]
Where:
<seq-name> name of sequence
<n> increment specified by user
Start with number with which the sequence will begin
MINVALUE lower bound
MAXVALUE upper bound
Use in table:
create table checking
(id number(5),name varchar2(10));
insert into checking values( empnumber.NEXTVAL , 'Anu');
insert
into
checking
values( empnumber.NEXTVAL , Dipti');
select * from checking;
Output:
ID NAME
--------- ---------2 Dipti
Altering SEQUENCES:
Alter SEQUENCE <seq-name> INCREMENT by <n>]
MAXVALUE N | NOMAXVALE]
MINVALUE N | NOMINVALUE]
ALTER SEQUENCE empnumber INCREMENT BY 2;
NOTE:This alter sequence command will not affect the
sequence number created earlier.Only future sequence
numbers are affected by the ALTER SEQUENCE
statement.START WITH value cannot be changed using
ALTER .The sequence must be dropped and recreated in
order to restart a sequence at different number.
Removing SEQUENCES:
Drop sequence <seq name>
Drop sequence empnumber;