RDBMS NOTES (1)
RDBMS NOTES (1)
UNIT I
Basic Concepts
What is Data?
The Raw facts are called as Data. The word “Raw” indicates that
they have not been processed.
What is Information?
The processed data is known as Information.
What is Knowledge?
1. Knowledge refers to the practical use of information.
2. Knowledge necessarily involves a personal experience.
For example: The College Database organizes the data about the
admin, staff, students and faculty etc.
Using the database, you can easily retrieve, insert, and delete the
information.
What is DBMS?
o Database Management System is a software which is used to
manage the database. For example: MySQL, Oracle, etc are a
very popular commercial database which is used in different
applications.
o DBMS provides an interface to perform various operations like
database creation, storing data in it, updating data,
creating a table in the database and more.
o It provides protection and security to the database. In case of
multiple users, it also maintains data consistency(database
must be consistent before and after transaction)
Advantages of DBMS
o Controls database redundancy: It can control data
redundancy because it stores all the data in one single database
file and that stored data is placed in the database.
o Data sharing: In DBMS, the authorized users of an organization
can share the data among multiple users.
o Easily Maintenance: It can be easily maintainable due to the
centralized nature of the database system.
o Reduce time: It reduces development time and maintenance
need.
o Backup and Recovery: It provides backup and recovery
subsystems which create automatic backup of data
from hardware and software failures and restores the data if
required.
Disadvantages of DBMS
o Cost of Hardware and Software: It requires a high speed of
data processor and large memory size to run DBMS software.
o Size: It occupies a large space of disks and large memory to run
them efficiently.
o Complexity: Database system creates additional complexity and
requirements.
o Higher impact of failure: Failure is highly impacted(strongly
affected by something) the database because in most of the
organization, all the data stored in a single database and if the
database is damaged due to electric failure or database
corruption then the data may be lost forever.
What is RDBMS?
How it works
The systems that are used to organize and maintain data files are
known as file based data systems. These file systems are used to
handle a single or multiple files and are not very efficient.
Database Approach
Data Integrity
Another important characteristic of the database approach is
data integrity. This refers to the accuracy and consistency of the
data in the database. The database approach uses a variety of
techniques to ensure data integrity, such as data validation, data
constraints, and data normalization.
Data validation is the process of checking the data entered into the
database to ensure that it is correct and consistent.
Data constraints are used to ensure that the data in the database
follows specific rules.
Data Sharing
Another important characteristic of the database approach is
data sharing. This refers to the ability of multiple users to access and
update the data in the database at the same time. The database
approach uses a variety of techniques to ensure data sharing, such as
locking and concurrency control.
events that may cause data loss. The database approach uses a
variety of techniques to ensure that data can be backed up and
recovered, such as database backups, transaction logs, and
replication.
1. External level
2. Conceptual level
3. Internal level
1. External level
The user doesn’t need to know the database schema details such
as data structure, table definition etc.
2. Conceptual level
3. Internal level
This data is stored in the external hard drives in the form of bits.
This level describes how the data actually stored in the storage
device.
Database Administrator(DBA)
A Database Administrator (DBA) is an individual person or
group of persons who is responsible for controlling, maintaining,
coordinating, and operating a database management system in an
organization.
Functions of DBA
Roles of DBA
A database administrator (DBA) plays a crucial role in the
management of a database management system (DBMS). The DBA is
responsible for the overall design, implementation, maintenance, and
security of the database.
A database administrator (DBA) is responsible for managing the
performance, integrity, and security of a database.
Types of Databases
The evolution of database systems are as follows:
Table Student
ROLL_N
O NAME ADDRESS PHONE AGE
94551234 1
1 RAM DELHI
51 8
91562531 2
3 SUJIT ROHTAK
31 0
SURES 1
4 DELHI
H 8
Important Terminologies
Attribute: Attributes are the properties that define an entity.
e.g.; ROLL_NO, NAME, ADDRESS
Relation Schema: A relation schema defines the structure of the
relation and represents the name of the relation with its attributes.
e.g.; STUDENT (ROLL_NO, NAME, ADDRESS, PHONE, and AGE) is the
relation schema for STUDENT. If a schema has more than 1 relation,
it is called Relational Schema.
Tuple: Each row in the relation is known as a tuple. The above relation contains 4 tuples, one of which is
shown as:
RA DEL 94551234 1
1
M HI 51 8
degree 5.
4.
ROLL_
NO
1
ROLL_
NO
Relation Key: These are basically the keys that are used to
identify the rows uniquely or also help in identifying tables.
Domain: Domain is the data type used by a column in a
database. This data type can be a built-in type (such as an integer
or a string) or a custom type that defines constraints on the data.
1. Primary Key
2. Candidate Key
3. Super Key
4. Foreign Key
5. Alternate Key
6. Composite Key
1. Primary key
o It is the first key used to identify one and only one instance of an
entity uniquely. An entity can contain multiple keys, as we saw in
the PERSON table. The key which is most suitable from those lists
becomes a primary key.
o In the EMPLOYEE table, ID can be the primary key since it is
unique for each employee. In the EMPLOYEE table, we can even
select License_Number and Passport_Number as primary keys
since they are also unique.
o For each entity, the primary key selection is based on
requirements and developers.
2. Candidate key
o A candidate key is an attribute or set of attributes that can
uniquely identify a tuple.
o Except for the primary key, the remaining attributes are
considered a candidate key. The candidate keys are as strong as
the primary key.
5. Alternate key
6. Composite key
Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the
quality of information.
o Integrity constraints ensure that the data insertion, updating, and
other processes have to be performed in such a way that data
integrity is not affected.
Example:
Example:
3. Referential Integrity Constraints
o A referential integrity constraint is specified between two tables.
o In the Referential integrity constraints, if a foreign key in Table 1
refers to the Primary Key of Table 2, then every value of the
Foreign Key in Table 1 must be null or be available in Table 2.
Example:
4. Key constraints
o Keys are the entity set that is used to identify an entity within its
entity set uniquely.
o An entity set can have multiple keys, but out of which one key will
be the primary key. A primary key can contain a unique and null
value in the relational table.
Example:
Relational Algebra / Relational Operations
Relational algebra is a procedural query language. It gives a
step by step process to obtain the result of the query. It uses operators
to perform queries.
1. Select Operation
o The select operation selects tuples that satisfy a given predicate.
o It is denoted by sigma (σ).
Notation: σ p(r)
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
Input:
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
3. Union Operation
o Suppose there are two tuples R and S. The union operation
contains all the tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.
Notation: R ∪ S
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
2) BORROW Relation
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
Input:
1)
∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
4. Set Intersection
o Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in both R & S.
o It is denoted by intersection ∩.
Notation: R ∩ S
Input:
Output:
CUSTOMER_NAM
E
Smith
Jones
5. Set Difference
o Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).
Notation: R - S
Input:
Output:
CUSTOMER_NA
ME
Jackson
Hayes
Willians
Curry
6. Cartesian product
o The Cartesian product is used to combine each row in one table
with each row in the other table. It is also known as a cross
product.
o It is denoted by X.
Notation: E X D
1 Smith A
2 Harry C
3 John B
2) DEPARTMENT Relation
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
1) EMPLOYEE X DEPARTMENT
Output:
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
7. Rename Operation
E-R Model
Components of ER Diagram
1. Entity
Weak Entity
2. Attribute
2) Composite Attribute
For example, a student can have more than one phone number.
4) Derived Attribute
1) One-to-One Relationship
For example, A female can marry to one male, and a male can marry
to one female.
2) One-to-many relationship
When only one instance of the entity on the left, and more than
one instance of an entity on the right associates with the relationship
then this is known as a one-to-many relationship.
For example, Scientist can invent many inventions, but the invention
is done by the only specific scientist.
3) Many-to-one relationship
When more than one instance of the entity on the left, and only
one instance of an entity on the right associates with the relationship
then it is known as a many-to-one relationship.
For example, Student enrolls for only one course, but a course can
have many students.
4) Many-to-many relationship
When more than one instance of the entity on the left, and more
than one instance of an entity on the right associates with the
relationship then it is known as a many-to-many relationship.
For example, Employee can assign by many projects and project can
have many employees.
Defining relationship for College Database
Conversion of E-R Diagram to Relational Database
Conversion of an E-R diagram into a relational model is required
because E-R diagrams represent the conceptual level of the
database design while the relational model represents the logical
level. The relational models can be easily implemented using RDBMS
like Oracle, MySQL, etc.
Consider the following E-R diagram in the figure below. The E-R
diagram consists of Employee as an entity set
and EmpNo, EmpName, and Salary as its attributes. Here we map
entity set into a relation Employee and attributes of an entity set will
become the attributes inside the table. The key attribute will become
the primary key of the table.
Entity set with a composite attribute
If we include the PhoneNo in the table with all other attributes, then
for a single-valued tuple we may have multiple entries as shown in the
table below
However, to avoid duplicate values in the table, we split the attributes
into two different relations as shown in the figure below
Likewise, we map the entity set into the relation in a relational model,
we can also map a relationship set into a relation. The attribute of such
a relation includes key attributes of the participating relations. The
attributes are will become a foreign key.
For example, in the figure given below, there are two entity
sets Employee and Department. These entity sets are participating in a
relationship works in. The relationship set is converted into relation
with attributes EmpNo from Employee relation, D_id
from Department relation and Since, the attribute of the relationship
set itself.
UNIT II
Dependency
Dependency is a relation between two or more attributes.
Functional Dependency
Transitive Dependency
Multivalued Dependency
Partial Dependency
Functional Dependency
P -> Q
<Employee>
Transitive Dependency
When an indirect relationship causes functional dependency it is called
Transitive Dependency.
Multivalued Dependency
When existence of one or more rows in a table implies one or more
other rows in the same table, then the Multi-valued dependencies
occur.
->->
For our example:
P->->QQ->->R
In the above case, Multivalued Dependency exists only if Q and R are
independent attributes.
Partial Dependency
Partial Dependency occurs when a nonprime attribute is
functionally dependent on part of a candidate key.
The 2nd Normal Form (2NF) eliminates the Partial Dependency. Let us
see an example −
<StudentProject>
What is Normalization?
EMPLOYEE table:
14 John 7272826385, UP
9064738238
14 John 7272826385 UP
14 John 9064738238 UP
Example: Let's assume, a school can store the data of teachers and
the subjects they teach. In a school, a teacher can teach more than
one subject.
TEACHER table
25 Chemistry 30
25 Biology 30
47 English 35
83 Math 38
83 Computer 38
In the given table, non-prime attribute (attributes which are not part
of any candidate key) TEACHER_AGE is dependent on TEACHER_ID
which is a proper subset of a candidate key. That's why it violates the
rule for 2NF.
TEACHER_DETAIL table
TEACHER_ID TEACHER_AGE
25 30
47 35
83 38
TEACHER_SUBJECT table
TEACHER_ID SUBJECT
25 Chemistry
25 Biology
47 English
83 Math
83 Computer
1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some
candidate key.
Example:
EMPLOYEE_DETAIL table
EMPLOYEE table
EMPLOYEE_ZIP table
201010 UP Noida
02228 US Boston
60007 US Chicago
06389 UK Norwich
462007 MP Bhopal
Example: Let's assume there is a company where employees work in more than one
department.
EMPLOYEE table
1.EMP_ID → EMP_COUNTRY
2.EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
The table is not in BCNF because neither EMP_DEPT nor EMP_ID alone
are keys.
EMP_COUNTRY table
EMP_ID EMP_COUNTRY
264 India
264 India
EMP_DEPT table
EMP_DEPT DEPT_TYPE EMP_DEPT_NO
EMP_DEPT_MAPPING table
EMP_ID EMP_DEPT
D394 283
D394 300
D283 232
D283 549
Functional dependencies:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
Candidate keys:
Now, this is in BCNF because left side part of both the functional
dependencies is a key.
Fourth normal form (4NF)
o A relation will be in 4NF if it is in Boyce Codd normal form and has
no multi-valued dependency.
o For a dependency A → B, if for a single value of A, multiple values
of B exists, then the relation will be a multi-valued dependency.
Example:
STUDENT table
21 Computer Dancing
21 Math Singing
34 Chemistry Dancing
74 Biology Cricket
59 Physics Hockey
The given STUDENT table is in 3NF, but the COURSE and HOBBY are
two independent entity. Hence, there is no relationship between
COURSE and HOBBY.
So to make the above table into 4NF, we can decompose it into two
tables:
STUDENT_COURSE table
STU_ID COURSE
21 Computer
21 Math
34 Chemistry
74 Biology
59 Physics
STUDENT_HOBBY table
STU_ID HOBBY
21 Dancing
21 Singing
34 Dancing
74 Cricket
59 Hockey
o In this method, the new record is always inserted at the file's end,
and then it will sort the sequence in ascending or descending
order. Sorting of records is based on any primary key or any other
key.
o In the case of modification of any record, it will update the record
and then sort the file, and lastly, the updated record is placed in
the right place.
Suppose we have five records R1, R3, R6, R4 and R5 in a heap and
suppose we want to insert a new record R2 in a heap. If the data block
3 is full then it will be inserted in any of the database selected by the
DBMS, let's say data block 1.
If any record has to be retrieved based on its index value, then the
address of the data block is fetched and the record is retrieved from
the memory.
Pros of ISAM
o In this method, each record has the address of its data block,
searching a record in a huge database is quick and easy.
o This method supports range retrieval and partial retrieval of
records. Since the index is based on the primary key values, we
can retrieve the data for the
given range of value. In the same way, the partial value can also
be easily searched, i.e., the student name starting with 'JA' can be
easily searched.
Cons of ISAM
o This method requires extra space in the disk to store the index
value.
o When the new records are inserted, then these files have to be
reconstructed to maintain the sequence.
o When the record is deleted, then the space used by it needs to be
released. Otherwise, the performance of the database will slow
down.
In this method, there is no effort for searching and sorting the entire
file. In this method, each record will be stored randomly in the
memory.
Indexing
Indexing is a data structure technique which allows you to
quickly retrieve records from a database file.
An Index is a small table having only two columns.
Index structure:
Indexes can be created using some database columns.
o The first column of the database is the search key that contains
values of the primary key are stored in sorted order so that the
Types of Indexes
Primary Index
Primary Index is an ordered file which is fixed length size with two
fields. The first field is the same a primary key and second, filed is
pointed to that specific data block. In the primary Index, there is
always one to one relationship between the entries in the index table.
Dense Index
Sparse Index
Dense Index
It is an index record that appears for only some of the values in the
file. Sparse Index helps you to resolve the issues of dense Indexing in
DBMS. In this method of indexing technique, a range of index
columns stores the same data block address, and when data needs to
be retrieved, the block address will be fetched.
However, sparse Index stores index records for only some search-key
values. It needs less space, less maintenance overhead for insertion,
and deletions but It is slower compared to the dense Index for locating
records.
Here, you can have a secondary index in DBMS for every search-key.
Index record is a record point to a bucket that contains pointers to all
the records with their specific search-key value.
Clustering Index
Example:
UNIT III
What is SQL?
Why SQL?
SQL is widely popular because it offers the following
advantages −
SQL Operators
1) Arithmetic operators
2) Comparison operators
3) Logical operators
1) Arithmetic operators
We can use various Arithmetic Operators on the data stored in the
tables.
+ [Addition]
- [Subtraction]
/ [Division]
* [Multiplication]
% [Modulus]
Example
SELECT employee_id, employee_name, salary, salary + 100
AS "salary + 100" FROM addition;
Output
employee_na
employee_id me salary salary+100
2 rr 55000 55100
2) Comparison operators
= Equals to
<> Not Equal to
Example
Output
3) Logical Operators
In SQL, the AND & OR operators are used for filtering the data and
getting precise results based on conditions. The
SQL AND & OR operators are also used to combine multiple
conditions.
AND Operator:
This operator displays only those records where both the conditions
condition1 and condition2 evaluates to True.
Syntax:
OR Operator:
This operator displays the records where either one of the conditions
condition1 and condition2 evaluates to True. That is, either condition1
is True or condition2 is True.
Syntax:
If suppose we want to fetch all the records from the Student table
where Age is 18 and ADDRESS is Delhi. then the query will be:
Query:
SELECT * FROM Student WHERE Age = 18 AND ADDRESS =
'Delhi';
Output:
XXXXXXXX 1
1 Ram Delhi
XX 8
ROLL_ NAM ADDRE
NO E SS PHONE Age
SURE XXXXXXXX 1
4 Delhi
SH XX 8
Take another example, to fetch all the records from the Student
table where NAME is Ram and Age is 18.
Query:
Output:
XXXXXXXX 1
1 Ram Delhi
XX 8
To fetch all the records from the Student table where NAME is Ram
or NAME is SUJIT.
Query:
SELECT * FROM Student WHERE NAME = 'Ram' OR NAME = 'SUJIT';
Output:
XXXXXXXX 1
1 Ram Delhi
XX 8
ROHTA XXXXXXXX 2
3 SUJIT
K XX 0
ROHTA XXXXXXXX 2
3 SUJIT
K XX 0
Types of Languages
Syntax:
CREATE table table_name
columnN datatype(size));
CustomerName VARCHAR2(50),
LastName VARCHAR2(50),
Country VARCHAR(50),
Age NUMBER(2),
Phone NUMBER(10));
Output:
DESCRIBE Command
As the name suggests, DESCRIBE is used to describe something. Since
in a database, we have tables, that’s why do we
use DESCRIBE or DESC(both are the same) commands to describe
the structure of a table.
Syntax:
DESCRIBE Table_name;
OR
DESC Table_name;
Example:
DESC users_info;
Output
Name Null? Type
------------------------------ -------- ----------------------------
Example
Output
The "Persons" table will now look like this:
The following SQL deletes the "DateOfBirth" column from the "Persons"
table:
Example
DROP
DROP is used to delete a whole table(Records with structure)
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE Persons;
TRUNCATE
The TRUNCATE TABLE Command is used to delete the data inside a
table, but not the table itself.
Syntax:
Example:
RENAME
RENAME Command is used to change the Name of the existing
table.
Syntax:
Example:
Insert Command
To add data to the table, we use INSERT INTO command, the syntax
is as shown below:
Syntax:
//Below query adds data in specific column, (like Column1=Value1)//
Example Query
This query will add data in the table named Subject
Output:
If an existing table was used to create a new table, by default the new
table would be populated with the existing values from the old table.
Syntax:
CREATE TABLE new_table_name AS
FROM existing_table_name ;
Query:
CREATE TABLE SubTable AS
FROM customer;
Output:
UPDATE Command
UPDATE Command is used to modify the existing records in a
table. It only modifies the data present in a table without affecting the
table's structure.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following query will update the ADDRESS for a customer whose
ID number is 6 in the table.
UPDATE CUSTOMERS
WHERE ID = 6;
Output
(1 row affected)
Verification
To verify whether the records of the table are modified or not, use the
following SELECT query below −
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
DELETE Command
Syntax
DELETE FROM table_name [WHERE condition];
Example1
Output
Example2
Output
WHERE clause is used to prevent the deletion of all the rows in the
table, If you don't use the WHERE clause you might loss all the
rows.
Syntax1:
SELECT column1,column2 FROM table_name;
Example:
Syntax2:
SELECT * FROM table_name;
1. COMMIT
2. ROLLBACK
3. SAVEPOINT
1. COMMIT :
This command is used to save the data permanently.
Whenever we perform any of the DML command like -INSERT,
DELETE or UPDATE, these can be rollback if the data is not stored
permanently. So in order to be at the safer side COMMIT command is
used.
Syntax:
commit;
2. ROLLBACK :
This command is used to get the data or restore the data to the last
savepoint or last committed state. If due to some reasons the data
inserted, deleted or updated is not correct, you can rollback the data
to a particular savepoint or if savepoint is not done, then to the last
committed state.
Syntax:
rollback;
3. SAVEPOINT :
This command is used to save the data at a particular point
temporarily, so that whenever needed can be rollback to that
particular point.
Syntax:
Savepoint A;
John 79
Jolly 65
Shuz
70
an
UPDATE STUDENT
COMMIT;
ROLLBACK;
By using this command you can update the record and save it
permanently by using COMMIT command.
Mar
Name ks
John 79
Mar
Name ks
Sherlo
65
ck
Shuza
70
n
UPDATE STUDENT
Mar
Name ks
John 79
Sherlo
65
ck
Shuza
70
n
Now if ROLLBACK is performed on the above table:
rollback;
After Rollback:
Mar
Name ks
John 79
Jolly 65
Shuz
70
an
Commit;
UPDATE NAME
SAVEPOINT A;
Savepoint B;
Savepoint C;
Nam Mar
e ks
John 79
Jolly 65
Ross
70
ie
Jack 95
Zack 76
Brun
85
o
Now if we Rollback to Savepoint B:
Rollback to B;
Nam Mar
e ks
John 79
Jolly 65
Ross
70
ie
Jack 95
Zack 76
Rollback to A;
Nam Mar
e ks
John 79
Jolly 65
Ross 70
Nam Mar
e ks
ie
Jack 95
WHERE Clause
Basic Syntax
Parameter Explanation:
Example
);
Following query inserts values into this table using the INSERT
statement −
The following query is an example which would fetch the ID, Name
and Salary fields from the CUSTOMERS table created above using
the SELECT statement, where the salary is greater than 2000 −
FROM CUSTOMERS
Output
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
Example
In the following query we are trying to update the age of all the
customers whose age is ‘25’ and updating it to ‘30’ using UPDATE
statement −
Output
(2 rows affected)
Verification
To verify if the changes are reflected in the tables, we can use SELECT
statement to print the tables as shown in the following query −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 30 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 30 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
As we can see in the above table, the AGE of ‘Khilan’ and ‘Chaitali’ has
been updated to ‘30’.
Example
Output
Output
+----+--------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+--------+-----+-----------+----------+
Example
Following is the query, which would display all the records where the
name starts with K and is at least 4 characters in length −
Output
+----+---------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+---------+-----+---------+---------+
WHERE Clause with AND, OR operators
We can use AND and OR operators together in SQL to combine multiple
conditions in a WHERE clause to filter rows that meets the specified
criteria. AND operator will make sure only those rows are filtered that
satisfy all the conditions and OR operator will filtered records that
satisfy any one condition specified. However, this is only used when
specifying one condition is not enough to filter all the required rows.
Example
In the following query, we are trying to retrieve all rows from the
"CUSTOMERS" table based on some conditions. The parentheses
control the order of evaluation so that the OR operator is applied first,
followed by the AND operator −
Output
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+
ORDER BY Clause / Statement
Note −
Syntax
Example
);
Following query inserts values into this table using the INSERT
statement −
insert INTO CUSTOMERS VALUES(1, 'Ramesh', 32, 'Ahmedabad',
2000.00);
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
In the following query we are trying to sort the result in an ascending
order by the name and the salary of the customers −
Output
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
Example
The following query sorts the result in the descending order by the
name of the customers −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+
In other words, the table will be sorted first by sorting the first
column specified, then the second column, and so on.
Example
In the following query, we are trying to retrieve all records from the
CUSTOMERS table and sorts them first by their address in ascending
order, and then by their salary in descending order −
Output
Example
Now, we are trying to retrieve all records from the CUSTOMERS table
where the age of the customer is 25 and sort them in descending order
based on their name −
WHERE AGE = 25
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+
Syntax
Following is the syntax of using the TOP clause with the ORDER BY
clause in SQL −
Example
FROM CUSTOMERS
ORDER BY NAME;
Output
+----------+
| SALARY |
+----------+
| 6500.00 |
| 8500.00 |
| 2000.00 |
| 1500.00 |
+----------+
GROUP BY Clause/Statement
Features
clause.
FROM table_name
WHERE condition
Explanation:
1. function_name: Name of the function used for example, SUM() ,
AVG().
2. table_name: Name of the table.
3. condition: Condition used.
Employee Table:
CREATE TABLE emp (
name VARCHAR(50),
sal DECIMAL(10,2),
age INT
);
Insert some random data into a table and then we will perform some
operations in GROUP BY.
Query:
INSERT INTO emp (emp_no, name, sal, age) VALUES
Output:
Student Table:
Query:
CREATE TABLE student
( name VARCHAR(50),
year INT,
subject VARCHAR(50));
('Alice', 1, 'Mathematics'),
('Bob', 2, 'English'),
('Charlie', 3, 'Science'),
('David', 1, 'History'),
('Emily', 2, 'Art'),
Output:
Group By single column means, placing all the rows with the same
value of only that particular column in one group. Consider the query
as shown below:
Query:
SELECT NAME, SUM(SALARY) FROM emp
GROUP BY NAME;
As you can see in the above output, the rows with duplicate
NAMEs are grouped under the same NAME and their corresponding
SALARY is the sum of the SALARY of duplicate rows. The SUM()
function of SQL is used here to calculate the sum.
FROM Student
As you can see in the above output the students with both the
same SUBJECT and YEAR are placed in the same group. And those
whose only SUBJECT is the same but not YEAR belong to different
groups. So here we have grouped the table according to two columns
or more than one column.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
Explanation:
1. function_name: Name of the function used for example, SUM() ,
AVG().
2. table_name: Name of the table.
3. condition: Condition used.
Example:
SELECT NAME, SUM(sal) FROM Emp
GROUP BY name
HAVING SUM(sal)>3000;
Output:
As you can see in the above output only one group out of the
three groups appears in the result set as it is the only group where
sum of SALARY is greater than 3000. So we have used the HAVING
clause here to place this condition as the condition is required to be
placed on groups not columns.
Important Rules:
o A subquery can be placed in a number of SQL clauses like
WHERE clause, FROM clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE
statements along with the operators like =, <, >, >=, <=, IN,
BETWEEN, etc.
o A subquery is a query within another query. The outer query is
known as the main query, and the inner query is known as a
subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But
GROUP BY command can be used to perform the same function as
ORDER BY command.
Syntax
1.SELECT column_name
2.FROM table_name
3.WHERE column_name expression operator
4.( SELECT column_name from table_name WHERE ... );
Example
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
Syntax:
Example:
Syntax:
1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);
Example:
1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);
This would impact three rows, and finally, the EMPLOYEE table would
have the following records.
4 Alina 29 UK 1625.0
0
Syntax
This would impact three rows, and finally, the EMPLOYEE table would
have the following records.
1 John 20 US 2000.00
JOINS
Types of JOINS
Student
StudentCourse
INNER JOIN
The INNER JOIN keyword selects all rows from both the tables
as long as the condition is satisfied. This keyword will create the
result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be the same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
ON table1.matching_column = table2.matching_column;
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:
LEFT JOIN
This join returns all the rows of the table on the left side of the
join and matches rows for the table on the right side of the
join. For the rows for which there is no matching row on the right
side, the result-set will contain null. LEFT JOIN is also known as
LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
ON table1.matching_column = table2.matching_column;
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both
are the same.
Example Queries(LEFT JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of
the table on the right side of the join and matching rows for the table
on the left side of the join. For the rows for which there is no matching
row on the left side, the result-set will contain null. RIGHT JOIN is also
known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
ON table1.matching_column = table2.matching_column;
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN,
both are the same.
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both
tables. For the rows for which there is no matching, the result-set will
contain NULL values.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
ON table1.matching_column = table2.matching_column;
Example Queries(FULL JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
COURSE
NAME _ID
HARSH 1
PRATIK 2
RIYANK
2
A
DEEP 3
SAPTAR
1
HI
COURSE
NAME _ID
DHANR
NULL
AJ
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
the tables being joined. A natural join returns all rows by matching
Both tables must have atleast one common column with same
result.
Example:
Employee
1 Ram 10
2 Jon 30
3 Bob 50
Department
Dept_ Dept_na
id me
10 IT
30 HR
40 TIS
1 Ram 10 10 IT
2 Jon 30 30 HR
Department
Employee data data
VIEWS
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
Syntax:
Query:
Just like table query, we can query the view to view the data.
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
Query:
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
Syntax
Example:
Types of Views:
Sequences in SQL
The statement specifies the name of the sequence, the starting value,
the increment, and other properties of the sequence.
Syntax
Here,
First of all, let us try to create a table “STUDENTS” using the following
query −
SQL> CREATE TABLE STUDENTS (ID INT, NAME CHAR(20), AGE INT NOT
NULL);
Now, let us insert some records in the table using INSERT statements
as shown in the query below −
+------+-----------+------+
| ID | NAME | AGE |
+------+-----------+------+
| NULL | Dhruv | 20 |
| NULL | Arjun | 23 |
| NULL | Dev | 25 |
| NULL | Riya | 19 |
| NULL | Aarohi | 24 |
| NULL | Lisa | 20 |
| NULL | Roy | 24 |
+------+-----------+------+
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 5
CYCLE;
Output
When you execute the above query, the output is obtained as follows −
Verification
+------+-----------+------+
| ID | NAME | AGE |
+------+-----------+------+
| 1| Dhruv | 20 |
| 2| Arjun | 23 |
| 3| Dev | 25 |
| 4| Riya | 19 |
| 5| Aarohi | 24 |
| 1| Lisa | 20 |
| 2| Roy | 24 |
+------+-----------+------+
UNIT IV
X's Account
1. Open_Account(X)
2. Old_Balance = X.balance
3. New_Balance = Old_Balance - 800
4. X.balance = New_Balance
5. Close_Account(X)
Y's Account
1. Open_Account(Y)
2. Old_Balance = Y.balance
3. New_Balance = Old_Balance + 800
4. Y.balance = New_Balance
5. Close_Account(Y)
Operations of Transaction:
1. R(X);
2. X = X - 500;
3. W(X);
o The first operation reads X's value from database and stores it in
a buffer.
o The second operation will decrease the value of X by 500. So
buffer will contain 3500.
o The third operation will write the buffer's value to the database.
So X's final value will be 3500.
Properties of Transactions
Atomicity − ensures that all operations within the work unit are
completed successfully. Otherwise, the transaction is aborted at
the point of failure and all the previous operations are rolled back
to their former state.
Consistency − ensures that the database properly changes
states upon a successfully committed transaction.
Isolation − enables transactions to operate independently of and
transparent to each other.
Durability − ensures that the result or effect of a committed
transaction persists in case of a system failure.
Concurrent Transactions
Example: Suppose that two ticket agents are dealing with the
seat booking system of a flight. If both agents book last
available seat in the flight, it would result in the overbooking or
double booking of that seat. This leaves the database in an
inconsistent state.
To avoid this inconsistency, some type of isolation should be
enforced among the transactions so that they may affect each
other –
Locking Protocol
1. Shared lock:
2. Exclusive lock:
o In the exclusive lock, the data item can be both reads as well as
written by the transaction.
o This lock is exclusive, and in this lock, multiple transactions do
not modify the same data simultaneously.
Two-Phase Locking(2PL)
T1 T2
1 lock-S(A)
2 lock-S(A)
3 lock-X(B)
4 ……. ……
5 Unlock(A)
6 Lock-X(C)
7 Unlock(B)
8 Unlock(A)
9 Unlock(C)
10 ……. ……
Serializable Schedules
What is a Schedule?
Serializable Schedule
Deadlock Detection
Wait-Die scheme
Let's assume there are two transactions Ti and Tj and let TS(T) is a
timestamp of any transaction T. If T2 holds a lock by some other
transaction and T1 is requesting for resources held by T2 then the
following actions are performed by DBMS:
Kinds of Failures
1. Transaction failure
2. System crash
3. Disk failure
1. Transaction failure
Database Errors
Backup and Recovery Techniques
It is imperative to have a backup of the database in case the original is
corrupted or lost because of any reason. Using this backup, the
database can be recovered as it was before the failure.
Full Backup - This method takes a lot of time as the full copy of
the database is made including the data and the transaction
records.
Transaction Log - Only the transaction logs are saved as the
backup in this method. To keep the backup file as small as
possible, the previous transaction log details are deleted once a
new backup record is made.
Differential Backup - This is similar to full backup in that it
stores both the data and the transaction records. However only
that information is saved in the backup that has changed since the
last full backup. Because of this, differential backup leads to
smaller files.
Recovery Techniques
There are four different recovery techniques are available in the
Database.
1. Mirroring
2. Recovery using Backups
3. Recovery using Transaction Logs
4. Shadow Paging
Mirroring:
Immediate Backup
Archival Backup
Immediate Backup:
Immediate Backup are kept in a floppy disk, hard disk or magnetic
tapes. These come in handy when a technical fault occurs in the
primary database such as a system failure, disk crash, or network
failure. Damage due to virus attacks repaired using the immediate
backup.
Archival Backup:
Archival Backups are kept in mass storage devices such as magnetic
tape, CD-ROMs, Internet Servers etc. They are very useful for
recovering data after a disaster such as fire, earthquake, flood etc.
Archival Backup should be kept at a different site other than where the
system is functioning. Archival Backup at a separate place remains
safe from thefts and international destruction by user staff.
Shadow Paging:
These systems can use for data recovery instead of using
transaction logs. In Shadow Paging, a database is divided into
several fixed-sized disk pages, say n, thereafter a current directory
creates. It has n entries with each entry pointing to a disk page in the
database. the current directory transfer to the main memory.
Database Security
Database Security means keeping sensitive information safe and
prevent the loss of data. Security of data base is controlled by
Database Administrator (DBA).
The following are the main control measures are used to
provide security of data in databases:
1. Authentication
2. Access control
3. Inference control
4. Flow control
5. Database Security applying Statistical Method
6. Encryption
1. Authentication :
Authentication is the process of confirmation that whether the
user log in only according to the rights provided to him to perform
the activities of data base. A particular user can login only up to his
privilege but he can’t access the other sensitive data. The privilege
of accessing sensitive data is restricted by using Authentication.
By using these authentication tools for biometrics such as retina
and figure prints can prevent the data base from
unauthorized/malicious users.
2. Access Control :
The security mechanism of DBMS must include some provisions for
restricting access to the data base by unauthorized users. Access
control is done by creating user accounts and to control login
process by the DBMS. So, that database access of sensitive data is
possible only to those people (database users) who are allowed to
access such data and to restrict access to unauthorized
persons. The database system must also keep the track of all
operations performed by certain user throughout the entire login
time.
3. Inference Control :
This method is known as the counter measures to statistical
database security problem. It is used to prevent the user from
completing any inference channel. This method protect sensitive
information from indirect disclosure.
Inferences are of two types, identity disclosure or attribute
disclosure.
4. Flow Control :
This prevents information from flowing in a way that it reaches
unauthorized users. Channels are the pathways for information to
flow implicitly in ways that violate the privacy policy of a company
are called convert channels.
5. Database Security applying Statistical Method :
Statistical database security focuses on the protection of
confidential individual values stored in and used for statistical
purposes and used to retrieve the summaries of values based on
categories. They do not permit to retrieve the individual
information.
This allows to access the database to get statistical information
about the number of employees in the company but not to access
the detailed confidential/personal information about the specific
individual employee.
6. Encryption :
This method is mainly used to protect sensitive data (such as credit
card numbers, OTP numbers) and other sensitive numbers. The
data is encoded using some encoding algorithms.
An unauthorized user who tries to access this encoded data will
face difficulty in decoding it, but authorized users are given
decoding keys to decode data.
Authorization
Authorization is a privilege provided by the Database
Administer. Users of the database can only view the contents they
are authorized to view. The rest of the database is out of bounds to
them.
1. Flexibility/Tunability
One of the main reasons for the need for distributed systems is its
Tunability. With the complex nature of organizations and various
transactions that happen every second, it becomes important that the
servers and the application are flexible enough to accommodate their
ever-changing needs without hampering the overall functions of the
database management system. For example, a machine that houses a
web server would service a high volume of small transactions whereas
a database server with a data warehouse would serve the low volume
of large or complex transactions. In distributed database systems
these functions are mutually separated and therefore can be
configured by end-users and developers as per their requirements.
2. Fault Tolerance
Imagine a system where the applications and the server are physically
located on the same computer or system and one of the components
fails and disrupts the entire system! With DDMS since the server and
application are located on a network of computers, failure of a
component doesn’t affect the system as a whole and thus becomes
fault-tolerant which is extremely important especially when used by
large organizations.
3. Security
Since the components of a DDMS are completely independent of each
other both in working and location if one of the components gets
compromised it wouldn’t affect the system as a whole and this greatly
increases the security of the database system.
4. Scalability
As an organization grows, so does its data and need for a better
database management system. With distributed systems,
organizations can scale their existing network of the system easily and
maneuver the system as per their needs.
5. Cost
It costs less to create a network of smaller computers spread across
geographies than a single large computer.
Types:
1. Homogeneous Database:
In a homogeneous database, all different sites store database
identically. The operating system, database management system, and
the data structures used – all are the same at all sites. Hence, they’re
easy to manage.
2. Heterogeneous Database:
In a heterogeneous distributed database, different sites can use
different schema and software that can lead to problems in query
processing and transactions. Also, a particular site might be
completely unaware of the other sites. Different computers may use a
different operating system, different database application. They may
even use different data models for the database. Hence, translations
are required for different sites to communicate.
Data Replication
Advantages :
As the data is stored close to the usage site, the efficiency of the
database system will increase
Local query optimization methods are sufficient for some queries as
the data is available locally
In order to maintain the security and privacy of the database
system, fragmentation is advantageous
Disadvantages :
Access speeds may be very high if data from different fragments
are needed
If we are using recursive fragmentation, then it will be very
expensive
Horizontal fragmentation
Vertical fragmentation
Mixed or Hybrid fragmentation
The different structures for two tier and three tier are given as
follows −
Two - Tier Client/Server Structure
The two-tier architecture primarily has two parts, a client tier and a
server tier.The client tier sends a request to the server tier and the
server tier responds with the desired information.
The Three - Tier structure provides much better service and fast
performance.
The structure can be scaled according to requirements without
any problem.
Data security is much improved in the three tier structure.
INDIRA PRIYADARSHINI GOVERNMENT DEGREE COLLEGE FOR WOMEN,
NAMPALLY - HYDERABAD - 500001
(An Autonomous college of Osmania University)
Re-Accredited by NAAC with ‘A’ Grade
B.Com (CA) II Year Examination
Semester – III
Subject: Computer Applications
RELATIONAL DATABASE MANAGEMENT SYSTEM
Practical Question Bank
H.P.W: 4 Credits: 1
Max Marks: 25M
1. Write sql query to display the name of suppliers who supply Processors and whose city is Delhi.
2. Write sql query to increase the price of Keyboard by 200.
3. Write sql query to display supplier numbers, Suplier names and itemprice for suppliers in delhi in the
ascending order of itemprice.
4. Write sql query to add a new column called CONTACTNO.
5. Write sql query to delete the record whose itemprice is the lowest of all the items supplied .
6. Create a view on the table which displays only supplier numbers and supplier names.
B. Below are the details of Employees working for a software Company. (For questions from 11 to20)
Create the table called EmpDetails with the below mentioned details.
Eid Ename DOB Designation Salary DOJ
(Primary Key)
E101 Suma 29-Dec-89 Designer 20000 01-Apr-10
E102 Amit 10-Jan-95 Programmer 25000 18-Feb-18
E103 Payal 15-Aug-85 Tester 35000 13-Jun-11
E104 Kiran 20-Apr-90 Programmer 40000 7-Mar-14
E105 Meenal 29-May-83 DBA 50000 9-Dec-11
E106 Sheila 1-May-70 Analyst 60000 25-Sep-18
E107 Swamy 13-Jan-85 Programmer 45000 14-Feb-16
E108 Sushma 22-Dec-76 DBA 45000 31-Jan-12
7. Write sql query to display all the employees whose designation is Programmer.
8. Write sql query to display all the employees whose name ends with ‘a’.
9. Write sql query to display the total salary of all the employees whose designation is
programmer.
10. Write sql query to display all the employee names in upper case.
11. Write sql query to display the details of the employee with highest experience.
12. Write sql query to increase the salaries of employees by 5000 whose designation is DBA.
C. Create the two tables as shown below with the given constraints: (for questions 21 to 30) Table name:
Employee Tablename: Department
Constraints: Eid is Primary key and DeptId is foreign key Constraints: DeptId Primary key Salary
should not be less than 10000 and Dname is NOT NULL
13. Write sql query to display the fields Eid, Ename and Dname.
14. Write sql query to sort the employee table in the descending order of salaries.
15. Write sql query to list all the job designations in the employee table without repetitions.
16. Write sql query to display all the employees who joined in the year 2011.
17. Write sql query to display all the employees whose salary is between 30000 and 45000.
18. Write sql query to display all the employee details along with their work experience in the company till
current date.
D. Below are the details of Students enrolled in various course of B.Com (For questions from 31 to 40) Create
the table called Student with the below mentioned details.
Sid Sname DOB State Gender Category Course
(Primary Key)
1001 Neha 29-Dec-02 Telangana F Gen Comp
1002 Arun 10-Jan-02 Telangana M OBC Honors
1003 Payal 15-Aug-01 Maharashtra F Gen Appl
1004 Amrita 20-Apr-02 Karnataka F OBC Honors
1005 Pavan 29-May-03 AndhraPradesh M ExServicemen Comp
1006 Anchal 1-May-03 Gujarat F OBC Comp
1007 Ramya 13-Jan-02 Telangana F Gen Appl
1008 Rakesh 22-Dec-01 AndhraPradesh M Sports Comp
19. Write sql query to display the students who are not from Telangana or AndhraPradesh.
20. Write sql query to create an index on column Sname.
21. Write sql query to display all the female students enrolled under Comp course and who belong to OBC.
22. Write sql query to display the students in the ascending order of their names for each course.
23. Write sql query to delete all the students records who have enrolled for Comp course and who are born
after 2002.
24. Write a sql query to add two new columns Contactno and Email to the existing fields.
E. Create a Table for Library Information : (for questions from 41 to 50) Table name: Library
Constraints: BookId is primary key and BookName is NOT NULL
25. Write sql query to display the list of authors from Himalaya publications.
26. Write sql query to display the total cost of books purchased Publisher wise.
27. Write sql query to count the total number of books under Kalyani publications.
29. Write sql query to display the books whose price is between 500 and 700
Write sql query to increase the price of all the books by 200 for publishers other than Himalaya or
Kalyani.
B.Com III Semester (New)
RELATIONAL DATABASE MANAGEMENT SYSTEM
Practical Question Bank Solutions 2023-24
1 row
created.
SQL> /
Enter value for sno: s2
Enter value for sname: Kiran
Enter value for item: Processor
Enter value for price: 8000
Enter value for city: Delhi
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s2','Kiran','Processor',8000,'Delhi')
1 row
created.
SQL> /
Enter value for sno: s3
Enter value for sname: Mohan
Enter value for item: Mouse
Enter value for price: 350
Enter value for city: Delhi
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s3','Mohan','Mouse',350,'Delhi')
1 row
created.
SQL> /
Enter value for sno: s4
Enter value for sname: Ramesh
Enter value for item: Processor
Enter value for price: 9000
Enter value for city: Banglore
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Suppliervalues('s4','Ramesh','Processor',9000,'Banglore')
1 row
created.
SQL> /
Enter value for sno: s5
Enter value for sname: Manish
Enter value for item: Printer
Enter value for price: 6000
Enter value for city: Mumbai
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s5','Manish','Printer',6000,'Mumbai')
1 row
created.
SQL> /
Enter value for sno: s6
Enter value for sname: Srikanth
Enter value for item: Processor
Enter value for price: 8500
Enter value for city: Chennai
old 1: insert into Supplier values('&sno','&sname','&item',&price,'&city')
new 1: insert into Supplier values('s6','Srikanth','Processor',8500,'Chennai')
1 row created.
6 rows selected.
Q1) Write sql query to display supplier numbers and supplier names whose name starts with ‘R’.
SQL> select sno,sname from supplier where sname like 'R%';
SN SNAME
s4 Ramesh
Q2) Write sql query to display the name of suppliers who supply Processors and whose city is Delhi.
SQL> select sname from supplier where item='Processor' and city='Delhi';
SNAME
Kiran
Q3) Write sql query to display the names of suppliers who lsupply the same items as supplied by
Ramesh.
SQL> select sname from supplier where item=(select item from supplier where sname='Ramesh');
SNAME
Kiran
Ramesh
Srikanth
1 row updated.
6 rows selected.
Q5) Write sql query to display supplier numbers, supplier names and item price for suppliers in delhi in
the ascending order of itemprice.
SQL> select sno,sname,price from supplier where city='Delhi' order by price;
SN SNAME PRICE
s3 Mohan 350
s2 Kiran 8000
Table altered.
SQL>desc supplier;
Name Null? Type
1 row deleted.
Q8)Create a view on the table which displays only supplier numbers and supplier names.
SQL> create view supplier_v as select sno,sname from supplier;
View created.
SN SNAME
s1 Suresh
s2 Kiran
s4 Ramesh
s5 Manish
s6 Srikanth
Q9)Write sql query to display the records in the descending order of itemprice for each itemsupplied.
SQL> select *from supplier order by price desc;
Q10)Write sql query to display the records of suppliers who supply items other than processors or
keyboard.
SQL> select *from supplier where item notin('Processor','Keyboard');
SQL> Create table emp(eidvarchar2(4) primary key, ename varchar2(8), dob date, desg varchar2(10), sal
number(5),doj date);
1 row created.
SQL> /
Enter value for eid: e102
Enter value for ename: amit
Enter value for dob: 10-jan-95
Enter value for desg:programmer
Enter value for sal:25000
Enter value for doj: 18-feb-18
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e102','amit','10-jan-95','programmer',25000,'18-feb-18')
1 row created.
SQL> /
Enter value for eid: e103
Enter value for ename: payal
Enter value for dob: 15-aug-85
Enter value for desg: tester
Enter value for sal: 35000
Enter value for doj: 13-jun-11
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e103','payal','15-aug-85','tester',35000,'13-Jun-11')
1 row created.
SQL> /
Enter value for eid: e104
Enter value for ename: kiran
Enter value for dob: 20-apr-
90
Enter value for desg:programmer
Enter value for sal:40000
Enter value for doj: 7-mar-14
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e104','kiran','20-apr-90','programmer',40000,'7-mar-14')
1 row created.
SQL> /
Enter value for eid:e105
Enter value for ename: meenal
Enter value for dob:29-may-83
Enter value for desg:dba
Enter value for sal: 50000
Enter value for doj: 9-dec-11
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e105','meenal','29-may-83','dba',50000,'9-dec-11')
1 row created.
SQL> /
Enter value for eid: e106
Enter value for ename: sheila
Enter value for dob: 1-may-70
Enter value for desg: analyst
Enter value for sal: 60000
Enter value for doj: 25-sep-18
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e106','sheila','1-may-70','analyst',60000,'25-s ep-18')
1 row created.
SQL> /
Enter value for eid: e107
Enter value for ename:swamy
Enter value for dob:13-jan-85
Enter value for desg: programmer
Enter value for sal: 45000
Enter value for doj: 14-feb-16
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e107','swamy','13-jan-85','programmer',45000,'14-feb-16')
1 row created.
SQL> /
Enter value for eid:e108
Enter value for ename:sushma
Enter value for dob: 22-dec-76
Enter value for desg:dba
Enter value for sal: 45000
Enter value for doj: 31-jan-12
old 1: insert into emp values('&eid','&ename','&dob','&desg',&sal,'&doj')
new 1: insert into emp values('e108','sushma','22-dec-76','dba',45000,'31-jan- 12')
1 row created.
SQL> select *from emp;
8 rows selected.
Q11)Write sql query to display all the employees whose designation is programmer.
SQL> select *from emp where desg='programmer';
Q12)Write sql query to display employees who have joined after 2014.
SQL> select *from emp where extract(year from doj)>2014;
Q13)Write sql query to display all the employees whose name ends with ‘a’.
SQL> select *from emp where enamelike'%a';
EID ENAME DOB DESG SAL DOJ
Q14)Write sql query to display the total salary of all the employees whose designation is programmer.
SUM(SAL)
110000
Q15)Write sql query to display all the employee names in upper case.
SUMA
AMIT
PAYAL
KIRAN
MEENAL
SHEILA
SWAMY
SUSHMA
8 rows selected.
Q16)Write sql query to display the details of the employee with highest experience.
Table altered.
8 rows updated.
Q17)Write sql query to display the details of the employees whose name contains ‘ee’.
Q18)Write sql query to increase the salaries of employees by 5000 whose designation is dba.
2 rows updated.
8 rows selected.
Q19)Write sql query to display the employees whose salary is more than the average salary of all the
employees.
1 row
created.
SQL> /
Enter value for deptid: d2
Enter value for dname: marketing
old 1: insert into dept values('&deptid','&dname')
new 1: insert into dept values('d2','marketing')
1 row
created.
SQL>.
SQL>/
Enter value for deptid: d3
Enter value for dname: finance
old 1: insert into dept values('&deptid','&dname')
new 1: insert into dept values('d3','finance')
1 row created.
SQL> select *fromdept;
DE DNAME
d1 sales
d2 marketing
d3 finance
1 row
created.
SQL> /
Enter value for eid: 102
Enter value for ename:david
Enter value for dept:d1
Enter value for desg: manager
Enter value for sal: 50000
Enter value for doj: 18-feb-18
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(102,'david','d1','manager',50000,'18-feb-18 ')
1 row
created.
SQL> /
Enter value for eid:103
Enter value for ename:preethi
Enter value for dept:d3
Enter value for desg: clerk
Enter value for sal: 35000
Enter value for doj: 13-jun-11
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(103,'preethi','d3','clerk',35000,'13-jun-11 ')
1 row
created.
SQL> /
Enter value for eid: 104
Enter value for ename: kiran
Enter value for dept: d1
Enter value for desg: salesman
Enter value for sal: 20000
Enter value for doj: 7-mar-14
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(104,'kiran','d1','salesman',20000,'7-mar-14 ')
1 row created.
SQL> /
Enter value for eid:105
Enter value for ename:meenal
Enter value for dept:d2
Enter value for desg: clerk
Enter value for sal: 50000
Enter value for doj: 9-dec-11
old 1: insert into employee
values(&eid,'&ename','&dept','&desg',&sal,'&doj') new 1: insert into
employee values(105,'meenal','d2','clerk',50000,'9-dec-11') 1 row created.
SQL> /
Enter value for eid:106
Enter value for ename:sunitha
Enter value for dept:d3
Enter value for desg: manager
Enter value for sal: 60000
Enter value for doj: 25-sep-18
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(106,'sunitha','d3','manager',60000,'25-sep- 18')
1 row created.
SQL> /
Enter value for eid: 107
Enter value for ename: akhil
Enter value for dept: d3
Enter value for desg: clerk
Enter value for sal: 25000
Enter value for doj:14-feb-
16
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(107,'akhil','d3','clerk',25000,'14-feb-16')
1 row
created.
SQL> /
Enter value for eid:108
Enter value for ename:sushma
Enter value for dept:d2
Enter value for desg: manager
Enter value for sal: 45000
Enter value for doj: 31-jan-12
old 1: insert into employee values(&eid,'&ename','&dept','&desg',&sal,'&doj')
new 1: insert into employee values(108,'sushma','d2','manager',45000,'31-jan-1 2')
1 row created.
SQL> select *from employee;
8 rowsselected.
21)Writesqlquerytodisplayalltheemployeeswhoearnmorethanaveragesalaryofalltheemployees in
thecompany.
Q22)Write sql query to display the fields eid, ename and dname.
8 rows selected.
Q23)Write sql query to sort the employee table in the descending order of salaries.
rows selected.
Q24)Write sql query to list all the job designations in the employee table without repetitions.
DESG
salesman
clerk
manager
Q25)Writesql query to display all the employee details department wise and in the ascending order. SQL>
select *from employee e,dept d where e.deptid=d.deptid order by dname;
8 rows selected.
Q27)Write sql query to display all the employees who joined in the year 2011.
SQL> select *from employee where doj between '01-jan-2011' and '31-dec-
Q28)Write sql query to display all the employees who joined in the month of February.
Q30) Write sql query to display all the employee details along with their work experience in the
company till current date.
1 row
created.
SQL> /
Enter value for sid: 1002
Enter value for sname: arun
Enter value for dob: 10-jan-02
Enter value for state: telangana
Enter value for gender: m
Enter value for category: obc
Enter value for course:honors
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1002,'arun','10-jan-02','telangana','m','obc','honors')
1 row
created.
SQL> /
Enter value for sid: 1003
Enter value for sname: payal
Enter value for dob: 15-aug-01
Enter value for state: maharashtra
Enter value for gender: f
Enter value for category: gen
Enter value for course: appl
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1003,'payal','15-aug-01','maharashtra','f','gen','appl')
1 row
created.
SQL> /
Enter value for sid: 1004
Enter value for sname: amrita
Enter value for dob:20-apr-02
Enter value for state: karnataka
Enter value for gender: f
Enter value for category: obc
Enter value for course:honors
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1004,'amrita','20-apr-02','karnataka','f','obc', 'honors')
1 row
created.
SQL> /
Enter value for sid: 1005
Enter value for sname: pavan
Enter value for dob: 29-may-03
Enter value for state: andhrapradesh
Enter value for gender: m
Enter value for category:
exservicemenEnter value for course:
comp
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1005,'pavan','29-may-03','andhrapradesh','m','ex servicemen','comp')
1 row created.
SQL> /
Enter value for sid: 1006
Enter value for sname: anchal
Enter value for dob: 01-may-01
Enter value for state: gujarat
Enter value for gender: f
Enter value for category: obc
Enter value for course: comp
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1006,'anchal','01-may-01','gujarat','f','obc','comp')
1 row
created.
SQL> /
Enter value for sid: 1007
Enter value for sname: ramya
Enter value for dob:13-jan-02
Enter value for state: telangana
Enter value for gender: f
Enter value for category: gen
Enter value for course: appl
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1007,'ramya','13-jan-02','telangana','f','gen',' pl')
1 row
created.
SQL> /
Enter value for sid: 1008
Enter value for sname:rakesh
Enter value for dob: 22-dec-01
Enter value for state: andhrapradesh
Enter value for gender: m
Enter value for category: sports
Enter value for course: comp
old 1: insert into std values(&sid,'&sname','&dob','&state','&gender','&category','&course')
new 1: insert into std values(1008,'rakesh','22-dec-01','andhrapradesh','m','sports','comp')
1 row created.
8 rows selected.
Q31)Writesql query to display the students who are not from telangana or Andhra Pradesh.
Q32)Create a view to display the columns sid, sname for students belonging to telangana.
SQL> create view std_telangana as select sid,sname from std where state in2 ('telangana');
View created.
1001 neha
1002 arun
1007 ramya
Q34)Write sql query to display all the female students enrolled under comp course and who belong to
obc.
Q35)Writesql query to display the student ids, names and their present age.
1001 neha 17
1002 arun 17
1003 payal 18
1004 amrita 17
1005 pavan 16
1006 anchal 18
1007 ramya 17
1008 rakesh 18
8 rows selected.
Q36)Writesql query to display the students in the ascending order of their names from each course.
Q37)Writesql query to delete all the students records who have enrolled for comp course and who are
born after 2002.
SQL> delete from std where course='comp' and extract(year from dob)>2002;
1 row deleted.
Q38)Writesql query to add two new columns contactno and email to the existing fields.
Table altered.
SQL>descstd;
Name Null? Type
STATE VARCHAR2(15)
GENDER VARCHAR2(1)
CATEGORY VARCHAR2(15)
COURSE VARCHAR2(8)
CONTACTNO NUMBER(10)
EMAIL VARCHAR2(15)
Q39)Write an sql query to display all the student names prefixed with Mr./Ms. Based on gender column.
Q40)Write an sql query to display all the student names where the length of the name is 5 characters.
SNAME
nehaa
runpa
yalra
mya
D) Questions from 41 to 50 for the Queries given below
1 row
created.
SQL> /
Enter value for bookid: b102
Enter value for bookname: businessstatistics
Enter value for author: opaggarwal
Enter value for purchased: 22-dec-11
Enter value for publisher: himalaya
Enter value for price: 750
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b102','businessstatistics','opaggarwal','22-dec-11','himalaya',750)
1 row
created.
SQL> /
Enter value for bookid: b103
Enter value for bookname: rdbms
Enter value for author: cjdate
Enter value for purchased: 2-mar-15
Enter value for publisher: tmh
Enter value for price: 900
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b103','rdbms','cjdate','2-mar-15','tmh',900)
1 row
created.
SQL> /
Enter value for bookid: b104
Enter value for bookname: mgmtaccounting
Enter value for author: rksharma
Enter value for purchased: 19-apr-16
Enter value for publisher: kalyani
Enter value for price: 450
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b104','mgmtaccounting','rksharma','19-apr-1 ','kalyani',450)
1 row created.
SQL> /
Enter value for bookid: b105
Enter value for
bookname:operatingsystemEnter value for
author:galvin
Enter value for purchased:25-nov-13
Enter value for publisher:phi
Enter value for price: 750
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b105','operatingsystem','galvin','25-nov-13 ','phi',750)
1 row
created.
SQL> /
Enter value for bookid: b106
Enter value for bookname:
advanceaccounting Enter value for author:
scgupta
Enter value for purchased: 16-apr-18
Enter value for publisher: himalaya
Enter value for price: 600
old 1: insert into library values('&bookid','&bookname','&author','&purchased','&publisher',&price)
new 1: insert into library values('b106','advanceaccounting','scgupta','16-apr-18','himalaya',600)
1 row created.
6 rows selected.
Q42)Writesql query to display the total cost of books purchased publisher wise.
SUM(PRICE) PUBLISHER
1250 kalyani
900 tmh
1350 himalaya
750 phi
Q43)Writesql query to count the total number of books under kalyani publications.
COUNT(*)
Table altered.
SQL>desc library;
Name Null? Type
Q45)Write a sql query to display the books in the ascending order of date purchased.
6 rows selected.
Q46)Write sql query to create an index on the fields book name and author.
Index created.
Q47)Write sql query to display the books whose price is between 500 and 700.
SQL> select *From library where price between 500 and 700;
Q48)Write sql query to increase the price of all the books by 200 for publishers other than himalaya or
kalyani.
6 rows selected.
Q49)Writesql query to display the book details where author name contains the name sharma.
Q50)Create a view to display the fields bookid and bookname where the publisher is
Himalaya. SQL> create view library_himalaya as select bookid,bookname from library where
2 publications in ('himalaya');
View created.
library_himalaya; BOOK
BOOKNAME
advancedaccounting