0% found this document useful (0 votes)
23 views57 pages

Dbms Manual

The document outlines experiments related to designing and implementing Entity-Relationship (ER) and Extended Entity-Relationship (EER) models, including mapping these models to relational schemas. It explains the components of ER diagrams, such as entities, relationships, and attributes, and provides DDL commands for creating and modifying database structures. Additionally, it covers integrity constraints like primary and unique keys during table creation.

Uploaded by

harshy1916
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views57 pages

Dbms Manual

The document outlines experiments related to designing and implementing Entity-Relationship (ER) and Extended Entity-Relationship (EER) models, including mapping these models to relational schemas. It explains the components of ER diagrams, such as entities, relationships, and attributes, and provides DDL commands for creating and modifying database structures. Additionally, it covers integrity constraints like primary and unique keys during table creation.

Uploaded by

harshy1916
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Computer Engg.

/ SSJCET, Asangaon

EXPERIMENT NO: 1

AIM: Design An Entity-Relationship (ER) / Extended Entity-Relationship (EER)


Model.
THEORY:
An Entity Relationship (ER) Diagram is a type of flowchart that illustrates how
“entities” such as people, objects or concepts relate to each other within a system.
ER Diagrams are most often used to design or debug relational databases in the
fields of software engineering, business information systems, education and
research. Also known as ERDs or ER Models, they use a defined set of symbols
such as rectangles, diamonds, ovals and connecting lines to depict the
interconnectedness of entities, relationships and their attributes.

The components and features of an ER diagram

ER Diagrams are composed of entities, relationships and attributes.

Entity

A definable thing—such as a person, object, concept or event—that can have data


stored about it. Think of entities as nouns. Examples: a customer, student, car or
product. Typically shown as a rectangle.

Entity type: A group of definable things, such as students or athletes, whereas the
entity would be the specific student or athlete. Other examples: customers, cars or
products.

Entity set: Same as an entity type, but defined at a particular point in time, such as
students enrolled in a class on the first day. Other examples: Customers who

DISL /CSL 503/ Sem- V Page1


Computer Engg. / SSJCET, Asangaon

purchased last month, cars currently registered in Florida. A related term is


instance, in which the specific person or car would be an instance of the entity set.

Entity categories: Entities are categorized as strong, weak or associative. A


strong entity can be defined solely by its own attributes, while a weak entity
cannot. An associative entity associates entities (or elements) within an entity set.

Entity keys: Refers to an attribute that uniquely defines an entity in an entity set.
Entity keys can be super, candidate or primary. Super key: A set of attributes (one
or more) that together define an entity in an entity set. Candidate key: A minimal
super key, meaning it has the least possible number of attributes to still be a super
key. An entity set may have more than one candidate key. Primary key: A
candidate key chosen by the database designer to uniquely identify the entity set.
Foreign key: Identifies the relationship between entities.

Relationship

How entities act upon each other or are associated with each other. Think of
relationships as verbs. For example, the named student might register for a course.
The two entities would be the student and the course, and the relationship depicted
is the act of enrolling, connecting the two entities in that way. Relationships are
typically shown as diamonds or labels directly on the connecting lines.

DISL /CSL 503/ Sem- V Page2


Computer Engg. / SSJCET, Asangaon

Recursive relationship: The same entity participates more than once in the
relationship.

Attribute

A property or characteristic of an entity. Often shown as an oval or circle.

Descriptive attribute: A property or characteristic of a relationship (versus of an


entity.)

Attribute categories: Attributes are categorized as simple, composite, derived, as


well as single-value or multi-value. Simple: Means the attribute value is atomic
and can’t be further divided, such as a phone number. Composite: Sub-attributes
spring from an attribute. Derived: Attributed is calculated or otherwise derived
from another attribute, such as age from a birthdate.

Multi-value: More than one attribute value is denoted, such as multiple phone
numbers for a person.

DISL /CSL 503/ Sem- V Page3


Computer Engg. / SSJCET, Asangaon

Single-value: Just one attribute value. The types can be combined, such as: simple
single-value attributes or composite multi-value attributes.

Cardinality

Defines the numerical attributes of the relationship between two entities or entity
sets. The three main cardinal relationships are one-to-one, one-to-many, and many-
many. A one-to-one example would be one student associated with one mailing
address. A one-to-many example (or many-to-one, depending on the
relationship direction): One student registers for multiple courses, but all those
courses have a single line back to that one student. Many-to-many example:
Students as a group are associated with multiple faculty members, and faculty
members in turn are associated with multiple students.

Cardinality views: Cardinality can be shown as look-across or same-side,


depending on where the symbols are shown.

Cardinality constraints: The minimum or maximum numbers that apply to a


relationship.

CONCLUSION: Thus we have studied and design An Entity-Relationship (ER) /


Extended Entity-Relationship (EER) Model.

DISL /CSL 503/ Sem- V Page4


Computer Engg. / SSJCET, Asangaon

EXPERIMENT NO: 2

AIM: Mapping ER/EER to Relational schema model.

THEORY:

ER Model, when conceptualized into diagrams, gives a good overview of entity-


relationship, which is easier to understand. ER diagrams can be mapped to
relational schema, that is, it is possible to create relational schema using ER
diagram. We cannot import all the ER constraints into relational model, but an
approximate schema can be generated.

There are several processes and algorithms available to convert ER Diagrams into
Relational Schema. Some of them are automated and some of them are manual.
We may focus here on the mapping diagram contents to relational basics.

ER diagrams mainly comprise of −

 Entity and its attributes


 Relationship, which is association among entities.

What are the ER diagrams?

ER diagram is a visual representation of data based on the ER model, and it


describes how entities are related to each other in the database.

What are EER diagrams?

EER diagram is a visual representation of data, based on the EER model that is an
extension of the original entity-relationship (ER) model.

DISL /CSL 503/ Sem- V Page5


Computer Engg. / SSJCET, Asangaon

Mapping Entity

An entity is a real-world object with some attributes.

Mapping Process (Algorithm)


 Create table for each entity.
 Entity's attributes should become fields of tables with their respective data
types.
 Declare primary key.

Mapping Relationship

A relationship is an association among entities.

Mapping Process

DISL /CSL 503/ Sem- V Page6


Computer Engg. / SSJCET, Asangaon

 Create table for a relationship.


 Add the primary keys of all participating Entities as fields of table with their
respective data types.
 If relationship has any attribute, add each attribute as field of table.
 Declare a primary key composing all the primary keys of participating
entities.
 Declare all foreign key constraints.

Mapping Weak Entity Sets

A weak entity set is one which does not have any primary key associated with it.

Mapping Process
 Create table for weak entity set.
 Add all its attributes to table as field.
 Add the primary key of identifying entity set.
 Declare all foreign key constraints.

Mapping Hierarchical Entities

ER specialization or generalization comes in the form of hierarchical entity sets.

DISL /CSL 503/ Sem- V Page7


Computer Engg. / SSJCET, Asangaon

Mapping Process
 Create tables for all higher-level entities.
 Create tables for lower-level entities.
 Add primary keys of higher-level entities in the table of lower-level entities.
 In lower-level tables, add all other attributes of lower-level entities.
 Declare primary key of higher-level table and the primary key for lower-
level table.
 Declare foreign key constraints.

The database can be represented using the notations, and these notations can
be reduced to a collection of tables.

In the database, every entity set or relationship set can be represented in


tabular form.

The ER diagram is given below:

DISL /CSL 503/ Sem- V Page8


Computer Engg. / SSJCET, Asangaon

o Entity type becomes a table.

In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms


individual tables.

o All single-valued attribute becomes a column for the table.

In the STUDENT entity, STUDENT_NAME and STUDENT_ID form the column


of STUDENT table. Similarly, COURSE_NAME and COURSE_ID form the
column of COURSE table and so on.

o A key attribute of the entity type represented by the primary key.

In the given ER diagram, COURSE_ID, STUDENT_ID, SUBJECT_ID, and


LECTURE_ID are the key attribute of the entity.
DISL /CSL 503/ Sem- V Page9
Computer Engg. / SSJCET, Asangaon

o The multivalued attribute is represented by a separate table.

In the student table, a hobby is a multivalued attribute. So it is not possible to


represent multiple values in a single column of STUDENT table. Hence we create
a table STUD_HOBBY with column name STUDENT_ID and HOBBY. Using
both the column, we create a composite key.

o Composite attribute represented by components.

In the given ER diagram, student address is a composite attribute. It contains


CITY, PIN, DOOR#, STREET, and STATE. In the STUDENT table, these
attributes can merge as an individual column.

o Derived attributes are not considered in the table.

In the STUDENT table, Age is the derived attribute. It can be calculated at any
point of time by calculating the difference between current date and Date of Birth.

Using these rules, you can convert the ER diagram to tables and columns and
assign the mapping between the tables. Table structure for the given ER diagram is
as below:

Figure: Table structure

DISL /CSL 503/ Sem- V Page10


Computer Engg. / SSJCET, Asangaon

CONCLUSION: Thus we have studied mapping of ER/EER model to relational


model.

DISL /CSL 503/ Sem- V Page11


Computer Engg. / SSJCET, Asangaon

EXPERIMENT NO: 3

AIM: A) Create Database Using Data Definition Language (DDL) commands.


B) Apply integrity constraints for the specified System.
THEORY:
Data Definition Language(DDL) : DDL is data definition language which is used
to define a structure of database or records in database.The DDL consist fo
following commands given as bellows -
DDL Commands are:
1) CREATE
2) ALTER
3) RENAME
4) DROP
5) TRUNCATE

1) CREATE: The create command is used to create a table in database .The syntax
of Create command is given as bellows-
Syntax > create table table_name(column_name datatype(size),column_name2
datatype(size),column_name n……);
2) ALTER: The alter command is to add a column to table after the table creation
is done. OR to Modify the records of a table.The syntax of alter command is given
as bellows -
Syntax > alter table table_name add (column_name datatype(size));
Syntax > alter table table_name modify(column_name datatype(size));
3) RENAME: The Rename is used to change the name of table.
Syntax of rename command is given as bellows -
Syntax > rename oldtable_name to newtable_name;

DISL /CSL 503/ Sem- V Page12


Computer Engg. / SSJCET, Asangaon

4) DROP: The drop command is simply delete the whole table from the
database.The syntax is given as bellows -
Syntax > drop table tablename;

CAMMANDS:
CREATE TABLE
Q1. Write a query to create a table employee with empno, ename, designation, and
salary.
SQL>CREATE TABLE EMP (EMPNO NUMBER (4),ENAME VARCHAR2
(10),DESIGNATIN
VARCHAR2(10),SALARY NUMBER (8,2));
Table created.
SQL> DESC EMP;
Name Null Type
----------------------------------------- -------- -------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

Q2. Write a query for create a from an existing table with all the fields
SQL> CREATE TABLE EMP1 AS SELECT * FROM EMP;
Table created.
SQL> DESC EMP1
Name Null? Type

DISL /CSL 503/ Sem- V Page13


Computer Engg. / SSJCET, Asangaon

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

EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

Q3. Write a query for create a from an existing table with selected fields
SQL> CREATE TABLE EMP2 AS SELECT EMPNO, ENAME FROM EMP;
Table created.
SQL> DESC EMP2
Name Null? Type
----------------------------------------- -------- ----------------------
EMPNO NUMBER (4)
ENAME VARCHAR2 (10)

Q4. Write a query for create a new table from an existing table without any record:
SQL> CREATE TABLE EMP3 AS SELECT * FROM EMP WHERE 1>2;
Table created. SQL> DESC EMP3;
Name Null? Type
----------------------------------------- -------- -----------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2);

DISL /CSL 503/ Sem- V Page14


Computer Engg. / SSJCET, Asangaon

ALTER & MODIFICATION ON TABLE


Q5. Write a Query to Alter the column EMPNO NUMBER (4) TO EMPNO
NUMBER (6).
SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER (6);
Table altered.
SQL> DESC EMP;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(6)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

Q6. Write a Query to Alter the table employee with multiple columns (EMPNO,
ENAME.)
SQL>ALTER TABLE EMP MODIFY (EMPNO NUMBER (7), ENAME
VARCHAR2(12));
Table altered.
SQL> DESC EMP;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2);

DISL /CSL 503/ Sem- V Page15


Computer Engg. / SSJCET, Asangaon

Q7. Write a query to add a new column in to employee


SQL> ALTER TABLE EMP ADD QUALIFICATION VARCHAR2(6);
Table altered. SQL> DESC EMP;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)

Q8. Write a query to add multiple columns in to employee


SQL>ALTER TABLE EMP ADD (DOB DATE, DOJ DATE);
Table altered. SQL> DESC EMP;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)
DOB DATE

DISL /CSL 503/ Sem- V Page16


Computer Engg. / SSJCET, Asangaon

REMOVE / DROP
Q9. Write a query to drop a column from an existing table employee
SQL> ALTER TABLE EMP DROP COLUMN DOJ;
Table altered.
SQL> DESC EMP;
Name Null? Type
----------------------------------------- -------- -------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)
DOB DATE

Q10. Write a query to drop multiple columns from employee


SQL> ALTER TABLE EMP DROP (DOB, QUALIFICATION);
Table altered.
SQL> DESC EMP;
Name Null? Type
----------------------------------------- -------- --------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
DISL /CSL 503/ Sem- V Page17
Computer Engg. / SSJCET, Asangaon

REMOVE
Q11. Write a query to rename table emp to employee
SQL> ALTER TABLE EMP RENAME EMP TO EMPLOYEE; SQL> DESC
EMPLOYEE;
Name Null? Type
----------------------------------------- -------- --------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

B) Apply integrity constraints for the specified System.


KEYS:
1) PRIMARY KEY: The primary key is the key used to find any record by using it
and the value of primary key never null.
At The Time of Table Creation:
Syntax > create table table_name(column_name datatype(size) primary key,
column_name datatype(size));

2) UNIQUE KEY: It used to prevent duplication of values within the rows of a


specified column or set of columns in the table.
At The Time Of Table Creation :
Syntax > create table table_name (column_name datatype(size) constraint
constraint_name unique);

DISL /CSL 503/ Sem- V Page18


Computer Engg. / SSJCET, Asangaon

After Table Creation :


Syntax > alter table table_name add constraint constraint_name
unique(column_name); 3) FOREIGN KEY : The foreign key represents relation
between two tables. A foreign key is column whose values are derived from the
‘primary key’ of another table.
At The Time Of Table Creation :
Syntax > create table table_name(column_name datatype(size) constraint
constraint_name references table_name (column_name));

4) NOT NULL : While inserting data in table The Not Null constraint is chek that
any field not remain empty OR Null values in table not allowed.
Syntax > create table table_name (column_name datatype(size) constraint
constraint_name unique not null);

5) DEFAULT : The Default constraint is used to set a default value in table where
the Null record is founded it get filled with that given value.
Syntax > create table table_name (column_name datatype(size) default‘value to be
set’);

6) CHECK : The Check constraints is check the condition given


While creating the table.
Syntax> create table table_name(column_name datatype(size)check
(condition));
COMMANDS:

Primary key
SQL>CREATE TABLE EMPLOYEE(EMPNO NUMBER(4) PRIMARY
KEY,ENAME VARCHAR2(10), JOB VARCHAR2(6), SAL NUMBER(5), DEPTNO
NUMBER(7));

DISL /CSL 503/ Sem- V Page19


Computer Engg. / SSJCET, Asangaon

Column level constraints Using Primary key with naming convention

Q. Write a query to create primary constraints with column level with naming
convention
SQL>CREATE TABLE EMPLOYEE(EMPNO NUMBER(4)CONSTRAINT
EMP_EMPNO_PK PRIMARY KEY,ENAME VARCHAR2(10), JOB
VARCHAR2(6),SAL NUMBER(5), DEPTNO NUMBER(7));

Table Level Primary Key Constraints


Q. Write a query to create primary constraints with table level with naming
convention
SQL>CREATE TABLE EMPLOYEE (EMPNO NUMBER(6),ENAME
VARCHAR2(20), JOB VARCHAR2(6), SAL NUMBER(7), DEPTNO
NUMBER(5),CONSTRAINT EMP_EMPNO_PK PRIMARY KEY(EMPNO));

Table level constraint with alter command (primary key):


Q. Write a query to create primary constraints with alter command
SQL>CREATE TABLE EMPLOYEE(EMPNO NUMBER(5),ENAME
VARCHAR2(6), JOB VARCHAR2(6), SAL NUMBER(6),DEPTNO NUMBER(6));

SQL>ALTER TABLE EMP3 ADD CONSTRAINT EMP3_EMPNO_PK PRIMARY


KEY (EMPNO);

Reference /foreign key constraint

Column level foreign key constraint:


Q. Write a query to create foreign key constraints with column level
Parent Table:
SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARY KEY,DNAME
VARCHAR2(20), LOCATION VARCHAR2(15));

Child Table:
SQL>CREATE TABLE EMP4 (EMPNO NUMBER(3),DEPTNO NUMBER(2)
REFERENCES DEPT(DEPTNO),DESIGN VARCHAR2(10));

Column level foreign key constraint with naming conversions:


Q. Write a query to create foreign key constraints with column level
Parent Table:
SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARY KEY,DNAME
VARCHAR2(20), LOCATION VARCHAR2(15));

DISL /CSL 503/ Sem- V Page20


Computer Engg. / SSJCET, Asangaon

Child Table:
SQL>CREATE TABLE EMP4A (EMPNO NUMBER(3),DEPTNO NUMBER(2)
CONSTRAINT EMP4A_DEPTNO_FK REFERENCES DEPT(DEPTNO),DESIGN
VARCHAR2(10));

Table Level Foreign Key Constraints


Q. Write a query to create foreign key constraints with Table level
Parent Table:
SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARY KEY, DNAME
VARCHAR2(20), LOCATION VARCHAR2(15));

Child Table:
SQL>CREATE TABLE EMP5 (EMPNO NUMBER(3), DEPTNO NUMBER(2),
DESIGN VARCHAR2(10)CONSTRAINT ENP2_DEPTNO_FK FOREIGN
KEY(DEPT NO) REFERENCESDEPT(DEPTNO));

Table Level Foreign Key Constraints with Alter command

Q. Write a query to create foreign key constraints with Table level with alter
command.
Parent Table:
SQL>CREATE TABLE DEPT(DEPTNO NUMBER(2) PRIMARY KEY, DNAME
VARCHAR2(20), LOCATION VARCHAR2(15));

SQL>CREATE TABLE EMP5 (EMPNO NUMBER(3), DEPTNO


NUMBER(2),DESIGN VARCHAR2(10));

Child Table:
SQL>ALTER TABLE EMP6 ADD CONSTRAINT EMP6_DEPTNO_FK FOREIGN
KEY(DEPTNO) REFERENCES DEPT(DEPTNO);

Check constraint
Column Level Check Constraint
Q. Write a query to create Check constraints with column level
Syntax for clumn level constraints using Check:
SQL>CREATE TABLE EMP7(EMPNO NUMBER(3), ENAME
VARCHAR2(20),DESIGN VARCHAR2(15), SAL NUMBER(5)CONSTRAINT
EMP7_SAL_CK CHECK(SAL>500 AND SAL<10001),DEPTNO NUMBER(2));

DISL /CSL 503/ Sem- V Page21


Computer Engg. / SSJCET, Asangaon

Table Level Check Constraint:


Q. Write a query to create Check constraints with table level
SQL>CREATE TABLE EMP8(EMPNO NUMBER(3), ENAME
VARCHAR2(20),DESIGN VARCHAR2(15), SAL NUMBER(5),DEPTNO
NUMBER(2), CONSTRAINTS EMP8_SAL_CK CHECK(SAL>500 AND
SAL<10001));

Check Constraint with Alter Command


Q. Write a query to create Check constraints with table level using alter command.
SQL>CREATE TABLE EMP9(EMPNO NUMBER, ENAME
VARCHAR2(20),DESIGN
VARCHAR2(15), SAL NUMBER(5));
SQL>ALTER TABLE EMP9 ADD CONSTRAINTS EMP9_SAL_CK
CHECK(SAL>500 AND
SAL<10001);

Column Level Constraint

Unique Constraint
Q. Write a query to create unique constraints with column level
SQL>CREATE TABLE EMP10(EMPNO NUMBER(3), ENAME
VARCHAR2(20),DESGIN VARCHAR2(15)CONSTRAINT EMP10_DESIGN_UK
UNIQUE, SAL NUMBER(5));

Table Level Constraint


Q. Write a query to create unique constraints with table level
SQL>CREATE TABLE EMP11(EMPNO NUMBER(3), ENAME VARCHAR2(20),
DESIGN VARCHAR2(15),SAL NUMBER(5),CONSTRAINT EMP11_DESIGN_UK
UNIGUE(DESIGN));

Table Level Constraint Alter Command


Q. Write a query to create unique constraints with table level
SQL>CREATE TABLE EMP12(EMPNO NUMBER(3), ENAME VARCHAR2(20),
DESIGN VARCHAR2(15), SAL NUMBER(5));
SQL>ALTER TABLE EMP12 ADD CONSTRAINT EMP12_DESIGN_UK
UNIQUE(DESING);

Not Null
Column Level Constraint
Q. Write a query to create Not Null constraints with column level

DISL /CSL 503/ Sem- V Page22


Computer Engg. / SSJCET, Asangaon

SQL>CREATE TABLE EMP13 (EMPNO NUMBER(4),ENAME VARCHAR2(20)


CONSTRAINT EMP13_ENAME_NN NOT NULL, DESIGN VARCHAR2(20),SAL
NUMBER(3));

Null
Q. Write a query to create Null constraints with column level
SQL>CREATE TABLE EMP13 (EMPNO NUMBER(4),ENAME VARCHAR2(20)
CONSTRAINT EMP13_ENAME_NN NULL, DESIGN VARCHAR2(20),SAL
NUMBER(3));

Constraint Disable

Constraint Disable \ Enable


Q. Write a query to disable the constraints
Syntax for disabling a single constraint in a table:
SQL>ALTER TABLE <TABLE-NAME> DISABLE CONSTRAINT
<CONSTRAINT- NAME>
Constraint Enable
SQL>ALTER TABLE EMP13 DISABLE CONSTRAINT EMP13_ENAME_NN
NULL;

Q. Write a query to enable the constraints


Syntax for disabling a single constraint in a table:
SQL>ALTER TABLE <TABLE-NAME> DISABLE CONSTRAINT
<CONSTRAINT- NAME>
SQL>ALTER TABLE EMP13 ENABLE CONSTRAINT EMP13_ENAME_NN
NULL;

CONCLUSION: Thus we have performed DDL commands and applied


constraints on it.

DISL /CSL 503/ Sem- V Page23


Computer Engg. / SSJCET, Asangaon

EXPERIMENT NO: 4

AIM: Perform DML Commands for the specified system


THEORY:
Data Manipulation Language (DML): The DML commands are the SQL
commands used to
Retrieve the data and manipulate the data in database.
DML Commands are:
1) INSERT
2) SELECT
3) UPDATE
4) DELETE

1) INSERT: The insert command is used to insert a record i.e. data into a table of
database.
Syntax > insert into table_name values(6,'swanand',1236);
2) SELECT:This command simply display the table records or data.
Syntax > select*from table_name;
3) UPDATE: This simply updates the database table data.
Syntax > update table_name set condition ;
4) DELETE: This command delete’s all or specified condition record’s from
database.
Syntax > delete from table_name where condition ;
5) TRUNCATE: The Truncate is used to delete all the records of the table but
structure remains as it is.

DISL /CSL 503/ Sem- V Page24


Computer Engg. / SSJCET, Asangaon

Syntax> truncate table stud;

COMMANDS:
INSERT
Q. Write a query to insert the records in to employee.
SQL>INSERT INTO EMP VALUES(101,'NAGARAJAN','LECTURER',15000);
1 row created.

SELECT
Q. Write a query to display the records from employee.
SQL> SELECT * FROM EMP;
EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 15000

UPDATE
Q. Write a query to update the records from employee.
SQL> UPDATE EMP SET SALARY=16000 WHERE EMPNO=101;
1 row updated.
SQL> SELECT * FROM EMP;
EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN LECTURER 15000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD, PROF 45000

UPDATE MULTIPLE COLUMNS


Q. Write a query to update multiple records from employee.
SQL>UPDATE EMP SET SALARY = 16000, DESIGNATIN='ASST. PROF'
WHERE EMPNO=102;
1 row updated.
SQL> SELECT * FROM EMP;
EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN ASST. PROF 16000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD, PROF 45000

DISL /CSL 503/ Sem- V Page25


Computer Engg. / SSJCET, Asangaon

DELETE
Q. Write a query to delete records from employee.
SQL> DELETE EMP WHERE EMPNO=103;
1 row deleted.
SQL> SELECT * FROM EMP;
EMPNO ENAME DESIGNATINSALARY
---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN ASST. PROF 16000

CONCLUSION: Thus we have performed DML commands

DISL /CSL 503/ Sem- V Page26


Computer Engg. / SSJCET, Asangaon

EXPERIMENT NO: 5

AIM: Perform DCL and TCL commands.


THEORY:
Data Control Language (DCL): The DCL commands are used to enforce the
database security in a multiple user database environment. DCL command are
given as bellows-
DCL Commands are:
1) GRANT
2) REVOKE
3) COMMIT
4) ROLLBACK
5) SAVEPOINT

1) GRANT: SQL Grant is a command used to provide access or privileges on the


database objects to the users.
Syntax > create user user_name identified by password;
Syntax > grant role_name to user_name;
Syntax > grant privileges_name on table_name to username;
2) REVOKE: The revoke command removes user right’s or privileges to the
database objects.
Syntax > revoke Command_name on table_name from user_name;
3) COMMIT: The commit command is make durable all changes done to data( it
simply like save option).
Syntax > commit;

DISL /CSL 503/ Sem- V Page27


Computer Engg. / SSJCET, Asangaon

4) ROLLBACK:The Rollback command is ends the current transaction and will


undo any changes made since the transaction began. If used with savepoint it will
undo part of a transaction.
Syntax > rollback;
5) SAVEPOINT: It marks the current point in the processing of a transaction.
Syntax > savepoint ;
Syntax > savepoint rollback; // using rollback with savepoint.

COMMANDS:
SAVEPOINT:
Q. Write a query to implement the save point.
SQL> SAVEPOINT S1;
Savepoint created.

SQL> SELECT * FROM EMP;


EMPNO ENAME DESIGNATIN SALARY
---------- ------------ - --------- ----------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN ASST. PROF 16000
104 CHINNI HOD, PROF 45000

SQL> INSERT INTO EMP VALUES(105,'PARTHASAR','STUDENT',100);


1 row created.

SQL> SELECT * FROM EMP;


EMPNO ENAME DESIGNATIN SALARY
----- ------------ ---------- ----------
105 PARTHASAR STUDENT 100
101 NAGARAJAN LECTURER 16000
102 SARAVANAN ASST. PROF 16000
104 CHINNI HOD, PROF 45000

DISL /CSL 503/ Sem- V Page28


Computer Engg. / SSJCET, Asangaon

ROLL BACK
Q. Write a query to implement the Rollback.
SQL> ROLL BACK S1;
Rollback complete.

SQL> SELECT * FROM EMP;


EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN ASST. PROF 16000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD, PROF 45000

COMMIT
Q. Write a query to implement the Rollback.
SQL> COMMIT;
Commit complete.

CONCLUSION: Thus we have implemented DCL commands.

DISL /CSL 503/ Sem- V Page29


Computer Engg. / SSJCET, Asangaon

EXPERIMENT NO: 6

AIM: Perform Simple queries, string manipulation operations and aggregate


functions.
THEORY:
A) Simple Queries
TYPES OF CLAUSE:
1) WHERE
2) HAVING
3) ORDER BY

1) WHERE CLAUSE: The where clause is generally used with the select
command.
Syntax > select*from table_name where column_name<3;

2) HAVING CLAUSE: The having clause was added to SQL because the
keyword could not be used with aggregate functions.
Syntax > select column_name, sum(column_name) from table_name group by
column_name having sum(column_name)<4;

3) ORDER BY CLAUSE: The order by keyword is used to sort the


The result-set by a specified column. The order by keyword
Sorts the records in ascending order by default.
Syntax > select*from table_name order by table_name desc;

DISL /CSL 503/ Sem- V Page30


Computer Engg. / SSJCET, Asangaon

1) WHERE CLAUSE :

SQL> select*from stud where id<3;

ID NAME MOBNO MARKS

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


1 pratik 1231 0
2 danish 1232 0
2) HAVING CLAUSE :
SQL> select name,sum(id) from stud group by name having sum(id)<4;

NAME SUM(ID)

---------- ----------
danish 2
pratik 1
yogesh 3
3) ORDER BY CLAUSE :

SQL> select*from stud order by id desc;

ID NAME MOBNO MARKS

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

5 faiz 1235 0

4 manish 1234 0

3 yogesh 1233 0

2 danish 1232 0

1 pratik 1231 0

DISL /CSL 503/ Sem- V Page31


Computer Engg. / SSJCET, Asangaon

B) String manipulation functions

SQL String functions are the predefined functions that allow the database users for
string manipulation. These functions only accept, process, and give results of the
string data type.

Following are the most important string functions in Structured Query Language:

1. ASCII()
2. CONCAT()
3. FORMAT()
4. LCASE()
5. LEFT()
6. LENGTH()
7. LOWER()
8. LPAD()
9. LTRIM()
10.MID()
11.REPLACE()
12.REVERSE()
13.TRIM()
14.UCASE()

ASCII(): This function is used to find the ASCII value of a character.


Syntax: SELECT ascii('t');
Output: 116

CONCAT(): This function is used to add two words or strings.


Syntax: SELECT 'Geeks' || ' ' || 'forGeeks' FROM dual;
Output: ‘GeeksforGeeks’

DISL /CSL 503/ Sem- V Page32


Computer Engg. / SSJCET, Asangaon

FORMAT(): This function is used to display a number in the given format.


Syntax: Format("0.981", "Percent");
Output: ‘98.10%’

LCASE(): This function is used to convert the given string into lower case.
Syntax: LCASE ("GeeksFor Geeks To Learn");
Output: geeksforgeeks to learn

LEFT(): This function is used to SELECT a sub string from the left of given size
or characters.
Syntax: SELECT LEFT('geeksforgeeks.org', 5);
Output: geeks

LENGTH(): This function is used to find the length of a word.


Syntax: LENGTH('GeeksForGeeks');
Output: 13

LOWER(): This function is used to convert the upper case string into lower case.
Syntax: SELECT LOWER('GEEKSFORGEEKS.ORG');
Output: geeksforgeeks.org

LPAD(): This function is used to make the given string of the given size by
adding the given symbol.
Syntax: LPAD('geeks', 8, '0');
Output: 000geeks

LTRIM(): This function is used to cut the given sub string from the original
string.
Syntax: LTRIM('123123geeks', '123');
Output: geeks

MID(): This function is to find a word from the given position and of the given
size.
Syntax: Mid ("geeksforgeeks", 6, 2);
Output: for

REPLACE(): This function is used to cut the given string by removing the given
sub string.

DISL /CSL 503/ Sem- V Page33


Computer Engg. / SSJCET, Asangaon

Syntax: REPLACE('123geeks123', '123');


Output: geeks

REVERSE(): This function is used to reverse a string.


Syntax: SELECT REVERSE('geeksforgeeks.org');
Output: ‘gro.skeegrofskeeg’

TRIM(): This function is used to cut the given symbol from the string.
Syntax: TRIM(LEADING '0' FROM '000123');
Output: 123

UCASE(): This function is used to make the string in upper case.


Syntax: UCASE ("GeeksForGeeks");
Output:GEEKSFORGEEKS

C) Aggregate functions.
The Aggregate Functions returns the result based on group of rows
Unlike single row functions operate on sets of rows to give one result per group
these sets may be the whole table or the table spilt into group’s.
The Aggregate Functions are: 1) MIN
2) MAX
3) SUM
4) AVG

1) MIN: It returns the minimum value of specified column.


Syntax > select min(column_name) from table_name;

2) MAX: It returns the maximum value of specified column.


Syntax > select max(column_name) from table_name;

DISL /CSL 503/ Sem- V Page34


Computer Engg. / SSJCET, Asangaon

3) SUM: It returns the sum (total value)of specified column.


Syntax > select sum(column_name) from table_name;

4) AVG: It returns the Average value of specified column.


Syntax > select avg(column_name) from table_name;

CONCLUSION: Thus we have implemented Simple queries, string manipulation


operations and aggregate functions.

DISL /CSL 503/ Sem- V Page35


Computer Engg. / SSJCET, Asangaon

EXPERIMENT NO: 7

AIM: To implement Join Operation in SQL.


THEORY:
SQL JOINS:
1) EQUI JOIN: The EQUI JOIN preforms a join against equality or matching
column(s) values of the associated tables. An equal sign(=) is used as comparison
operator in the where clause to refer equality.
Syntax>selectcolumnlistfromtable1,table2 where table.column_name =
table2.column;

2) NON EQUI JOIN: The NON EQUI JOIN uses comparison operator instead of
the equal sign like >,<,>=,<= along with conditions.
Syntax > select*from table_name1, table_name2 where
table_name1.column [ > / < / >= / <= ] table_name2.column;

3) INNER JOIN: The INNER JOIN will select all rows from both participating
tables as long as there is a match between the columns.An sql inner join is same as
join clause, combining rows from to or more tables.
Syntax > select*from table_name1 JOIN table_name2 on table_name1.column =
table_name2.column;

4) NATURAL JOIN: The NATURAL JOIN is a type of equi-join and is


structured in such a way that,columns with same name of associate tables will
appear once only.
Syntax > select*from table_name1 Natural Join table_name2;

DISL /CSL 503/ Sem- V Page36


Computer Engg. / SSJCET, Asangaon

LEFT JOIN or LEFT OUTTER JOIN


Table:1 - ORDERS
SQL> CREATE table orders(O_Id number(5),Orderno number(5),P_Id
number(3));
Table created.

SQL> DESC orders;


Name Null? Type
--------------------- -------- -----------
O_ID NUMBER(5)
ORDERNO NUMBER(5)
P_ID NUMBER(3)

INSERTING VALUES INTO ORDERS


SQL>INSERT into orders values(1,77895,3)
1 row created.

SQL>INSERT into orders values(2,44678,3)


1 row created.

SQL>INSERT into orders values(3,22456,1)


1 row created.

SQL> INSERT into orders values(4,24562,1)


1 row created.

SQL> INSERT into orders values(5,34764,15)


1 row created.

TABLE SECTION:
SQL> SELECT * FROM orders;
O_ID ORDERNO P_ID
---------- ---------- ----------
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

DISL /CSL 503/ Sem- V Page37


Computer Engg. / SSJCET, Asangaon

TABLE -2: PERSONS


SQL> CREATE table persons(p_Id number(5),LASTNAME
varchar2(10),Firstname varchar2(15), Address varchar2(20),city varchar2(10));
Table created.

SQL> INSERT into persons values(1,'Hansen','Ola','Timoteivn 10','sadnes')


1 row created.

SQL> INSERT into persons values(2,'Svendson','Tove','Borgn 23','Sandnes')


1 row created.

SQL> INSERT into persons values(3,'Pettersen','Kari','Storgt 20','Stavanger')


1 row created.

SQL> SELECT * FROM persons;


P_ID LASTNAME FIRSTNAME ADDRESS CITY
---------- ---------- --------------- ------------------- ----------
1 Hansen Ola Timoteivn 10 sandnes
2 Svendson Tove Borgn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

LEFT JOIN SYNTAX


SQL>SELECT column_name(s) FROM table_name1 LEFT JOIN table_nameeON
table_name1.column_name=table_name2.column_name
LEFT JOIN EXAMPLE
SQL> SELECTpersons.lastname,persons.firstname,orders.orderno FROM persons
LEFT JOIN orders ON persons.p_Id = orders.p_Id ORDER BY persons.lastname;

OUTPUT
LASTNAME FIRSTNAME ORDERNO
------------------ ------------------ ---------------
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
Svendson Tove

DISL /CSL 503/ Sem- V Page38


Computer Engg. / SSJCET, Asangaon

FULL OUTTER JOIN


SQL> SELECT * FROM persons;
P_ID LASTNAME FIRSTNAME ADDRESS CITY
---------- --------------- -------------------- ---------------- ----------
1 Hansen Ola Timoteivn 10 sandnes
2 Svendson Tove Borgn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SQL> SELECT * FROM orders;


O_ID ORDERNO P_ID
---------- ---------- ----------
1 77895 3
2 44678 3
3 22456 1

FULL OUTER JOIN SYNTAX


SQL>SELECT column_name(s) FROM table_name1 FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

FULL OUTER JOIN EXAMPLE


SQL> SELECT persons.lastname,persons.firstname,orders.orderno FROM
persons
FULL OUTER JOIN orders ON persons.p_Id = orders.p_Id ORDER BY
persons.lastname;

RIGHT OUTTER JOIN


RIGHT OUTTER JOIN SYNTAX
SQL>SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM
Persons RIGHT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY
Persons.LastName

RIGHT OUTTER JOIN EXAMPLE


SQL> SELECT persons.lastname,persons.firstname,orders.orderno FROM
persons RIGHT OUTER JOIN orders ON persons.p_Id = orders.p_Id ORDER BY
persons.lastname;

DISL /CSL 503/ Sem- V Page39


Computer Engg. / SSJCET, Asangaon

LASTNAME FIRSTNAME ORDERNO


------------------- ----------------- ---------------
Hansen Ola 24562
Hansen Ola 22456
Pettersen Kari 44678
Pettersen Kari 77895

INNER JOIN
INNTER JOIN SYNTAX
SQL>SELECT column_name(s) FROM table_name1 INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name

INNTER JOIN EXAMPLE


SQL> SELECT persons.lastname,persons.firstname,orders.orderno FROM
persons INNER JOIN orders ON persons.p_Id = orders.p_Id ORDER BY
persons.lastname;

LASTNAME FIRSTNAME ORDERNO


------------------ ------------------ ---------------
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678

LASTNAME FIRSTNAME ORDERNO


------------- --------------- ----------
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
Svendson Tove 34764
6 rows selected.

CONCLUSION: Thus we have studied implementation of Join Operation in SQL.

DISL /CSL 503/ Sem- V Page40


Computer Engg. / SSJCET, Asangaon

EXPERIMENT NO: 8

AIM: Implementation of Views and Triggers.


THEORY:
VIEW:
A view is logical table based on a table or another view. View logically represents
Subsets of data from one or more tables. A view contains no data of its own but It
is like a window through which data from tables can be viewed or changed.
To Create View:
Using this syntax given bellows we can create the view of table.
Syntax > create view view _name as select column_name 1, column_name n from
table_name;
Syntax > select*from view _name;

To Update View:
Using this syntax given bellows we can modify the view data.
Syntax > update view _name set column_name ='value' where
column_name=value;
Syntax > select*from view _name;
COMMANDS:

CREATION OF TABLE
--------------------------------
SQL> CREATE TABLE EMPLOYEE( EMPLOYEE_NAMEVARCHAR2(10),
EMPLOYEE_NONUMBER(8), DEPT_NAME VARCHAR2(10), DEPT_NO
NUMBER (5),DATE_OF_JOIN DATE);
Table created.

TABLE DESCRIPTION
-------------------------------
SQL> DESC EMPLOYEE;

DISL /CSL 503/ Sem- V Page41


Computer Engg. / SSJCET, Asangaon

NAME NULL? TYPE


------------------------------- -------- ------------------------
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE

SYNTAX FOR CREATION OF VIEW


--------------------------------------------------
SQL> CREATE <VIEW><VIEW NAME> AS SELECT <COLUMN_NAME_1>,
<COLUMN_NAME_2> FROM <TABLE NAME>;

CREATION OF VIEW
------------------------------
SQL> CREATE VIEW EMPVIEW AS SELECT
EMPLOYEE_NAME,EMPLOYEE_NO,DEPT_NAME,DEPT_NO,
DATE_OF_JOIN FROM EMPLOYEE;

VIEW CREATED.

DESCRIPTION OF VIEW
--------------------------------
SQL> DESC EMPVIEW;

NAME NULL? TYPE


-------------------------- -------- ----------------------------
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)

DISPLAY VIEW:
----------------------
SQL> SELECT * FROM EMPVIEW;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO


---------- ----------- ---------- ----------
RAVI 124 ECE 89

DISL /CSL 503/ Sem- V Page42


Computer Engg. / SSJCET, Asangaon

VIJAY 345 CSE 21


RAJ 98 IT 22
GIRI 100 CSE 67

INSERTION INTO VIEWINSERT STATEMENT:


SYNTAX:
SQL> INSERT INTO <VIEW_NAME> (COLUMN NAME1,………)
VALUES(VALUE1,….);

SQL> INSERT INTO EMPVIEW VALUES ('SRI', 120,'CSE', 67,'16-NOV-1981');


1 ROW CREATED.

SQL> SELECT * FROM EMPVIEW;


EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO
---------- ----------- ---------- ----------
RAVI 124 ECE 89
VIJAY 345 CSE 21
RAJ 98 IT 22
GIRI 100 CSE 67
SRI 120 CSE 67

SQL> SELECT * FROM EMPLOYEE;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J


---------- ----------- ---------- ---------- ---------
RAVI 124 ECE 89 15-JUN-05
VIJAY 345 CSE 21 21-JUN-06
RAJ 98 IT 22 30-SEP-06
GIRI 100 CSE 67 14-NOV-81
SRI 120 CSE 67 16-NOV-81

DELETION OF VIEW:
DELETE STATEMENT:
SYNTAX:
SQL> DELETE <VIEW_NMAE>WHERE <COLUMN NMAE> =’VALUE’;
SQL> DELETE FROM EMPVIEW WHERE EMPLOYEE_NAME='SRI';
SQL> SELECT * FROM EMPVIEW;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO


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

DISL /CSL 503/ Sem- V Page43


Computer Engg. / SSJCET, Asangaon

RAVI 124 ECE 89


VIJAY 345 CSE 21
RAJ 98 IT 22
GIRI 100 CSE 67
SRI 120 CSE 67

SQL> SELECT * FROM EMPLOYEE;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_N DATE_OF_J


---------- ----------- ---------- ---------- ---------
RAVI 124 ECE 89 15-JUN-05
VIJAY 345 CSE 21 21-JUN-06
RAJ 98 IT 22 30-SEP-06
GIRI 100 CSE 67 14-NOV-81
SRI 120 CSE 67 16-NOV-81

Trigger
Trigger in Structured Query Language is a set of procedural statements which are
executed automatically when there is any response to certain events on the
particular table in the database. Triggers are used to protect the data integrity in the
database.

In Structured Query Language, triggers are called only either before or after
the below events:

1. INSERT Event: This event is called when the new row is entered in the
table.
2. UPDATE Event: This event is called when the existing record is changed
or modified in the table.
3. DELETE Event: This event is called when the existing record is removed
from the table.

Types of Triggers in SQL

Following are the six types of triggers in SQL:

1. AFTER INSERT activated after data is inserted into the table.

DISL /CSL 503/ Sem- V Page44


Computer Engg. / SSJCET, Asangaon

2. AFTER UPDATE: activated after data in the table is modified.

3. AFTER DELETE: activated after data is deleted/removed from the table.

4. BEFORE INSERT: activated before data is inserted into the table.

5. BEFORE UPDATE: activated before data in the table is modified.

6. BEFORE DELETE: activated before data is deleted/removed from the table.

Examples showing implementation of Triggers:


1. Write a trigger to ensure that no employee of age less than 25 can be
inserted in the database.

delimiter $$
CREATE TRIGGER Check_age BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
IF NEW.age < 25 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'ERROR:
AGE MUST BE ATLEAST 25 YEARS!';
END IF;
END; $$
delimiter;

2. Create a trigger which will work before deletion in employee table and
create a duplicate copy of the record in another table employee_backup.

Before writing trigger, we need to create table employee_backup.

DISL /CSL 503/ Sem- V Page45


Computer Engg. / SSJCET, Asangaon
create table employee_backup (employee_no int,
employee_name varchar(40), job varchar(40),
hiredate date, salary int,
primary key(employee_no));
delimiter $$
CREATE TRIGGER Backup BEFORE DELETE ON employee
FOR EACH ROW
BEGIN
INSERT INTO employee_backup
VALUES (OLD.employee_no, OLD.name,
OLD.job, OLD.hiredate, OLD.salary);
END; $$
delimiter;

Write a trigger to count number of new tuples inserted using each insert
statement.

Declare count int


Set count=0;
delimiter $$
CREATE TRIGGER Count_tupples
AFTER INSERT ON employee
FOR EACH ROW
BEGIN
SET count = count + 1;
END; $$
delimiter;

CONCLUSION: Thus we have performed practical on implementation of views


and trigger.

DISL /CSL 503/ Sem- V Page46


Computer Engg. / SSJCET, Asangaon

EXPERIMENT NO: 9

AIM: Implement procedure and functions


THEORY:
SQL Functions
Functions in SQL Server are the database objects that contains a set of SQL
statements to perform a specific task. A function accepts input parameters, perform
actions, and then return the result. We should note that functions always return either a
single value or a table. The main purpose of functions is to replicate the common task
easily. We can build functions one time and can use them in multiple locations based on
our needs. SQL Server does not allow to use of the functions for inserting, deleting, or
updating records in the database tables.

Types of SQL Functions


SQL Server categorizes the functions into two types:
o System Functions
o User-Defined Functions

System Functions
Functions that are defined by the system are known as system functions. In other
words, all the built-in functions supported by the server are referred to as System
functions. The built-in functions save us time while performing the specific task. These
types of functions usually work with the SQL SELECT statement to calculate values and
manipulate data.

Here is the list of some system functions used in the SQL Server:

o String Functions (LEN, SUBSTRING, REPLACE, CONCAT, TRIM)


o Date and Time Functions (datetime, datetime2, smalldatetime)
o Aggregate Functions (COUNT, MAX, MIN, SUM, AVG)
o Mathematical Functions (ABS, POWER, PI, EXP, LOG)
o Ranking Functions (RANK, DENSE_RANK, ROW_NUMBER, NTILE)

User-Defined Functions
Functions that are created by the user in the system database or a user-defined
database are known as user-defined functions. The UDF functions accept

DISL /CSL 503/ Sem- V Page47


Computer Engg. / SSJCET, Asangaon

parameters, perform actions, and returns the result. These functions help us to
simplify our development by encapsulating complex business logic and making it
available for reuse anywhere based on the needs. The user-defined functions make
the code needed to query data a lot easier to write. They also improve query
readability and functionality, as well as allow other users to replicate the same
procedures.

Syntax

CREATE FUNCTION schema_name.function_name (parameter_list)


RETURNS data_type AS
BEGIN
statements
RETURN value
END

The above syntax parameters are described below:


We will first define the function name after the CREATE FUNCTION keywords.
The name of the schema is optional. If we will not define the schema name, SQL
Server uses default schema dbo. Next, we will define the list
of parameters enclosed in parenthesis. Third, we will write the statements for the
function and then, in the RETURNS statement, define the data type of the return
value. Finally, we have added the RETURN statement to return a value inside the
function's body.

Example

DELIMITER $$
CREATE FUNCTION add
(
a INT, b INT
)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE added_together INT;
SET added_together = a + b;
RETURN added_together;
END$$

DISL /CSL 503/ Sem- V Page48


Computer Engg. / SSJCET, Asangaon

DELIMITER;

Stored Procedure

A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.

So if you have an SQL query that you write over and over again, save it as a
stored procedure, and then just call it to execute it.

You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value(s) that is passed.

Stored Procedure Syntax


CREATE PROCEDURE procedure_name
AS
sql_statement
GO;

Execute a Stored Procedure


EXEC procedure_name;

Stored Procedure Example

The following SQL statement creates a stored procedure named


"SelectAllCustomers" that selects all records from the "Customers" table:

CREATE PROCEDURE SelectAllCustomers


AS
SELECT * FROM Customers
GO;

Execute the stored procedure above as follows:

Example
EXEC SelectAllCustomers;

Stored Procedure With One Parameter

The following SQL statement creates a stored procedure that selects Customers
from a particular City from the "Customers" table:

Example
DISL /CSL 503/ Sem- V Page49
Computer Engg. / SSJCET, Asangaon
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;

Execute the stored procedure above as follows:

Example
EXEC SelectAllCustomers @City = 'London';

Stored Procedure With Multiple Parameters

Setting up multiple parameters is very easy. Just list each parameter and the
data type separated by a comma as shown below.

The following SQL statement creates a stored procedure that selects Customers
from a particular City with a particular PostalCode from the "Customers" table:

Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode
nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;

Execute the stored procedure above as follows:

Example
EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';

Difference between functions and procedures

Parameter

DISL /CSL 503/ Sem- V Page50


Computer Engg. / SSJCET, Asangaon
Function Procedure

The function calculates and


The procedure performs certain tasks after
Return Value returns the results after receiving
receiving certain inputs.
certain inputs.

Try-Catch Functions do not support try-catch


Procedures support try-catch blocks.
Blocks blocks.

SQL Query Procedures cannot be called in a SQL


Functions are called in SQL Query
Integration query.

Select SELECT statements can have SELECT statements cannot have procedure
Statements function calls calls.

We cannot use DML(Data We can use DML in procedure to


DML Usage Manipulation Language) in manipulate data using UPDATE, DELETE
function. and INSERT commands.

Inter-
We can call a function using
Procedure Procedure cannot be called in a SQL query.
procedure.
Calling

For example, it calculates the total For example, a procedure is one that
price of products in a shopping updates the inventory of products when a
Example
cart or converts units of purchase is made or inserts new records
measurement. into a transaction log.

Conclusion : Thus we have performed practical on functions and procedure.

EXPERIMENT NO: 10

AIM: Demonstrate Database connectivity


THEORY:

DISL /CSL 503/ Sem- V Page51


Computer Engg. / SSJCET, Asangaon

Database Connectivity refers to the mechanisms that enable application software


to communicate with database management systems (DBMS). Establishing a
connection is essential for performing operations such as creating, reading,
updating, and deleting data within a database.
Key components of database connectivity include:

 Connection Strings: These strings contain information that the software


uses to establish a connection to the database. They typically include
parameters like the database type, server address, database name, user ID,
and password.
 Data Providers: These are libraries or modules specific to a database
system (e.g., SQL Server, MySQL, Oracle) that offer an interface to execute
commands and manage data.
 APIs: Application Programming Interfaces enable developers to interact
with the DBMS using standard programming constructs, abstracting the
complexities of direct database manipulation.

The process of database connectivity often involves the use of popular protocols
such as JDBC for Java applications or ODBC for applications written in various
programming languages. The choice of technology and method depends on
performance requirements, security considerations, and the specific features
provided by the DBMS vendor.

Querying the database

Organized collection of data in a computer system is a database. It stores


information in the form of structured tables that contain rows and columns to
organize the data. It is controlled by the management system. DBMS enables
creation and maintenance of database.

SQL (Structured Query Language) is used for querying the data stored in a
relational database. MySQL database and SQL select are some modified versions
of SQL. The query is categorized into DDL (Data Definition Language) and DML
(Data Manipulation Language).

Data Definition Language (DDL):

DISL /CSL 503/ Sem- V Page52


Computer Engg. / SSJCET, Asangaon

The statements used to create the database schema and the tables are referred to as
DDL. They can also be used to modify the structure of the table. For example,
CREATE, ALTER and so forth.

Data Manipulation Language (DML):

These statements are used to insert records into the table, update and delete records
present in the table. For example, INSERT, UPDATE, DELETE and so forth.

Database Driver

A driver is a computer program that helps applications to establish database


connection. There are two standard protocols for establishing database connectivity
name Open Database Connectivity (ODBC) and Java Database Connectivity
(JDBC). These enable applications to access and manipulate database contents by
providing a generic interface.

Java Database Connectivity (JDBC)

JDBC is an application programming interface (API) for the Java programming


language. It uses a Java-based technology to access the database. JDBC gives
methods to query and update data in a database.

A JDBC API accesses data from the relational database tables. The data in these
databases can be saved, updated, deleted and retrieved. JDBC uses drivers to
connect with the database.

JDBC is based on an Open SQL Call Level Interface. The classes and interfaces
for JDBC API are stored in the java.sql package. Some of the popular JDBC API
interfaces include ResultSet interface, CallableStatement interface, Driver
interface, Connection interface, Statement interface, and RowSet interface.

Example program that connects an application with the database using JDBC

DISL /CSL 503/ Sem- V Page53


Computer Engg. / SSJCET, Asangaon
package database_console;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class DBConnect {

public static void main(String[args]){

try{

String host = “jdbc:derby://localhost:1527/Students”

String userName = “Username”;

String userPassword = “Password”;

Connection con = DriverManager.getConnection(host, userName, Password);

catch (SQLException error) {

System.out.println(error.getMessage() );

Explanation:

The above program establishes a connection between the database Students and
Java application. The code begins by importing the necessary Java packages. In the
following line, a new class DBConnect is created. In JDBC, the connection starts
with jdbc: protocol. So, in this code, inside the try function, the connection with
the Java application is being made using the jdbc protocol. The next two
statements are written to fetch the username and password of the user. Finally, the
connection is established through the DriverManager.getConnection() function.

DISL /CSL 503/ Sem- V Page54


Computer Engg. / SSJCET, Asangaon

The try-catch block is used in database connectivity so that it can return an


SQLException error if a database fails to connect to the application.

JDBC drivers

A JDBC driver is software that allows the Java application to connect with a
database. The driver connects to the database and implements the protocol to
transfer the query between the application and the database. JDBC drivers are of
four types:

 JDBC-ODBC bridge- This bridge driver connects to the database using the
ODBC driver. The driver transforms the JDBC method calls into ODBC
function calls.
 Native-API driver– This driver uses client-side libraries of the database. It
transforms JDBC method calls into native calls of the API.
 Network-Protocol driver– This JDBC driver uses a middleware between
the calling program and database. The middleware is responsible for
converting JDBC calls directly or indirectly to a database protocol call.
 Database-Protocol driver (Pure Java driver/Thin driver)– This JDBC
driver transforms the JDBC calls directly into a vendor-specific database
protocol call. It is the fastest JDBC driver.

Open database connectivity (ODBC)

DISL /CSL 503/ Sem- V Page55


Computer Engg. / SSJCET, Asangaon

The standard way to create an application programming interface (API) used by


the system to access databases is open database connectivity (ODBC). It is
supported by Microsoft and is written in C programming language. ODBC has
highly efficient database connectivity with a high-performance interface.
Relational data storage and relational data management systems (RDBMS) are
handled using ODBC, which is low-level database connectivity.

It is an independent application that can be added to the software as ODBC drivers


to form an interface that will work between the user application and particular
DBMS. ODBC compliant is an application that uses an ODBC driver. ODBC is
mainly used in database management systems.

Before the invention of ODBC, SQL servers were used to create APIs (Application
Programming Interface). SQL language embedding and SQL statements were used
in late 1980 as a potential way to create an interface. The latest version of ODBC is
available on all platforms. ODBC drivers such as SQLite are to be embedded in the
existing software.

Driver Manager

ODBC drivers are managed using driver managers. Functions such as spooling and
enumerating drivers are done by the driver manager.

Bridge drivers

Bridge drivers are drivers that use another type of driver for operation. Depending
on the drivers, bridges can be classified into:

 ODBC-JDBC bridges: Open database connectivity driver uses Java database


connectivity driver functions and calls.
 JDBC-ODBC bridges: Java database connectivity driver uses Open database
connectivity function calls.
 OLE DB-ODBC bridges: Object linking and embedding database (OLE DB)
driver uses ODBC method calls.
 ADO.NET TO ODBC bridges: ActiveX database objects embedded in .NET
uses ODBC method calls.

Conclusion : Thus we have performed practical on database connectivity using


SQL with an example.

DISL /CSL 503/ Sem- V Page56


Computer Engg. / SSJCET, Asangaon

DISL /CSL 503/ Sem- V Page57

You might also like