Sie sind auf Seite 1von 18

Introduction to Database

A database is an organized collection of data. It is the collection of schemas, tables, queries,


reports, views and other objects. The data are typically organized to model aspects of reality in a
way that supports processes requiring information, such as modeling the availability of rooms in
hotels in a way that supports finding a hotel with vacancies.

Database Management System


A database management system (DBMS) is a computer software application that interacts with
the user, other applications, and the database itself to capture and analyze data. A generalpurpose DBMS is designed to allow the definition, creation, querying, update, and administration
of databases. Well-known DBMSs include MySQL, PostgreSQL, Microsoft SQL Server, Oracle,
Sybase, SAP HANA, and IBM DB2. A database is not generally portable across different
DBMSs, but different DBMS can interoperate by using standards such as SQL and ODBC or
JDBC to allow a single application to work with more than one DBMS. Database management
systems are often classified according to the database model that they support; the most popular
database systems since the 1980s have all supported the relational model as represented by the
SQL language. Sometimes a DBMS is loosely referred to as a 'database'.
Databases are used to support internal operations of organizations and to underpin online
interactions with customers and suppliers.
Databases are used to hold administrative information and more specialized data, such as
engineering data or economic models. Examples of database applications include computerized
library systems, flight reservation systems, computerized parts inventory systems, and many
content management systems that store websites as collections of webpages in a database.

Benefits of DBMS

The amount of data redundancy in stored data can be reduced.


No more data inconsistencies.
Stored data can be shared by a single or multiple users
Standards can be set and followed
Data integrity can be maintained
Security of data can be simply implemented
Data independence can be achieved

Introduction to Structured Query language


Structured Query language is a language that provides an interface to relational database system.
SQL was developed by IBM in the 1970s for use in System R and is a de facto standard, as well
as an ISO and ANSI standard. SQL is often pronounced SEQUEL.
In common usage, SQL also encompasses data manipulation language, for INSERTSs,
UPDATEs, DELETEs and DDL used for creating and modifying tables and other database
structure.
The development of SQL is governed by standards. The ANSI is an organization that approves
certain standards in many different industries.
SQL has been a command language for communication with the ORACLE 9i server from any
tool or application. Oracle SQL contains many extension . When an SQL statement is entered it
is stored in a part of memory called the SQL buffer and remains there until a new SQL statement
is entered.

Features of SQL
1. SQL can be used by a range of users, including those with little or no programming
experience.
2. It is a non-procedural language.
3. It reduces the amount of time required for creating and maintaining system
4. It is an English-like language.
Rules for SQL
1. SQL starts with a verb. For example:- SELECT statements. IT can also have additional
adjectives.
2. Each verb is followed by number of clauses. Examples- FROM, WHERE.
3. A space separates clauses.
4. A comma separates parameters without a clause.
5. A ; is used to end SQL statements.
6. Statements may be split across line but keywords may not.
7. Lexical units such as identifiers, operator names, literals are separated by one or more
spaces or other delimiters that will not be confused with the lexical unit.
8. Reserved words cannot be used as identifiers.
9. Identifiers can contain upto 30 characters and must start with an alphabetic character.
10. Characters and date literals must be enclosed within single quotes.

Components of SQL
a) DDL(Data definition language )It is set of SQL commands used to create , modify and delete database structure but not
data. These commands are normally not used by a general user who should be accessing
the database via an application. They are normally used by a DBA to a limited extent, a
database designer or application developer. These statements are immediate i.e. they are
not susceptible to ROLLBACK commands. It should also be noted that if several DML
statements for example updates are executed then issuing any DDL command would
commit all the updates as every DDL command implicitly issues a COMMIT command
to the database.
b) DML(Data Manipulation Language)It is the area of the SQL that allows changing data within the database.
c) DCL( Data Control Language)It is the component of SQL statement that control access to the data and the database.
Occasionally DCL statements are grouped with DML statements.

d) DQL( Data Query Language)It is the component of SQL statement that allows getting data from the database and
imposing ordering upon it. It includes the SELECT statement. This command is the heart
of the SQL. It allows getting the data out of the database perform operations with it.
When a SELECT command is fired against a table or tables the result is compiled into a
further temporary table, which is displayed or perhaps received by the program i.e. frontend.

DDL commands:DDL consists the CREATE, ALTER, DROP, TRUNCATE, COMMENT, GRANT ,
REVOKE commands.

a) The CREATE TABLE commandThe CREATE TABLE command defines each column of table uniquely. Each
column has a minimum of three attributes, a name ,datatype, size. Each table column
definition is a single clause in the create table syntax. Each table column definition is
separated from the other by a comma. Finally, The SQL statement is terminated with
a semi colon.
Rules for Creating Table: A name can have maximum upto 30 characters.
Alphabets from A-Z, a-z and numbers from 0-9 are allowed.
A name should begin with an alphabet.
The use of special character like _ is not allowed and also recommended.
SQL reserved words are not allowed.
Syntax :CREATE TABLE <tableName> (<columnName1><data type>(<size>),
(<columnName1><data type>(<size>));
CREATING a Table from a TABLE:SyntaxCREATE TABLE <new tableName> (<columnName>, <columnName>)
AS SELECT <columnName>,<columnName> FROM <Table name>

b) The ALTER command


The structure of a table can be modified by using the ALTER TABLE command.
ALTER TABLE allows changing the structure of an existing table. With ALTER
TABLE it is possible to add or delete columns, create or destroy indexes , change the
data type of existing columns or rename columns or the table itself.
ALTER TABLE works by making a temporary copy of the original table. The
alteration is performed on the copy, then the original table is deleted and the new one
is renamed. While the ALTER TABLE is executing , the original table is still readable
by the users of the oracle.
i. Adding new columnSyntax:ALTER TABLE <TableName>
ADD(<NewColumnName><Datatype> (<size>),
(<NewColumnName><Datatype> (<size>));
ii.

Dropping a column from the table-

Syntax:ALTER TABLE<tableName> DROP COLUMN <columnName>;


iii.

Modifying Existing ColumnSyntax:ALTER TABLE <TableName>


MODIFY(<ColumnName><NewDatatype>(<NewSize>));

Restriction on the ALTER TABLE


The following tasks cannot be performed when using ALTER TABLE command Change the name of the table
Change the name of the column
Decrease the size of a column if table data exists

c) TRUNCATE TABLE:TRUNCATE TABLE empties a table completely. Logically it is equivalent to a


DELETE statement that delete rows, but there are practical differences under spme
circumstances.
Syntax:TRUNCATE TABLE<TableName>;
Difference between TRUNCATE TABLE and DELETE commands: Truncate operation drop and re-create the table, which is much faster than deleting rows
one by one .
Truncate operation are not transaction-safe
The number of deleted rows are not returned.

d) DROP command:Sometimes tables within a particular database become obsolete and need to be
discarded. In such situation using the DROP TABLE statement with the table name
can destroy a specific table.
Syntax:DROP TABLE <TableName>
DML ( Data Manipulation Language)-

This language consists the INSERT , UPDATE, DELETE, CALL, EXPLAIN PLAN , LOCK
commands.
a) INSERT command- Once a table is created , the most natural thing to do is load this
table with data to be manipulated later.
When insertinga single row of data into the table, the insert operation Creates a new row in the database table
Loads the value passed into the columns specified
Syntax:INSERT INTO <tablename> (<columnName1> ,<columnName2>)
VALUES (<expression>,<expression2>);
Inserting Data Into A Table From Another Table:Syntax:INSERT INTO <TableName>
SELECT <ColumnName1>,<CoumnNameN> FROM <TableName>;
Insertion Of A Data Set Into A Table From Another Table:Syntax:INSERT INTO <TableName>SELECT <ColumnName1>,<CoumnNameN>
FROM <TableName> WHERE <Condition>;
b) UPDATE command:Update command is used to update a row of a table.
Syntax:UPDATEtable-name set column-name = value wherecondition;

c) DELETE command
Delete command is used to delete data from a table. Delete command can also be used
with condition to delete a particular row.
Syntax:-

DELETE from Table-name


Data Control Language(DCL)
Data Control Language(DCL) commands are used to manage transactions in database.These are
used to manage the changes made by DML statements. It also allows statements to be grouped
together into logical transactions.
a) COMMIT command
Commit command is used to permanently save any transaction into database.
Syntax:commit;
b) ROLLBACK command
This command restores the database to last commited state. It is also use with savepoint
command to jump to a savepoint in a transaction.
Syntax:Rollback to savepoint name;
c) SAVEPOINT command
savepoint command is used to temporarily save a transaction so that you can rollback to
that point whenever necessary.
Syntax:savepointsavepointname;

d) GRANT command:The GRANT statement provides various type of access to database objects such as
tables, views, sequences and so on.
SyntaxGRANT <Object Privileges>
ON <ObjectName>
TO <UserName>
[WITH GRANT OPTION];

Object Privileges:-Each object privilege that is granted authorizes the grantee to


perform some operation on the object. A user can grant all the privileges or grant only
specific object privileges.
WITH GRANT OPTION:The WITH GRANT OPTION allows the grantee to in turn grant object privileges to
other users.
e) REVOKE command:Privileges once given can be denied using to a user using the revoke command. The
object owner can revoke privileges granted to another user. A user who is not the
owner , but has been granted the GRANT privilege, has the power to REVOKE the
privileges from a grantee.
Syntax:REVOKE <Object Privileges>
ON <ObjectName>
FROM <UserName>;

DQL(Data Query Language):This language consists the SELECT command.


a) SELECT command
Select query is used to retrieve data from a tables. It is the most used SQL query. We can
retrieve complete tables, or partial by mentioning conditions using WHERE clause.
Syntax:SELECT column-name1, column-name2, column-name3, column-nameN from table-name;

Select all records from the table


A special character asterisk * is used to address all the data(belonging to all columns) in a
query. SELECTstatement uses * character to retrieve all records from a table.

Syntax :SELECT * from table-name;

Select the records based on condition:Syntax:SELECT * FROM table-name WHERE condition;

Data Constraints:There are two types of data constraints. One type of constraint is called an I/O constraint and
another type is called business rule constraint.
I/O constraint:1) Primary Key Constraint: Primary key is column or a set of columns that uniquely identifies a row. Its main
purpose is to record uniqueness.
Primary key will not allow duplicate values.
It will also not allow null values.
Only one primary key is allowed per table.
Primary key constraint defined at Column Level:Syntax:<columnName> <datatype>(<Size>) PRIMARY KEY
Primary key constraint defined at Table Level:Syntax:PRIMARY KEY (<ColumnName>, <ColumnName>)

2) Foreign Key Constraint: Foreign key is a column or set of columns that references the column or set of
columns of a table and it can be same table also.
Parent that is being referenced has to be unique or primary key.

Foreign key constraint defined at Column Level:Syntax:<columnName> <datatype>(<Size>) REFERENCES <TableName> [(<ColumnName>)]
Foreign key constraint defined at Table Level:Syntax:FOREIGN KEY (<ColumnName>, [<ColumnName>])
REFERENCES <TableName> [(<ColumnName>, <columnName>)]
3) Unique Key Constraint: Unique key will not allow duplicate values.
Unique index is created automatically.
A table can have more than one unique key which is not possible in primary key.
Unique key constraint defined at Column Level:Syntax:<columnName> <datatype>(<Size>) UNIQUE
Foreign key constraint defined at Table Level:Syntax:CREATE TABLE TableName (<ColumnName1> <datatype>(<Size>), <ColumnName2>
<datatype>(<Size>), UNIQUE (<ColumnName1>, < ColumnName2>));

Business Rule Constraint


1) The check Constraint:Business rule validations can be applied to a table column by using this constraint.

It must be specified as a logical expression that evaluates either to True or False.


Check constraint defined at Column Level:Syntax:<columnName> <datatype>(<Size>) CHECK (<Logical Expression>)
Check constraint defined at Table Level:Syntax:CHECK(<Logical Expression>)

GROUP BY Clause:The GROUP BY clause is another section of the select statement. This optional clause tells
Oracle to group rows based on distinct values that exist for specified columns. The GROUP BY
clause creates a data set, containing set of records grouped together based on condition.
Syntax:SELECT <columnName> , < columnnName2>, <columnNameN>,
AGGREGATE_FUNCTION (<Expression>)
FROM TableName WHERE <condition>
GROUP BY <columnName> , < columnnName2>, <columnNameN>;
Having Clause:The Having Clause can be used in conjuction with GROUP BY clause. Having imposes a
condition on the GROUP BY clause, which further filters the group created by the GROUP BY
clause.
Syntax:SELECT <columnName> , < columnnName2>, <columnNameN>,
AGGREGATE_FUNCTION (<Expression>)
FROM TableName WHERE <condition>
GROUP BY <columnName> , < colimnnName2>, <columnNameN>HAVING <condition>

INDEXES
Indexing a table is an access strategy or we can say a way to sort and search records in a table.

Indexes are essential to improve the speed with which records can be located and retrived from a
table.
Creation of An Index:An Index can be created on one or more columns. Based on this, this is of two type:

Simple Index
Composite Index

Creating Simple Index:An Index created on a single column of a table is called a Simple Index.
Syntax:CREATE INDEX <Index name> ON <TableName> (<ColumnName>);
Creating Composite Index:An index created on more than one column is called a Composite Index.
Syntax:CREATE INDEX <IndexName> ON <TableName> (<ColumnName1>, <ColumnName2>);

VIEWS
When a table is created and populated with data, it may become necessary to prevent all the users
from accessing all columns of a data for data security reasons.
The reasons why views are created:

When data security is required


When data redundancy is kept to be minimum while mainitaining data security

Creating View:Syntax:CREATE VIEW <ViewName>AS


SELECT <columnName1>, <columnName2> FROM <TableName>
WHERE <columnName>=<Expression List>;
GROUP BY <Grouping Criteria> HAVING <predicate>
IF a view is used to only look at table data and nothing else, the view is called a Read-Only
View. A view that is used to look at table data as well as Insert, Update, Delete table data is
called an Updateable View.

For a view to be updateable , it should meet the following criteria: Views defined from single table
If the user wants to INSERT records with the help of a view, then the Primary Key column
and all the NOT NULL columns must be included in the view.

Destroying A View:The drop view command is used to remove a view from the database.
Syntax:DROP VIEW <ViewName>;

declare
num number;
i number:=1;
c number:=0;
begin
num:=&num;
for i in 1..num
loop
if((mod(num,i))=0)
then
c:=c+1;
end if;
end loop;
if(c>2)
then
dbms_output.put_line(num||' not a prime');
else
dbms_output.put_line(num||' is prime');
end if;
end;
/
declare
Grd student.grade%type;
begin

select grade into Grd from student


where sno=100;
dbms_output.put_line('Grade:');
case Grd
when 'A' then Dbms_output.Put_line('Very Good');
when 'B' then Dbms_output.Put_line('Good');
when 'C' then Dbms_output.Put_line('Avrage');
else
Dbms_output.Put_line('Fail');
end case;
end;
/
Aim: To Write a pl/sql program to print mark list using cursors.
Procedure:
Creating table:
SQL>create table Student(
sno number(4),
sname varchar(10),
m1 numbar(3),
m2 numbar(3),
m3 numbar(3));
table created.
SQL>insert into student values
1 row inserted.
SQL>insert into student values
1 row inserted.
SQL>insert into student values
1 row inserted.
SQL>insert into student values
1 row inserted.

(500,wasim,70,75,89);
(500,siva,75,69,88);
(500,vani,84,75,75);
(500,naga,67,50,33);

Source code:
declare
stu student%rowtype;
total number(4);
result varchar(4);
cursor c is select * From student;
begin
for stu in c
loop

Dbms_output.put_line('STUDENT MARKLIST');
Dbms_output.put_line('----------------------------');
Dbms_output.put_line('sno:'||stu.sno||' sname:'||stu.sname);
total:=stu.m1+stu.m2+stu.m3;
if stu.M1>35 and stu.M2>35 and stu.M3>35
then
result:='pass';
else
result:='fail';
end if;
Dbms_output.put_line('m1:'||stu.M1||' m2:'||stu.M2||' m3:'||stu.M3);
Dbms_output.put_line('total:'||total||' result:'||result);
end loop;
end;

/
DECLARE
counter NUMBER;
k NUMBER;
BEGIN
FOR n IN 1..50 LOOP
counter := 0;
k := floor(n/2);
FOR i IN 2..k LOOP
IF (mod(n, i) = 0 ) THEN
counter := 1;
END IF;
END LOOP;
IF (counter = 0) THEN
DBMS_OUTPUT.PUT_LINE(n||' is prime number');
END IF;
END LOOP;
END;

PL/SQL Programs:1. Find the Reverse of a number .


Solution:declare
num1 number(5);
num2 number(5);
rev number(5);
begin
num1:=:num1;
rev:=0;
while num1>0
loop
num2:=num1 mod 10;
rev:=num2+(rev*10);
num1:=floor(num1/10);
end loop;
dbms_output.put_line('Reverse number is: '||rev);
end;

2. To increase the salary of a given employee by 10 % if that is less than 50000

INSERT ALL
INTO emp VALUES(1, 'ram', 78645)
INTO emp VALUES(2, 'ram', 45645)
INTO emp VALUES(3, 'ram', 48695)
SELECT * FROM dual;
DECLARE
eno emp.emp_no%TYPE;
sal emp.salary%TYPE;
s number;
BEGIN
eno:=:emp_no;
SELECT salary INTO sal FROM emp where emp_no=eno;
if sal < 50000 then
UPDATE emp set salary=salary+(salary*0.10) where emp_no=eno;
end if;
end;

Das könnte Ihnen auch gefallen