You are on page 1of 35

Ms. S. A.

Kshirsagar SYCM
-DMS
2. RELATIONAL DATA MODEL

2.1 FUNDAMENTALS OF RDBMS- Record,fields,Datatypes,Tables and Database

RDBMS stands for Relational Database Management Systems


All database management system like SQL,MS SQL server, IBM DB2,ORACLE,MySQL and
Microsoft Access are based on RDBMS.
It is called relational database management system(RDBMS) because it is introduced by
E.F.Codd.
Data is represented in terms of tuples (rows) in RDBMS.
it contains number of tables and each table has its own primary key.

DATABASE -
A database is an organized collection of data.
The main purpose of database is to operate large amount of information by storing , retrieving
and managing.
There are many database available like SQL,MySQL,Oracle,SQLserver,MongoDB,Sybase etc.

TABLE:
A table is a collection of data organized in terms of rows and columns .
Below is the example of student table:

Rollno Name Age City


1 Priya 16 Pune
2 Pravin 18 Mumbai
3 Prasad 20 Solapur

RECORD:
A single entry in table is called a Record or Tuple or Row.

e.g. In the above student table it has 4 records/tuples, rows.


Following is an example of a single record/tuple.

1 Priya 16 Pune

FIELDS:
A space allocated for a perticular item of information.
In Database a fields are the smallest units of information you can access.
fields may have an attributes associated with them.

Sou.venutaichavan polytechnic, pune Page 1


Ms. S. A. Kshirsagar SYCM
-DMS
e.g. a student table have a number of fields one for RollNo,one for name, one for age, one for
city.
some fields are numeric ,some are textual, whereas some are long & some are short.

DATA TYPES
1. NUMERIC DATA TYPES

INT or INTEGER
SMALLINT
NUMBER
2. APPROXIMATE NUMERIC DATA TYPES
FLOAT(p)
Real
3. DATE AND TIME DATA TYPES
datetime
date
time
timestamp
4. CHARACTER STRINGS DATA TYPES
char
varchar
varchar(max)
text
5. FORMATTED NUMBERS
DEC(p, s) or DECIMAL(p,s)
NUM(p,s) or NUMERIC(p,s)
p - precision value i.e. number of digits in a number
s - scale value i.e. number of digits to right side after point.

CONCEDPT OF RDBMS

A relational database management system(RDBMS) is a database management system


based on the relational modelintroduced by E.F.codd.

In relational model data is stored in relations i.e tables and it is represented in the form of
rows/tuples.
RDBMS is used to manage realational database.
Relational database is a collection of organized set of tables related to each other and from it we
can access data easily.
Relational database is the most commonly used database.

Sou.venutaichavan polytechnic, pune Page 2


Ms. S. A. Kshirsagar SYCM
-DMS

2.2 Codd’s Rule for relational DBMS

E.F.codd was a scientist who invented the relational model for database managent. Based
onrelationalmodel,the relational database was created.codd proposed rules known as codd’s 12
rules. They are as follows:

Codd rules:
Rule 1 : The information rule
According to E.F. codd’s first rule, the whole data/information has to be presented in the form of
table.
Rule 2 : Guaranteed Access Rule
second rule states that whole data should be accessible to the user by the combination of table
name, primary key, and column name.
e.g. select name from student where rollno=3;

Rule 3: Systematic treatment of null values


Third law states that the null values i.e. absence of the values in the table should be treated
properly. The table should allow a field to remain empty. This is not applicable to primary keys.
Key columns cannot have null values.

Rule 4 : Dynamic on-line catalog

Database dictionary must have description of database. The database structures i. e metadata and
its contents are stored into tables so some commands should be used to access data as well as
catalogs.

Rule 5 :Powerfull language

The RDBMS must support at least one clearly defined language that includes functions for data
definition, data manipulation,data integrity and transaction control.

e.g. SQL

Rule 6 : View updating rule

RDBMS should support data consistency in case of updations into database.


The changes must be transmitted to the base table and its view.
Rule 7: High level insert,update and delete
The RDBMs supports insertion,updation and deletion at the table level.

Sou.venutaichavan polytechnic, pune Page 3


Ms. S. A. Kshirsagar SYCM
-DMS
The performance is improved if the commands act on a set of records rather than on a single at a
time.
Rule 8: Physical data independence

The application programs are not affected by changes in the physical data access and storage
methods.

e.g. if some file supporting table is renamed or moved from one disk to other ,it should not affect
the application.

Rule 9: Logical data independence

Logical changes in tables and views such as adding/deleting columns or changing column size
should not affect on application program.

E.g. if a table split into two tables, a new view should give result as the join of the two tables.

Rule 10: Integrity independence


Similar to data definition integrity constraints i.e. key and check constraints, trigger etc should be
stored in data dictionary.

Rule 11: Distribution independence


Application programs and user requests should not affected by changes in the distribution of
physical data at different locations.

Rule 12: Non subversion rule


The language used by RDBMS to access data should not be used to subvert (destroy) integrity
rules to change the data.

KEY CONCEPTS:
Key:
To identify the entity in entity set.

Define super key.


Definition: Super key of an entity set is a set of one or more attributes uniquely identify an entity
in entityset.
e.g. consider a customer relation
customer ={ id,name,addr}
id is a super key.
If k is acting as super key then super set of k is also called super key.
super keys are: id
id,name
id,addr
id,name,addr

Sou.venutaichavan polytechnic, pune Page 4


Ms. S. A. Kshirsagar SYCM
-DMS

Candidate key:

Definition: A minimal super key is called as a candidate key.


e.g.id
Here above id is minimal super key so id is the candidate key.

OR
Definition:In a relation, there may be a primary key or may not, but there may be a key or
combination of keys which uniquely identify the record. Such a key is called as Candidate key.

Primary key:

Definition :A key which is selected by the designer to uniquely identify the entity is called as
Primary key.
 A primary key cannot contain duplicate values.
 It can never contain null values inside it.
 each table can have only ONE primary key

Foreign key:
Definition :A foreign key is an attribute of relation r1 which is used as primary key of other
relation r2.

The relation r1 is called as referencing relation and r2 is caaled as referenced relation.

e.g. r1-customer = {cust_id, cust_name, loan_id, cust_addr }


r2- loan= {loan_id, branch_name,amount}

create table customer(cust_id number(5) primary key,cust_namevarchar(20),loan _id


number(5) constraint lidfk references loan(loan_id)

Here , customer relation contains one attribute loan_id which is primary key of loan relation.
Such attribute is called as foreign key of customer relation.

Here, customer is referencing relation and loan is referenced relation.

Sou.venutaichavan polytechnic, pune Page 5


Ms. S. A. Kshirsagar SYCM
-DMS

2.3 Normalization
Definition: Normalization can be defined as process of decomposition of database tables to avoid
the data redundancy.

The normalization is an important process that removes the repeating data from database andalso
used to remove the inconsistency.

Need of normalization

 Insert anomaly due to lack of that is all the data available for insertion such that null
values inkeys should be avoided. This kind anomaly and seriouslydamage a database.
 Update anomalydue to data redundancy that is multiple occurrences of same values
incolumn.
 Deletion anomaly it leads to loss of data for rows that are not stored else square it could
result in loss of vital data.

Advantages of the normalization.

 More efficient data structure.


 Avoid redundant fields or columns.
 More flexible data structure i.e. we should be able to add new rows and data values easily
 Better understanding of data
 Ensures that distinct tables exist when necessary.

Types of Normalization:
1 NF
2NF
3NF

First Normal Form (1NF):


Definiion:A relation R is said to be in first normal form (1NF) if the domain of all attributes of R
are atomic.
OR
A table is in the first normal form if it contains no repeating elements groups.

Example: Supplier (sno, sname, location, pno, qty)

Sou.venutaichavan polytechnic, pune Page 6


Ms. S. A. Kshirsagar SYCM
-DMS

The above relation is in 1NF as all the domains are having atomic value. But it is not in 2NF

Second Normal Form (2NF):


Definiion:A relation is said to be in the second normal form if it is in first
normal form and all the non key attributes are fully functionally dependent on the primary key.

Example: In the above relation NAME, LOCATION depends on SNO and QTY on (SNO, PNO)
so the table can be split up into two tables as Supplier(SNO,SNAME,LOCATION) and Supplier
Products(SNO,PNO,QTY) and now both the tables are in second normal form.

Supplier

SNO SNAME LOCATION


S1 Abc Mumbai
S2 Pqr Pune
S3 Lmn Delhi

Supplier products

Sou.venutaichavan polytechnic, pune Page 7


Ms. S. A. Kshirsagar SYCM
-DMS

Third normal form(3NF):


Definiion:A table is in the third normal form if it is in the second normal form and all the non-key
columns are non transitively dependent on the primary key.

If the value of a non-key column is dependent on the value of another non-key column we have a
situation known as transitive dependency.

So in above supplier product table, the non key column QTY is dependent on non key column
PNO but non key column PNO is depends on primary key SNO, so QTY transitively depends on
SNO for removing this transitivity create table product with non key columns i.e. PNO and QTY.
{ QTY -> PNO
PNO -> SNO
QTY->SNO
}

Supplier

SNO SNAME LOCATION


S1 Abc Mumbai
S2 Pqr Pune
S3 Lmn Delhi

Suppliers product

SNO PNO
S1 P1
S2 P2
S3 P3

product

PNO QTY
P1 200
P2 300
P3 400

Sou.venutaichavan polytechnic, pune Page 8


Ms. S. A. Kshirsagar SYCM
-DMS
Q.Given: Student (Roll_No, Name, Class, Total_Marks, Percentage, Grade)
normalize up to 3NF
Ans:
1NF:
1) Student (Roll_No, Name, Class, Total_Marks, Percentage, Grade)
2NF:
1) Student(Roll_No, Name, Class)
2) Marks(Roll_No, Total_Marks, Percentage, Grade)
3NF:
1) Student(Roll_No, Name, Class )
2) Marks(Roll_No, Total_Marks, Percentage)
3) Grade (Percentage, Grade)

Q. Given: Student (student_id ,student_name, DOB, Street, City,State,Zip)


normalize up to 3NF

1NF:
1) Student (student_id, student_name, Dob, Steet, City, State, Zip)
2NF:
1) Student(Student_id, Student_name, Dob)
2) Student_details(student_id, , Street,City,State,Zip)
3NF:
1) Student(Student_id, Student_name, Dob)
2) Student_details(student_id ,Zip)
3)Address(Zip, Street,City,State)

2.3 SQL [Structured Query Language]


Definition: SQL stands for Structured Query Language .It is a database query language used for
creating, storing and managing data in RDBMS.
Features of SQL are:
 SQL allows the user to create, update, delete, and retrieve data from a database.
 SQL is very simple and easy to learn.
 SQL works with database programs like DB2, Oracle,
 MS Access, Sybase, MS SQL Sever etc.

Components of SQL are as follows:

 DDL (Data Definition language)


 DML (Data Manipulation language)
 DCL (Data Control language)
 DQL (Data Query language)

Sou.venutaichavan polytechnic, pune Page 9


Ms. S. A. Kshirsagar SYCM
-DMS
DDL (DATA DEFINITION LANGUAGE)

This includes changes to the structure of the table like creation of the table, altering table,
deleting structure of the table(i.e. drop)
All DDL commands are auto committed that means it saves all the changes permanently.
e.g. List of DDL commands
1. Create
2. Alter
3. Rename
4. Drop
5. Truncate
6.Rename

DML (DATA MANIPULATION LANGUAGE)


DML commands are used for manipulating the data stored in the table .
DML command are not auto committed.
That means changes are not permanent, they can be roll backed.
e.g. List of DML commands:
1. Insert
2. Update
3. Delete

DQL (DATA QUERY LANGUAGE)


DQL are used to fetch/retrieve/select/display data from tables based on condition that we can
apply easily.
e. g. List of DQL commands:
1. Select

DCL (DATA CONTROL LANGUAGE)


DCL are the commands to grant and take back authority from any database users.
e. g. List of DCL commands:
1. Grant
2. Revoke
3. Commit
4. Rollback
5. Savepoint

DDL commands:

1) CREATE

This command is used to create the table or define the structure of the table.

Syntax:

Sou.venutaichavan polytechnic, pune Page 10


Ms. S. A. Kshirsagar SYCM
-DMS
create table table_name( column_name1 datatype(size), column_name2 datatype(size),….,
column_name_ndatatype(size) );

e.g:
create table student ( rollno number(3), name varchar(20), city varchar(20), dob date);

2) DESCRIBE or DESC
Used to describe the structure of the table
Syntax:
desctable_name;
e.g:
desc student;

3)ALTER
This command is used to make certain changes in structure of table after creating it.
It helps in modifying the table if we want to change datatype or size of column ,add new column,
delete i.e drop any column from existing table.

Syntaxes:

a)for adding new column in an existing table:

syntax:
alter table table_name add column_namedatatype(size);

e.g. alter table student add marks number(3);

in above example marks column added in existing student table.

b)for deleting any column from existing table:

syntax:
alter table table_name drop column column_name;

e.g.alter table student drop column dob;

in above example dob column is deleted from existing student table.

c)To change the size or datatype

Sytax:
Alter table table_name modify column_name datatype(size);

Here datatype is changed datatype and size is changed size.

Sou.venutaichavan polytechnic, pune Page 11


Ms. S. A. Kshirsagar SYCM
-DMS
e.g. alter table student modify marks float(4);

in above example we have changed the datatype of marks column number to float and size from
3 to 4.

d)To rename column name

Syntax:
Alter table table_name rename column old_column_name to new_column_name;

e.g. alter table student rename column city to address;

in above example we have renamed column name of city to address in an existing table student.
e)To add primary key

Syntax:
Alter table table_name add primary key(column_name);

e.g. alter table student add primary key(rollno);

in above example we have added or set the primary key for column rollno.

e)To remove primary key

Syntax:
alter table table_name drop primary key;

e.g. alter table student drop primary key;

in above example we had unset primary key for column rollno.

4)TRUNCATE

This command is used to delete only data or rows .


After using this command only data deleted ,the structure of the table remains same. I.e the table
structure remains as it is.
After truncate the space will frees, we can reenter the data.
Syntax

truncate table table_name;

e.g. truncate table student ;


in above example only data is deleted and space will free. table structure remains as it is.

Sou.venutaichavan polytechnic, pune Page 12


Ms. S. A. Kshirsagar SYCM
-DMS
5)RENAME
This command is used to rename the name of table.That is we can give new name to table.
Syntax:
Rename old_table_name to new_table_name;

e.g. rename student to student_info;

now the name of table is student_info.

6) DROP
This command is used to delete the structure of table.That is the whole table structure is deleted
with data permanently i.e. table does not exists.

Syntax:

drop table table_name;

e.g. drop table student_info;

in above example the structure of the student_info table is deleted .it will does not exist after
using this command.

2.6 Data integrity constraint

Integrity constraints are used to ensure accuracy and consistencyof data in relational database.
In RDBMS accuracy and consistency stands for completeness and correctness.

The integrity or data integrity has following types:

I/O constraints or entity constraints

It includes primary key, foreign key, unique key constraints.

Business rule or domain constraints

It includes default, not null, check constraints.

I/O constraints
Constraints are the rule which apply to table columns to store valid data and prevents the user to
enter invalid data into columns.
a) Primary key constraints :

Sou.venutaichavan polytechnic, pune Page 13


Ms. S. A. Kshirsagar SYCM
-DMS
It helps to identify the row uniquely. It has two rules:
1) There should not be a duplicate or repeated values.
2) No any cell is null. i.e. not null constraint
One table has only one primary key and is created when table is created.

Syntax:

Create table table_name(column_name1 datatype(size) ,column_name2 datatype(size)


constraint constraint_name primary key,…, column_name_ndatatype(size) );

e.g. create table emp(eid number constraint eid_pk primary key, enamevarchar(20),city
varchar(20));

b) Foreign key constraint/Referential integrity constraint:

This is also called as referential integrity constraints. Parent table is known as referenced table
and table with foreign key is called as child constraint.

Syntax:
Create table table_name(column_name1 datatype(size),column_name2 datatype(size)
constraint constraint_name references referenced_table_name(column_name),
….,column_name_ndatatype(size));

Examples:
1)[ loan(lid,type,amount)
customer(cid,cname,caddr,lid) …..in this lid is foreign key i.e taken from loan table so we will
create table customer.]

 Create table customer(cid number(8),cnamevarchar(15),caddrvarchar(15),lid number(4)


constraint lidfk references loan(lid));

2)[Dept-{deptno,deptname}
emp-{empid,empname,deptno,salary} …here deptno is foreign key which taken the reference of
dept table.]
 Create table emp(empid number(4),empnamevarchar(15),deptno number(4) constraint
deptnofk references dept(deptno),salary number(8));

Unique Constraint: The UNIQUE constraint is used to avoid the duplicate values.
The unique and primary key constraints both provides the guarantee for uniqueness i.e both keys
are avoid duplicate values but unique key accept null values.
Syntax:

Sou.venutaichavan polytechnic, pune Page 14


Ms. S. A. Kshirsagar SYCM
-DMS
create table table_name (column_namedata_type(size),…..,column_name_ndata_type(size)
constraint constraint_name unique);

OR
create table table_name (column_namedata_type(size),…..,column_name_ndata_type(size)
unique);

Example: person(pid,firstname,city) -----make unique for pid


Create table person(pid number(5) constraint pidukunique,firstnamevarchar (15),city
varchar(14));
OR
Create table person(pid number(5)unique,firstnamevarchar (15),city varchar(14));

2)book(bid,bname,author,price) ……..take bid unique


Create table book(bid number(4) unique,bnamevarchar(15),author varchar(15),price number(3));

ii)BUSINESS RULE OR DOMAIN CONSTRAINT:


These rules are applied to the data prior the data being inserted into the table.
These constraints are as follows:
i) Default constraint:

default constraints are used to provide default values for a column. The default value will be
added to all new records if no other value is specified.

Syntax:
Create table table_name (column_name1 datatype(size),column_name_2 datatype (size) default
value,---, column_name n datatype(size) );

Example:
Student(rollno,name,city)….take default value for city as pune

Create table student(rollno number(4),name varchar(15),city varchar default ‘pune’);

ii) Not Null Constraint

Not null constraint to a column is used to do not accept null values.


These values not allow a null value in a column.
We can specify not null constraints at the time of table creation as well as at the time of alter
table.

Syntax:
Create table table_name(column_name1 datatype(size),column_name2 datatype (size)
constraint constraint_name not null,…,column_name_ndatatype(size));
OR

Sou.venutaichavan polytechnic, pune Page 15


Ms. S. A. Kshirsagar SYCM
-DMS
Create table table_name (column_name1 datatype(size),column_name2 datatype(size) not
null,….,column_name_ndatatype(size));

Example:

Emp(eid take as not null,enamae,ecity,salary)


 Create table emp(eid number(4) constraint eid_n_n not
null,enamevarchar(15),ecityvarchar(17),salary number(8));
OR
Create table emp(eid number(4) not null,enamevarchar(15),ecityvarchar(15),salary varchar(8));
iii) Check constraint
It avoids entering unnecessary values to the columns. That is before doing operations it will
check condition or logical expression.

Syntax at table creation:


Create table table_name(column_name1 datatype(size) constraint constraint_name check
condition or logical expression,---, column_name n datatype(size));
Or
Create table table_name (column_name1 datatype(size) check (condition or logical
expression),---, column_name n datatype(size) );

Example:
1) create table emp( empno number(5), ename varchar2(25), salary
number(7)constraintemp_sal_ck check(salary > 5000), job varchar2(15) );
or
create table emp( empno number(5), ename varchar2(25), salary number(7) check(salary >
5000), job varchar2(15) );

2)student(rollno,name,marks,dob) …..check marks<100


Create table student(rollno number(3) primary key,namevarchar(15),marks number(3) check
(marks<100),dob date);

After table creation


Syntax:
Alter table table_name add constraint constraint_name check condition;
Example:
alter table emp add constraint emp_deptno_ck check(deptno>5);

Sou.venutaichavan polytechnic, pune Page 16


Ms. S. A. Kshirsagar SYCM
-DMS

DML COMMANDS:

DML stands for data manipulation language,These commands are used to insert,update,delete
data in database table.
DML commands are insert,delete,update.
i)insert:
we can insert data in table by 4 ways:
consider table student(rollno,name,marks,city)

1. Syntax1: syntax for insert command without defining attributes


Insert into Table_namevalues (value1,value2,…..);
e.g: insert into student values(9,’sakshi’,85,’pune’);

2. Syntax2: syntax for insert command with defining attributes


Insert into Table_name(col1,col2,.…) values (value1,value2,…..);
e.g: insert into student(rollno,name,marks,city) values (8,’sayali’,89,’mumbai’);

3. Syntax3: To insert values for selected attributes in a table.


Insert into Table_name(col1,col2) values (value1,value2);

e.g: 1) insert into student(rollno,city) values (3,’delhi’);


2)insert into student(rollno,name) values (2,’abhishek’);

4. Syntax4: To insert more than one row in a single insert query.


Insert all into Table_namevalues(value1,value2,……,valuen)
intotable_name values(value1,value2,……,valuen
.
.
.
.
intotable_namevalues(value1,value1……valuen)
select * from dual;

example: insert 3 rows:

insert all into student values(5, ‘ram’, 78, ‘solapur’)


into student values(6, ‘rushi’ ,75, ‘pune’)
into student values(7,’sanchey’,75,’mumbai’)
select * from dual;

Sou.venutaichavan polytechnic, pune Page 17


Ms. S. A. Kshirsagar SYCM
-DMS

ii) Update:
this command is used to update the column values which are inserted already.This command is
used to update or modify single or multiple rows of the table.

Syntax:
Update table_name set column_name=value where condition;
Example: change the name of rollno3 byarjunto pravin
update student set name=’pravin’ where rollno=3;

2) To change mark of ‘Ajay’ to 88 instead of 80.

Update student set mark=88 where name=’Ajay’;

iii) DELETE
Detele command is used to delete single or multiple records from table.You can delete specific
rows using where condition/clause.When all rows deleted structure of the table remains same
Syntax:

i)For deleting specific rows:


Delete from table_name where condition;

Example 1) delete from student where rollno<3;


Above example deletes the details of student table whose rollno is less than 3.

2)Delete the records of employees whose salary is more than 25000.


Ans-> delete from employee where salary > 25000;

ii)for deleting all rows:

delete from table_name;

example: delete from student;

above example deletes all rows/details of table student but table structure remains same.

2) Delete theemployeetable(i.e all details).

Delete from employee;

Sou.venutaichavan polytechnic, pune Page 18


Ms. S. A. Kshirsagar SYCM
-DMS

DCL commands
A data control language (DCL) is used to create rules,permissions and referential integrity.
It is used to control access to database by securing it.
DCL commands ibcludes following commands:

a)commit
Commit command is used to end the transaction and also make the effect permanent to the
database. That is it save the changes permanently.

Syntax:
Commit;
Or

Commit work;

Example: commit;

b)savepoint
savepoint command is used to temporarily save transaction so that you can rollback to that point
whenever required

Syntax:
Savepointsavepoint_name;
Example: Savepoint SV1;

c) Rollback:
This command restores the database to last committed state.It is also used with savepoint
command to jump toasavepoint in an ongoing transaction.
Syntax:

ROLLBACK;
Example: rollback;
OR
ROLLBACK WORK;

OR
ROLLBACK TO SAVEPOINT_NAME;
Example: update employee set salary=salary-500;
Savepoint s1;

Sou.venutaichavan polytechnic, pune Page 19


Ms. S. A. Kshirsagar SYCM
-DMS
Rollback to savepoint s1;

d)GRANT
grantcommand is used to provide access or privileges on the database objects to the users.

Syntax
GRANT privilege_nameON object_name TO user_name ;

Example:
GRANT insert,updateON emp TO pravin ;

Syntax: for providing all privileges:


Grant all on objectname to username;
Example:
grant all on student to jay;

2. REVOKE
revokecommand removes user access rights or privileges to the database objects.
Once you have granted privileges,you may to remove some or all of these privileges.
Revoke means taking authorization back from user.
The revoke command is used to denied grant given on the object.

Syntax

REVOKE privilege_nameON object_name FROM user_name;

Example
REVOKE insert, updateON emp FROM staff ;

2)denied delete privilege provided to pradip on student object


->Revoke delete on student from pradip;

3)denied insert, update, delete privilege provided to ajay on employee object.

Revoke insert,update,delete on employee from ajay;

2)For revoking all privileges:

Revoke all on object_name from user_name;

Example:
Revoke all on employee from pravin;

Sou.venutaichavan polytechnic, pune Page 20


Ms. S. A. Kshirsagar SYCM
-DMS

DQL COMMANDS:
DQL stands for data query language which includes only one command. i.e select

Select is used to display/retrieve rows and columns in table.

SYNTAX:

a)To display all rows and columns (i.e all details or all data)

select * from table_name;

example: select * from student;

b)to display all details with where clause


select * from table_name where condition;

example: select * from student where rollno<15;

c)To display specific columns from table.


Select col1,col2,col3 from table_name where condition;
Example: select rollno,name from student where rollno<15;

d)for applying more than one conditions we can use logical operators AND,OR,NOT with
select command
example: 1) select name, address from student where rollno< 3 and name= ‘pravin’;
2)selectrollno,name, address from student where rollno< 4 or name= ‘rupali’;

NOT
Example: select rollno, name where rollno not like 5;

Sou.venutaichavan polytechnic, pune Page 21


Ms. S. A. Kshirsagar SYCM
-DMS

SQL OPERATORS:
SQL operators are used to operate on value or numbers.
The SQL operators are as follows:

Consider table:
Empid Ename deptname deptno salary address
1 A Production 11 35000 Pune
2 B Manufacturer 22 20000 Mumbai
3 C Design 33 25000 Kolhapur
4 D Testing 44 15000 Delhi
5 E developing 55 60000 Pune

A) Arithmetic operators:
List and explain any 4 arithmetic operators in SQL with example.

(For each - 1 mark)


Ans: Arithmetic operators are used to perform mathematical functions in SQL.

+ (addition)
- (subtraction)
* (multiplication
/ (division)

Addition
Addition is performed using the plus (+) symbol.
Example
SELECT SALARY + 20000 “total_sal” FROM EMPLOYEE;
Meaning:
The SALARY column is added with the 20000 for each row of data .

Subtraction
Subtraction is performed using the minus (-) symbol.
e.g
SELECT SALARY –5000 “decremented_sal” FROM EMPLOYEE;
Meaning:
The SALARY column is substractedby5000 for each row of data
Multiplication
Multiplication is performed by using the asterisk (*) symbol.
Example:
SELECT SALARY * 10 FROM EMPLOYEE;

Sou.venutaichavan polytechnic, pune Page 22


Ms. S. A. Kshirsagar SYCM
-DMS
Meaning:
The SALARY column is multiplied by 10

Division
Division is performed through the use of the ‘/’ symbol.
e.g
SELECT SALARY / 10 FROM EMPLOYEE;
Meaning:
The SALARY column is divided by 10

B)Range operators:
Explain range searching operators:
(i) IN and NOT IN
(ii) BETWEEN and NOT BETWEEN.
(Each operator – 1 Mark)
Ans:
(i) IN and NOT IN
IN: x in (y,z)
This operator tests that operand x matches at least one element of the list provided.
Example: select * from employee where salaryin(35000,60000,17000);
Meaning:it displays information of employees whose salary is in 35000,60000,17000.
.

NOT IN: x not in (y,z)


This operator tests that operand x does not match any elements of list provided
Example: select * from employee where salry not in (35000,60000,17000);
Meaning:it displays information of employees whose salary is not in 35000,60000,17000.

(ii) BETWEEN and NOT BETWEEN


BETWEEN: x between y and z
Tests that operand x is greater than or equal to operand y and less than or equal to operand z.
It is used numeric and date datatype.
Example. Select * from employee where salary between 20000 and 35000;
Meaning: it will display details of employees whose salary between 20000 and 35000.

NOT BETWEEN: x not between y and z


Testes that operand x is less than operand y or greater than operand z. It test the
Range other than b to c.
Example. Select * from employee where salary not between 15000 and 25000;

Meaning: it will display details of employees whose salary between 15000 and 25000.

Sou.venutaichavan polytechnic, pune Page 23


Ms. S. A. Kshirsagar SYCM
-DMS

c)Pattern Matching Operators:


like:
like operator is used for pattern matching operator.

This is used with NOT logical operator i.eNot like

It uses special characters to match the paterne.g : ‘? ’ and ‘%’

? - indicates single character.

% - indicates any number of characters.

Example:

Select empid, deptname from employee where deptname like ‘p%’;

o/p- empid deptname

1 production

Meaning: It displaysempid , deptname whose deptname start from p i.e p on first location.

Display empid,deptname whose employee does not contain ‘a’ at 2nd location.

Ans: select empid,deptname from employee where deptname not like ‘_a%’;

o/p- empid deptname

1 production
2 design

4 testing

5 developing

Sou.venutaichavan polytechnic, pune Page 24


Ms. S. A. Kshirsagar SYCM
-DMS
Display empid,deptname whose deptname contain ‘d’ at start and ‘n’ at end location.

Ans: select empid,deptname from employee where deptname like ‘d%n’;

o/p- empid deptname

3 design

Display empid whose deptnameended with ‘s’.

Ans: select empid from department where deptname like ‘_%s’;

o/p no rows are selected

Display empid,name of the department contains ‘s’ at third location.

Select empid,deptname from employee where deptname like ‘_ _ s%’;

o/p- empid deptname

3 design

1 testing

State use of ‘%’ character in string operations.


(Explanation - 2 Marks)
Ans: ‘%’ is used in select command with ‘like’operator . ‘%’ matches all characters.
e.g. Select ename from emp where ename like ‘A%’;
In this it will give all enames having first character as ‘A’;

Sou.venutaichavan polytechnic, pune Page 25


Ms. S. A. Kshirsagar SYCM
-DMS

D) Comparision operators:
Used for comparing attribute values.

These are checking relations of attributes.

= -equal to

!= -Not equal to

>-greater than

<- lessthan

> = -greater than equal to

< = -less than equal to

<> -not equal to

Example: select empid,empname,address from employee where salary> 20000;

Note: comparision operators are used with where clause.

E) Logical Operators:
It is used with specific or combination of conditions.

There are 3 logical operators

AND –used when all the conditions must be true.

OR -used when one of the condition is to be true.

NOT – it uses negation

Examples:

Select * from employee where salary > 20000 and salary < 40000;

Select * from employee where address=’pune’ or address= ‘kolhapur’;

Select empname, salary, address from employee where address not like ‘pune’;

Sou.venutaichavan polytechnic, pune Page 26


Ms. S. A. Kshirsagar SYCM
-DMS

F)SET OPERATORS:
When we want to combine the result of 2 queries then the special type of operators are used
known as set operators.

Used to join queries and retrieve theh number of rows.

Set operators are as follows:

 Union
 Union all
 Intersect
 Minus

Consider the tables

Employee

Empid Deptno
1 101
2 102
3 103
4 104
8 105
10 106

Department

Empid deptno Deptname


1 101 Production
2 102 Manufacturer
8 103 Design
10 105 Testing
11 106 Developing
12 101 Sales

Sou.venutaichavan polytechnic, pune Page 27


Ms. S. A. Kshirsagar SYCM
-DMS
Union

Union operator selects different values of same attribute from different related tables.

e.g: select empid from employee union select empid from department;

output: empid

1
2
3
4
8
10
11
12

Union all

Union all operator combines all records from both the queries without avoiding duplicate values.

i. e. it selects all values of same attribute from different related tables without avoiding duplicate
values.

selectempid from employee union all select empid from department;

output: empid
1
2
3
4
8
10
1
2
8
10
11
12

Sou.venutaichavan polytechnic, pune Page 28


Ms. S. A. Kshirsagar SYCM
-DMS
Intersect

It selects similar values of same attribute from different related tables.

e.g. select empid from employee intersect select empid from department;

Output: empid
1
2
8
10

Minus

It performs the subtraction. i.e. values present in first table and not in second table are displayed.

e.g. select empid from employee minus select empid from department;

Output: empid
3
4

e.g. select empid from department minus select empid from employee;

Output: empid
11
12

Sou.venutaichavan polytechnic, pune Page 29


Ms. S. A. Kshirsagar SYCM
-DMS
Difference between DBMS and RDBMS
DBMS RDBMS
Old version of software to handle the Latest version of software for handling
Databases Databases
Can relate one table to another table. RDBMS can relate one database to another
database.
Data security is low as compare to Level of data security is very high as compare
RDBMS. to DBMS.
Data storage capacity is less as Data storage capacity is very high.
compare to RDBMS.
Not easy to maintain data integrity. Data integrity is one of the most important
features of RDBMS. It can be maintained
easily in RDBMS.
Works better in single user or few user Works very efficiently and give good
systems. performance over the network
All Codd‟s 12 rules are not followed. All Codd‟s 12 rules are followed

Difference between drop and truncate

Sou.venutaichavan polytechnic, pune Page 30


Ms. S. A. Kshirsagar SYCM
-DMS
QUESTIONS ON QUERIES WHICH ARE ASKED IN MSBTE EXAM:

Consider the following database schema:


Emp(Empno,Ename,job,mgr,joindate,salary,comm.,deptno).
Write the SQL queries for the following:
i) Write a query to find list of employees whose salary is not less 5000.
ii) Write a query to find list of employees whose job title is either “Manager” or
“Analyst”.
iii) Change the location of deptno 40 to Pune from Chandrapur.
iv) Display the Ename and salary of employees who earn more than Rs. 50,000
and are in deptno 10 or 30.

Ans:
i) select * from Emp where salary >= 5000;
ii) select * from Emp where job=’Manager’ or job=’Analyst’;
OR
ii) select * from Emp where job in(’Manager’ , ’Analyst’);
iii) update Emp set location=’Pune’ where deptno=40; {consider location attribute in Emp table}
iv) selectEname,Salary from Emp where salary >50000 and(deptno = 10 or deptno=30);

Consider the following database:


Employee(emp_id, emp_name, emp_city, emp_addr, emp_dept, join_date) Solve the following
query:
i) Display the names of employees in capital letters.
ii) Display the emp_id of employee who live in city Pune and Mumbai.
iii) Display the details of employees whose joining date is after ‘01-Apr.-1997’.
iv) Display the total number of employees whose dept.no.is ‘10’.

(Each correct query - 1 mark) Ans:


i) select upper(emp_name) from Employee;
ii) selectemp_id from Employee where emp_city = ‘Pune’ or emp_city = ‘Mumbai’;

OR
Select emp_id from Employee where emp_cityin(‘Mumbai‘, ‘Pune‘);
iii) select * from Employee where join_date>’01-Apr-1997’;
iv) select count(emp_id) from Employee where emp_dept = 10;

Consider following database and solve queries


emp (empno, ename, ph, sal, dept_no, comm)
(i) Change employee name ‘Rahul’ to ‘Ramesh’.
(ii) Give increment of 20% in salary to all employees.(For each command - 2 Marks)
Ans:
(i) Update emp set ename= „Ramesh‟ where ename= „Rahul‟;
(ii) Updateemp set salary=salary+(salary*20)/100;

Sou.venutaichavan polytechnic, pune Page 31


Ms. S. A. Kshirsagar SYCM
-DMS

Consider following schema:


Employee (emp_no, emp_name, dept, designation, salary, Dept_location)
Solve following queries:
(i) List all Managers in Mumbai location.
(ii) Set salary of all ‘project leaders’ to 70000/-.
(iii) List employees with having alphabet ‘A’ as second letter in their name.
(iv) Display details of those employees who work in Mumbai or Chennai.
(For each query - 1 Mark)
Ans:
i) Select * from Employee where designation= ‘Manager’ and Dept_location= ‘Mumbai’;
ii) Update Employee set salary=70000 where designation=’project leader’;
iii) Select * from Employee where emp_name like ‘_A%’;
iv) Select * from Employee where Dept_location= ‘Mumbai’orDept_location= ‘Chennai’;

Consider following schema:


depositor (cust_name, acc_no)
Borrower (cust_name, loan_no)
Solve following queries:
(i) Find customer name having savings account as well as loan account.
(ii) Find customer names having loan account but not the saving account.
(Each query – 2 Marks)
Ans:
(i) selectcust_name from depositor intersect select cust_name from borrower;
(ii) Selectcust_name from borrower minus select cust_name from depositor;

Consider the structure of student (Name, Mark, Age, Place, Phone, Birthdate).
WriteSQL queries for the following :
To list name of student who do not have phone number
Select name from student where phone is null;

To list students from Mumbai and Pune.


select * from student where place=’mumbai’ and place=’pune’;

To change mark of ‘Ajay’ to 88 instead of 80.


Update student set mark=88 where name=’ajay;

To list the students whose age is more than 12.

Select * from student where age>12;

Sou.venutaichavan polytechnic, pune Page 32


Ms. S. A. Kshirsagar SYCM
-DMS

MSBTE QUESTIONS
Explain candidate key and primary key.
Describe following keys:
(i) Primary key.
(ii) Foreign key.
(Each key – 2 Marks)
Explain Foreign Key with suitable example.
(Foreign key explanation with example – 3Marks, On delete cascade – 1 Mark)
List first four codd rules.
(For each rule - ½ Mark)
Define normalization.
(Definition - 2 marks)
Explain need of normalization and state 3NF.
(Need - 3 Marks, 3NF - 1 Mark)
List advantages of Normalization.
State and explain INF and 2NF with example.
(For 1NF - 2 Marks, For 2NF -2 Marks)
Explain 3NF with example.
(Explanation - 2 marks; example - 2 marks)
Given: Student (Roll_No, Name, Class, Total_Marks, Percentage, Grade)
normalize up to 3NF
What is SQL? State its features.
List four DML commands.
(For each command - ½Mark)
List four DDL commands. 2M
List DCL commands any four. 2M
Give the syntax and example of CREATE and RENAME Commands. 4M
Explain ALTER command with any two options. 4M
Explain Alter command. Give syntax of add and modify option.
(Explanation - 2 Marks, for each syntax - 1 Mark)
Describe commit and rollback with proper syntax.
Give the use of grant and revoke command with syntax and example.
What are the four ways to insert a record in a table?
(Each Syntax or example- 1 Mark)
Explain the difference between DROP and TRUNCATE with example.
(Any 4 valid differences – 1 Mark each OR Explanation of DROP and TRUNCATE – 2
Marks each)
How to apply NOT NULL constraint at the time of table creation? Give syntax.
(For correct syntax - 2 Marks)
Explain Domain/Business integrity constraint with syntax and example.
Explain entity integrity constraints with syntax and example. 4M
Explain Domain/Business integrity constraint with syntax and example.
How to apply NOT NULL constraint at the time of table creation? Give syntax.
Sou.venutaichavan polytechnic, pune Page 33
Ms. S. A. Kshirsagar SYCM
-DMS
(For correct syntax - 2 Marks)
State use of ‘%’ character in string operations.
(Explanation - 2 Marks)
Explain range searching operators:
(i) IN and NOT IN
(ii) BETWEEN and NOT BETWEEN.
(Each operator – 1 Mark)
List and explain any 4 arithmetic operators in SQL with example.
(For each - 1 mark)
State 4 (four) difference between DBMS and RDBMS.
(Any correct difference - 1 Mark each)

Assignment No2

Sou.venutaichavan polytechnic, pune Page 34


Ms. S. A. Kshirsagar SYCM
-DMS
• Describe :primary key and foreign key with suitable example.
• Explain DCL commands with syntax and example.
• Explain the difference between DROP and TRUNCATE with example.
• Explain DELETE and DROP Command with syntax and example.
• Define Super key & Candidate key.
• How to apply NOT NULL constraint at the time of table creation? Give syntax.
• State normalization and explain INF ,2NF,3NF with example.
• Explain range operators:
• IN and NOT IN
• BETWEEN and NOT BETWEEN.
• What are the atomic values ?
• State use of ‘%’ character in string operations.
• State and explain INF ,2NF,3NF with example.
• List and explain the types of integrity constraints in detail.
• Compare DBMS and RDBMS
• What are ways to insert a record in a table ?.
• Explain DDL and DML commands with syntax and example.
• List first four codd rules.

• What are ways to insert a record in a table ?

• Explain the set operator with help of example.

• Consider the structure of student (Name, Mark, Age, Place, Phone, Birthdate).
• WriteSQL queries for the following :
• To list name of student who do not have phone number
• To list students from Mumbai and Pune.
• To change mark of ‘Ajay’ to 88 instead of 80.
• To list the students whose age is more than 12.

Sou.venutaichavan polytechnic, pune Page 35

You might also like