CA2 Practical Journal
CA2 Practical Journal
CA2 Practical Journal
List of Experiments
1 Introduction to DBMS
Experiment No. 1
Introduction To DBMS:
A database management system is a collection of interrelated data and set of program to access
those data.
Database systems are designed to manage large bodies of information. Management of data
involves both defining structures for storage of information and providing mechanisms for the
manipulation of information. In addition, the database system must ensure the safety of the
information stored, despite system crashes or attempts at unauthorized access. If data are to be
shared among several users, the system must avoid possible anomalous results.
There are four different types of database sytem users, differentiated by the way they expect to
interact with the syatem. Different types of user interface have been designed for different types
of users.
a)Naıve users: They are unsophisticated users who interact with the system by invoking one of
the application programs that have been written previously.
b) Application Programmer: They are computer professionals who write application programs.
Application programmers can choose from many tools to develop user interfaces.
c) Sophisticated User: They interact with the system without writing programs. Instead, they
form their requests either using a database query language or by using tools such as data analysis
software. Analysts who submit queries to explore data in the database fall in this category.
d) Specialized users: They are sophisticated users who write specialized database applications
that do not fit into the traditional data-processing framework. Among these applications are
computer-aided design systems, knowledge base and expert systems, systems that store data with
complex data types (for example, graphics data and audio data), and environment-modeling
systems.
1.1
2019-20
Computer application -II
Database Administrator:
One of the main reasons for using DBMS is to have central control of both the data and the
programs that access those data. A person who has such central control over the system is called
a database administrator (DBA).
• Schema definition
• Storage structure to access method definition
• Schema and physical organization modification
• Granting of authorization for data access
• Routine maintenance
• DDL interpreter which interpretes DDL stataements and records the definition in the
data dictionary.
• DML compiler which translates DML statements in a query language into an evaluation
plan consisting of low level instruction that the query evaluation engine understands.
• Query evaluation engine which interprets low level instructions generated by DML
compiler.
• Transaction manager, which ensures that the database remains in a consistent (correct) state
despite system failures, and that concurrent transaction executions proceed without conflicting.
• File manager, which manages the allocation of space on disk storage and the data structures
used to represent information stored on disk.
• Buffer manager, which is responsible for fetching data from disk storage into main memory,
and deciding what data to cache in main memory. The buffer manager is a critical part of the
1.2
2019-20
Computer application -II
database system, since it enables the database to handle data sizes that are much larger than the
size of main memory.
Transaction Management
Database Architecture
The architecture of a database system is greatly influenced by the underlying computer system
on which the database system runs. Database systems can be centralized, or client-server, where
one server machine executes work on behalf of multiple client machines. Database systems can
also be designed to exploit parallel computer architectures. Distributed databases span multiple
geographically separated machines.
In a two-tier architecture, the application resides at the client machine, where it invokes
database system functionality at the server machine through query language statements.
Application program interface standards like ODBC and JDBC are used for interaction between
the client and the server.
In a three-tier architecture, the client machine acts as merely a front end and does not contain
any direct database calls. Instead, the client end communicates with an application server,
usually through a forms interface. The application server in turn communicates with a database
system to access data. The business logic of the application, which says what actions to carry out
under what conditions, is embedded in the application server, instead of being distributed across
multiple clients. Three-tier applications are more appropriate for large applications, and for
applications that run on the WorldWideWeb.
1.3
2019-20
Computer application -II
1.4
2019-20
Computer application -II
1.5
2019-20
Computer application -II
Experiment No. 2
Introduction:
The entity-relationship (E-R) data model was developed to facilitate database design by allowing
specification of an enterprise schema that represents the overall logical structure of a database.
The E-R model is very useful in mapping the meanings and interactions of real-world enterprises
onto a conceptual schema. Because of this usefulness, many database-design tools draw on
concepts from the E-R model
An entity set is a set of entities of the same type that share the same properties, or attributes. The
set of all people who are instructors at a given university, for example, can be defined as the
entity set instructor. Similarly, the entity set student might represent the set of all students in the
university.
Entity sets do not need to be disjoint. For example, it is possible to define the entity set of all
people in a university (person). A person entity may be an instructor entity, a student entity, both,
or neither.
Relationship:
A relationship is an association among several entities. For ex we can define a relationship that
associates customer with loan.
Relationship Sets:
Relationship set is a set of relationships of the same type. Formally, it is a mathematical relation
on n ≥ 2 (possibly nondistinct) entity sets. If E1, E2, . . . , En are entity sets, then a relationship
set R is a subset of
The function that an entity plays in a relationship is called that entity’s role. Since entity sets
participating in a relationship set are generally distinct, roles are implicit and are not usually
specified. However, they are useful when the meaning of a relationship needs clarification. Such
is the case when the entity sets of a relationship set are not distinct; that is, the same entity set
participates in a relationship set more than once, in different roles. In this type of relationship set,
2.1
2019-20
Computer application -II
sometimes called a recursive relationship set, explicit role names are necessary to specify how an
entity participates in a relationship instance.
Attributes:
An attribute of an entity set is a function that maps from the entity set into a domain.
For each attribute, there is a set of permitted values, called the domain, or value set, of that
attribute. The domain of attribute course id might be the set of all text strings of a certain length.
Similarly, the domain of attribute semester might be strings from the set.
Types of Attribute
There may be instances where an attribute has a set of values for a specific entity. Suppose we
add to the instructor entity set a phone number attribute. An instructor may have zero, one, or
several phone numbers, and different instructors may have different numbers of phones.
3) Derived Attributes:
The value for this type of attribute can be derived from the values of other related attributes or
entities. For instance, let us say that the instructor entity set has an attribute students advised,
which represents how many students an instructor advises. We can derive the value for this
attribute by counting the number of student entities associated with that instructor.
Constraints:
An E-R enterprise schema may define certain constraints to which the contents of a database
must conform. In this section, we examine mapping cardinalities and participation constraints.
Mapping Cardinalities
2.2
2019-20
Computer application -II
Mapping cardinalities, or cardinality ratios, express the number of entities to which another
entity can be associated via a relationship set. Mapping cardinalities are most useful in
describing binary relationship sets, although they can contribute to the description of relationship
sets that involve more than two entity sets. In this section, we shall concentrate on only binary
relationship sets.
For a binary relationship set R between entity sets A and B, the mapping cardinality must be one
of the following:
• One-to-one. An entity in A is associated with at most one entity in B, and an entity in B
is associated with at most one entity in A.
• One-to-many. An entity in A is associated with any number (zero or more) of entities in
B. An entity in B, however, can be associated with at most one entity in A.
2.3
2019-20
Computer application -II
2. Participation Constraints:
The participation of an entity set E in a relationship set R is said to be total if every entity in E
participates in at least one relationship in R. If only some entities in E participate in relationships
in R, the participation of entity set E in relationship R is said to be partial.
For example, we expect every student entity to be related to at least one instructor through the
advisor relationship. Therefore the participation of student in the relationship set advisor is total.
Keys
We must have a way to specify how entities within a given entity set are distinguished.
Conceptually, individual entities are distinct; from a database perspective, however, the
differences among them must be expressed in terms of their attributes.
Therefore, the values of the attribute values of an entity must be such that they can uniquely
identify the entity. In other words, no two entities in an entity set are allowed to have exactly the
same value for all attributes.
The notion of a key for a relation schema, applies directly to entity sets. That is, a key for an
entity is a set of attributes that suffice to distinguish entities from each other.
ENTITY-RELATIONSHIP Diagrams:
An E-R diagram can express the overall logical structure of a database graphically. E-R diagrams
are simple and clear—qualities that may well account in large part for the widespread use of the
E-R model.
Consider E-R diagram, which consists of two entity sets, Customer and Loan, related through
binary relationship borrower. The attribute associated with customer are Customer_ID,
customer_name,Customer_street and Customer_city. The Attributes associated with Loan are
Loan_no, amount. The relation set borrower may be many to many, many to one or one to one.
2.4
2019-20
Computer application -II
The figure alongside is the full representation of the conceptual model of bank, expressed in
terms of E-R concept. The diagram includes entity sets, attributes, relationship sets & mapping
cardinalities.
The E-R diagram for our specific view of banking enterprise is very complex. E-R diagram for
realistic enterprise that cannot be drawn on single page & must be split up at multiple points.
2.5
2019-20
Computer application -II
Experiment No. 3
Aim: To create table and implement various DDL (Data Definition Language) commands.
Introduction:
Data-Definition Language
We specify a database schema by a set of definitions expressed by a special language called a
data-definition language (DDL). The DDL is also used to specify additional properties of the
data.
We specify the storage structure and access methods used by the database system by a set of
statements in a special type of DDL called a data storage and definition language. These
statements define the implementation details of the database schemas, which are usually hidden
from the users.
The data values stored in the database must satisfy certain consistency constraints. For example,
suppose the university requires that the account balance of a department must never be negative.
The DDL provides facilities to specify such constraints. The database system checks these
constraints every time the database is updated. In general, a constraint can be an arbitrary
predicate pertaining to the database.However, arbitrary predicates may be costly to test.
Verview of SQL:
IBM developed the original version of SQL, originally called Sequel, as part of the System R
project in the early 1970s. The Sequel language has evolved since then, and its name has
changed to SQL (Structured Query Language). Many products now support the SQL language.
SQL has clearly established itself as the standard relational database language.
In 1986, the American National Standards Institute (ANSI) and the International Organization
for Standardization (ISO) published an SQL standard, called SQL-86.
ANSIpublishedanextendedstandard for SQL, SQL-89, in 1989. The next version of the
standardwas SQL-92 standard, followed by SQL:1999, SQL:2003, SQL:2006, and most recently
SQL:2008. The bibliographic notes provide references to these standards.
3.1
2019-20
Computer application -II
Basic Datatypes:
1) Char (n): A fixed-length character string with user-specified length n. The full form,
character, can be used instead.
2) varchar(n): A variable-length character string with user-specified maximum
length n. The full form, character varying, is equivalent.
3) int: An integer (a finite subset of the integers that ismachine dependent). The full form,
integer, is equivalent.
4) smallint: A small integer (a machine-dependent subset of the integer type).
5) numeric(p, d): A fixed-point numberwith user-specified precision. The number consists of p
digits (plus a sign), and d of the p digits are to the right of the decimal point. Thus, numeric(3,1)
allows 44.5 to be stored exactly, but neither 444.5 or 0.32 can be stored exactly in a field of this
type.
6) real, double precision: Floating-point and double-precision floating-point numbers with
machine-dependent precision.
7) float(n): A floating-point number, with precision of at least n digits.
8) date : In mysql , date is displayed in the format YYYY-MM-DD eg: 2015-01-29.
9) Time: Time format in mysql is HH:MM:SS. Eg: 23:59:59.
10)Timestamp: Time stamp datat is used for values that contain both date and time parts. Time
stamp has a range ‘1970-01-01 00:00:01’ to ‘2038-01-19 08:14:07.
Data Definition Language normally known as DDL are the mysql statements or query which are
used to define and modify the structure of database schema or tables. DDL have these
commands: CREATE, ALTER, TRUNCATE, DROP, COMMENT, RENAME.
1) CREATE :
It creates a table with the given name. You must have a CREATE privelege for the table:
Syntax:
Create table <table_name> (attr1 datatype1, attr2 datatype2, attr3 datatype3, ……);
Note: To check the ouptput for each command DESCRIBE TABLE command is used. Following is the
Syntax for DESCRIBE command:
DESC <table_name>;
2)ALTER:
ALTER query is used to make modifications like Key constraints, Column size, etc in the table
structure.
3.2
2019-20
Computer application -II
3) DROP:
DROP command is used to delete database table. It delete all the records and database table
schema .
Syntax:
DROP TABLE table_name;
4) COMMENT:
COMMENT can be used in mysql by three types which are given below
5) RENAME
RENAME command can be used to rename the database table. Here is an example for this
statement.
RESULT:
Study of all the DDL statements is completed and implemented successfully.
3.3
2019-20
Computer Application- II Experiment no 4
EXPERIMENT NUMBER 04
AIM: To implement DML commands on created table.
• Procedural DMLs require a user to specify what data are needed and how to get those data.
2) DML Queries:
3.1 Insert Command:
The command is used to insert values in the created table in the form of rows.
Syntax:
Insert into <table_name> values (val1,val2,val3…..valn);
3.3 Select:
This command is used to select and view the table in various ways. It is used to retrieve and
extract various information from a given table.
2019-20 1
Computer Application- II Experiment no 4
Syntax:
Select <col1,col2,col3….> from <table_name>;
3.To retrieve data based on condition:
Syntax:
Select<col1,col2….> from <table_name> where <condition>;
Result:
Thus all the DML queries are studied and implemented on table.
2019-20 2
Computer Application- II Experiment No 5
Experiment No. 5
Aim: To implement various constraints on table
SQL constraints:
SQL constraints are used to specify rules for the data in a table. If there is any violation between
the constraint and the data action, the action is aborted by the constraint. Constraints can be
specified when the table is created (inside the CREATE TABLE statement) or after the table is
created (inside the ALTER TABLE statement). Constraints are the rules enforced on data
columns on table. These are used to limit the type of data that can go into a table. This ensures
the accuracy and reliability of the data in the database. Constraints could be column level or table
level. Column level constraints are applied only to one column, whereas table level constraints
are applied to the whole table. Constraints can be divided into following two types: Column level
constraints: limits only column data Table level constraints: limits whole table data Constraints
are used to makesure that the integrity of data is maintained in the database. Following are the
most used constraints that can be applied on table.
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• INDEX
• DEFAULT
NOT NULL constraint: Indicates that a column cannot store NULL value. By default, a column
can hold NULL values. If you do not want a column to have a NULL value, then you need to
define such constraint on this column specifying that NULL is now not allowed for that column.
A NULL is not the same as no data, rather, it represents unknown data.
Syntax:
Create table <table name> (column1_name datatype NOT NULL, column2_name datatype);
UNIQUE constraint: The UNIQUE Constraint prevents two records from having identical
values in a particular column. A UNIQUE constraint field will not have duplicate data. In the
CUSTOMERS table, for example, you might want to prevent two or more people from having
identical age.
2019-20 1
Computer Application- II Experiment No 5
Syntax:
Create table <table name> (column1_name datatype NOT NULL UNIQUE, column2_name
datatype NOT NULL);
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values. A
table can have only one primary key, which may consist of single or multiple fields. When
multiple fields are used as a primary key, they are called a composite key/candidate key. If a
table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
Syntax:
Create table <table name> (column1_name datatype NOT NULL UNIQUE, column2_name
datatype NOT NULL, PRIMARY KEY (column1_name));
FOREIGN KEY constraint: A foreign key is a key used to link two tables together. This is
sometimes called a referencing key. Foreign Key is a column or a combination of columns
whose values match a Primary Key in a different table. The relationship between 2 tables
matches the Primary Key in one of the tables with a Foreign Key in the second table. If a table
has a primary key defined on any field(s), then you cannot have two records having the same
value of that field(s).
Syntax:
❖ Create table <table_name1> (column1.1_name datatype NOT NULL UNIQUE,
column1.2_name datatype NOT NULL, PRIMARY KEY (column1_name), FOREIGN KEY
(column_name2.3) references <table_name2> );
❖ Alter table <table_name1> add foreign key (cloumn_name) references <table_name2>;
CHECK constraint: The CHECK Constraint enables a condition to check the value being
entered into a record. If the condition evaluates to false, the record violates the constraint and
isn't entered into the table. CHECK constraint is used to limit values of column between a range.
Syntax:
Create table <table name> (column1_name datatype CHECK (<predicate>), column2_name
datatype NOT NULL, PRIMARY KEY (column1_name));
INDEX constraint:
The INDEX is used to create and retrieve data from the database very quickly. Index can be
created by using single or group of columns in a table. When index is created, it is assigned a
2019-20 2
Computer Application- II Experiment No 5
ROWID for each row before it sorts out the data. Proper indexes are good for performance in
large databases, but you need to be careful while creating index. Selection of fields depends on
what you are using in your SQL queries.
Syntax:
Create INDEX <index_name> on <table_name> (column1,column2……);
DEFAULT constraint:
The DEFAULT constraint is used to insert a default value into a column. The default value will
be added to all new records, if no other value is specified.
Syntax:
create table <table_name> (column1 datatype, column2 datatype, column3 datatype DEFAULT
‘value1’);
NOTE:
1. All the constraints {except NOT NULL constraint} can be applied after creating table using
ALTER TABLE command. Also, can be deleted using DROP TABLE command.
RESULT: All the constraints are studied and applied on database table.
2019-20 3
COMPUTER APPLICATION –II Ex. No.6
Experiment No:6
Aim: To implement concept of index and views.
Theory:
INDEX:
A database index is a data structure that improves the speed of data retrieval
operations on a database table at the cost of additional writes and storage space to
maintain the index data structure. Indexes are used to quickly locate data without
having to search every row in a database table every time a database table is
accessed. Indexes can be created using one or more columns of a database table,
providing the basis for both rapid random lookups and efficient access of ordered
records.
An index is a copy of select columns of data from a table that can be searched very
efficiently that also includes a low-level disk block address or direct link to the
complete row of data it was copied from. Some databases extend the power of
indexing by letting developers create indices on functions or expressions
Information in the DBMS files is stored in form of records. Every record is
equipped with some key field, which helps it to be recognized uniquely.
Indexing is a data structure technique to efficiently retrieve records from database
files based on some attributes on which the indexing has been done. Indexing in
database systems is similar to the one we see in books.
Indexing is defined based on its indexing attributes. Indexing can be one of the
following types:
1
2017-2018
COMPUTER APPLICATION –II Ex. No.6
• Dense Index
• Sparse Index
Dense Index
In dense index, there is an index record for every search key value in the database.
This makes searching faster but requires more space to store index records itself.
Index record contains search key value and a pointer to the actual record on the
disk.
Sparse Index
In sparse index, index records are not created for every search key. An index
record here contains search key and actual pointer to the data on the disk. To
search a record we first proceed by index record and reach at the actual location of
the data. If the data we are looking for is not where we directly reach by following
index, the system starts sequential search until the desired data is found.
Multilevel Index
Index records are comprised of search-key value and data pointers. This index
itself is stored on the disk along with the actual database files. As the size of
database grows so does the size of indices. There is an immense need to keep the
2
2017-2018
COMPUTER APPLICATION –II Ex. No.6
index records in the main memory so that the search can speed up. If single level
index is used then a large size index cannot be kept in memory as whole and this
leads to multiple disk accesses.
VIEWS
A view is nothing more than a SQL statement that is stored in the database with an
associated name. A view is actually a composition of a table in the form of a
predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be
created from one or many tables which depends on the written SQL query to create
a view.
Views, which are kind of virtual tables, allow users to do the following:
• Structure data in a way that users or classes of users find natural or intuitive.
• Restrict access to the data such that a user can see and (sometimes) modify
exactly what they need and no more.
• Summarize data from various tables which can be used to generate repor
Creating Views:
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables, or another view.
To create a view, a user must have the appropriate system privilege according to
the specific implementation.
The basic CREATE VIEW syntax is as follows:
4
2017-2018
COMPUTER APPLICATION –II Ex. No.6
You can include multiple tables in your SELECT statement in very similar way as
you use them in normal SQL SELECT query.
RESULT:
The concept of INDEX and VIEWS is studied and implemented successfully.
5
2017-2018
Computer application – II Experiment no 7
Experiment No.: 7
Theory:
Aggregate Functions:
Aggregate Functions are functions that take a collection (a set or multiset) of
values as input and return a single value. SQL offers fine built in aggregate
functions:
• Average: avg
• Minimum: min
• Maximum: max
• Total: sum
• Count: count
The input to sum and avg must be a collection of numbers, but the other operators
can operate on collection of non-numeric data types such as strings as well.
1) Average: (avg)
This operator is used to find average of the numbers in the table the query might
be in relation with a single attribute containing single tuple with numerical valu.
- Select avg(attribute_name) from <table_name>;
- Select avg(attribute_name) from <table_name> where <predicate>;
E.g.:
2) Minimum: (min)
It finds the minimum value from the numerical column of the table. A particular
predicate must be given to find minimum value at a particular condition.
- Select min(attribute_name) from <table_name>
- Select min(attribute_name) from <table_name> where <predicate>;
3) Maximum: (max)
It is used to find maximum value from the column of table or the maximum value
of a particular attribute at some condition.
- Select max(attribute_name) from <table_name>;
- Select min(attribute_name) from <table_name> where <predicate>;
2019-20 1
Computer application – II Experiment no 7
-
4) Total: (sum)
It is used to add the numbers in a column. It also adds the number with common
attribute
- Select sum(attribute_name) from <table_name>;
- Select min(attribute_name) from <table_name> where <predicate>;
Eg:
5) Count: (count)
It is used to count the total number of rows in the table. It is classified in three
types.
-Select count(*) from <table_name>
- Select count(attribute name) from <table_name>;
- Select count (distinct <attribute_name>) from <table_name>;
2019-20 2
COMPUTER APPLICATION –II Experiment No. 8
Experiment No: 8
Aim: To study various set operations
THEORY:
UNION:
The SQL UNION clause/operator is used to combine the results of two or more SELECT statements
without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same number of
column expressions, the same data type, and have them in the same order, but they do not have to be
the same length.
SYNTAX:
UNION
INTERSECT:
The SQL INTERSECT clause/operator is used to combine two SELECT statements, but returns rows
only from the first SELECT statement that are identical to a row in the second SELECT statement. This
means INTERSECT returns only common rows returned by the two SELECT statements.
Just as with the UNION operator, the same rules apply when using the INTERSECT operator. MySQL
does not support INTERSECT operator
SYNTAX:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
2019-20 1
COMPUTER APPLICATION –II Experiment No. 8
EXCEPT:
The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows from
the first SELECT statement that are not returned by the second SELECT statement. This means
EXCEPT returns only rows, which are not available in second SELECT statement.
Just as with the UNION operator, the same rules apply when using the EXCEPT operator. MySQL does
not support EXCEPT operator.
SYNTAX:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
EXCEPT
The SET OPERATIONS automatically eleiminates the duplicates, unlike the se;ect clause. If we want
to retain duplicates we must write ALL after set operation clause (ie. UNION ALL, INTERSECT ALL,
EXCEPT ALL).
RESULT:
2019-20 2
Computer Application- II
SQL clauses:
In MYSQL we use various clauses to get data based on different conditions. We have following
type of SQL clauses to study.
• ORDER BY
• GROUP BY
• HAVING
ORDER BY clause:
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on
one or more columns. Some database sorts query results in ascending order by default. You can
use more than one column in the ORDER BY clause. Make sure whatever column you are using
to sort, that column should be in column-list.
Syntax:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
Example:
GROUP BY clause:
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups. The GROUP BY clause follows the WHERE clause in a SELECT
statement and precedes the ORDER BY clause.
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
Syntax:
2019-20 9.1
Computer Application- II
Example:
HAVING clause:
A HAVING clause in SQL specifies that an SQL SELECT statement should only return rows
where aggregate values meet the specified conditions. It was added to the SQL language because
the WHERE keyword could not be used with aggregate functions.
The HAVING clause enables you to specify conditions that filter which group results appear in
the final results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause
places conditions on groups created by the GROUP BY clause.
Syntax:
Example:
RESULT:
2019-20 9.2
Computer Application- II
SQL specifies strings by enclosing them in single quotes, for example, ’Computer’. A single
quote character that is part of a string can be specified by using two single quote characters; for
example, the string “It’s right” can be specified by “It”s right”.
The SQL standard specifies that the equality operation on strings is case sensitive; as a result the
expression “’comp. sci.’ = ’Comp. Sci.’” evaluates to false. However, some database systems,
such as MySQL and SQL Server, do not distinguish uppercase from lowercase when matching
strings; as a result “’comp. sci.’ = ’Comp. Sci.’” would evaluate to true on these databases. This
default behavior can, however, be changed, either at the database level or at the level of specific
attributes.
SQL also permits a variety of functions on character strings, such as concatenating (using “_”),
extracting substrings, finding the length of strings, converting strings to uppercase (using the
function upper(s) where s is a string) and lowercase (using the function lower(s)), removing
spaces at the end of the string (using trim(s)) and so on. There are variations on the exact set of
string functions supported by different database systems. See your database system’s manual for
more details on exactly what string functions it supports.
Pattern matching can be performed on strings, using the operator like. We describe patterns by
using two special characters:
Patterns are case sensitive; that is, uppercase characters do not match lowercase characters, or
vice versa. To illustrate pattern matching,we consider the following
examples:
• ’%Comp%’ matches any string containing “Comp” as a substring, for example, ’Intro. to
Computer Science’, and ’Computational Biology’.
2019-20 9.3
Computer Application- II
SQL expresses patterns by using the like comparison operator. Consider the query “Find the
names of all departments whose building name includes the substring ‘Watson’.” This query can
be written as:
Result:
Thus we have implemented and studied the string operators.
2019-20 9.4
Computer Application- II
Experiment No. 10
Aim: To implement the concept Nested Queries.
THEORY:
A Sub query or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.
A Sub query is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
• A Sub query can have only one column in the SELECT clause, unless multiple columns
are in the main query for the Sub query to compare its selected columns.
• An ORDER BY cannot be used in a Sub query, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the ORDER
BY in a Sub query.
• Subqueries that return more than one row can only be used with multiple value operators,
such as the IN operator.
• The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
• The BETWEEN operator cannot be used with a Sub query; however, the BETWEEN
operator can be used within the Sub query.
2019-20 10.1
Computer Application- II
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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 |
+----+----------+-----+-----------+----------+
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500);
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Example:
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy complete CUSTOMERS table into CUSTOMERS_BKP, following is the syntax:
2019-20 10.2
Computer Application- II
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example:
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS
table.
Following example updates SALARY by 0.25 times in CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27:
This would impact two rows and finally CUSTOMERS table would have the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
2019-20 10.3
Computer Application- II
FROM TABLE_NAME)
[ WHERE) ]
Example:
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS
table.
Following example deletes records from CUSTOMERS table for all the customers whose AGE
is greater than or equal to 27:
This would impact two rows and finally CUSTOMERS table would have the following records:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
2019-20 10.4