dbms file
dbms file
IN
ELECTRONICS AND COMMUNICATION
ENGINEERING
DBMS
PRACTICAL FILE
20001003065
INDEX
20001003065
EXPERIMENT 1: To study various Data Types and Data Objects in SQL
SQL Data Type is an attribute that specifies the type of data of any object. Each column, variable
and expression has a related data type in SQL. We can use these data types while creating tables.
We can choose a data type for a table column based on our requirement.
For any database, data types are primarily categorized into three categories:
• String Datatypes
• Numeric Datatypes
• Date and time Datatypes
The most common data types that we studied in our lab class are as follows:
DATA TYPE DESCRIPTION SIZE/FORMAT
FLOAT( p) A number with a decimal value. MySQL utilizes the p 4 bytes if 0 <= p
value to determine if the final data type is FLOAT or <= 24, 8 bytes if
DOUBLE. If p is between 0 and 24, the data type is 25 <= p <= 53
changed to FLOAT (). If p is between 25 and 53, the d at
type is changed to DOUBLE ().
a
DATE It's a date. The permitted value range is '1000-01-01' to YYYY-MM-DD
'9999-12-31'.
20001003065
A database object is any defined object in a database that is used to store or reference data.
Anything which we make from create command is known as Database Object. It can be used to hold and
manipulate the data. Some of the examples of database objects are: view, sequence, indexes, etc.
2. View – This database object is used to create a view in database.A view is a logical
table based on a table or another view. A view contains no data of its own but is like a window
through which data from tables can be viewed or changed. The tables on which a view is based
are called base tables.
The view is stored as a SELECT statement in the data dictionary.
Example:
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
4. Index– This database object is used to create a indexes in database. An Oracle server
index is a schema object that can speed up the retrieval of rows by using a pointer. Indexes can
be created explicitly or automatically. If you do not have an index on the column, then a full
20001003065
table scan occurs. An index provides direct and fast access to rows in a table. Its purpose is to reduce the
necessity of disk I/O by using an indexed path to locate data quickly. The index is used and maintained
automatically by the Oracle server. Once an index is created, no direct activity is required by the user.
Indexes are logically and physically independent of the table they index. This means that they can be
created or dropped at any time and have no effect on the base tables or other indexes.
Example:
CREATE INDEX emp_last_name_idx
ON employees(last_name);
20001003065
EXPERIMENT 2: To study Data Definition Language (DDL) a)
Create
b) Alter
c) Drop
d) Truncate
CREATE DATABASE
A Database is defined as a structured set of data. So, in SQL the very first step to store the data in
a well-structured manner is to create a database. The CREATE DATABASE statement is used to
create a new database in SQL.
Syntax:
This query will create a new database in SQL and name the database as Jatin.
20001003065
CREATE TABLE
To store the data, we need a table to do that. The CREATE TABLE statement is used to create a
table in SQL. A table comprises of rows and columns. So while creating tables we have to provide
all the information to SQL about the names of the columns, type of data to be stored in columns,
size of the data etc.
Syntax:
column1 data_type(size),
int for integer data. size: Size of the data we can store in
a particular column.
For example: If for a column we specify the data_type as int and size as 10 then this column can
store an integer number of maximum 10 digits.
This query will create a table named Students. The ROLL_NO field is of type int and can store an
integer number of size 3. The next two columns NAME and SUBJECT are of type varchar and
can store characters and the size 20 specifies that these two fields can hold maximum of 20
characters.
ALTER COMMAND
ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used
to add and drop various constraints on the existing table.
20001003065
Syntax:
( Columnname_1 datatype,
Columnname_2 datatype );
DROP Command
DROP is used to delete a whole database or just a table. The DROP statement destroys the objects
like an existing database, table, index, or view.
A DROP statement in SQL removes a component from a relational database management system
(RDBMS).
Syntax:
Examples:
TRUNCATE
TRUNCATE statement is a Data Definition Language (DDL) operation that is used to mark the
extents of a table for deallocation (empty for reuse). The result of this operation quickly removes
all data from a table, typically bypassing a number of integrity enforcing mechanisms. The
20001003065
TRUNCATE TABLE mytable statement is logically (though not physically) equivalent to the
DELETE FROM mytable statement (without a WHERE clause).
Syntax:
TRUNCATE TABLE table_name;
20001003065
EXPIREMENT 3: To study Data Manipulation Language (DML)
(a) Insert
(b) Select
(c) Update
(d) Delete
INSERT
The INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of
using INSERT INTO statement for inserting rows:
Only values: First method is to specify only the value of data to be inserted without the column
names.
Column names and values both: In the second method we will specify both the columns which
we want to fill and their corresponding values as shown below:
INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1, value2, value3,..);
table_name: name of the table.
column1: name of first column, second column … value1, value2, value3 : value of first
column, second column,… for the new record Example:
20001003065
UPDATE
Syntax:
UPDATE table_name
SELECT
Syntax:
AND:
FROM table_name
OR:
FROM table_name
20001003065
NOT:
FROM table_name
DELETE
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
20001003065
EXPIREMENT 4: To implement various aggregate functions in SQL with
GROUP BY and HAVING clause
Aggregate Functions are database built-in functions that act on multiple rows of the table and
produce a single output. There are basically 5 aggregate functions that we use frequently in SQL.
Aggregate functions are deterministic.
COUNT(): Calculates the total number of rows in the table, it returns a single value.
AVG(): Calculates the average of the values to the column it is applied to.
MIN(): Returns the minimum value in the column it is applied to.
MAX(): Returns the maximum value in the column it is applied to.
SUM(): Return the sum of all values of the column it is applied to.
WHERE keyword that we used to filter data on the given condition works well with SQL operators
like arithmetic operator, comparison operator, etc but when it comes to aggregate functions we use
the HAVING keyword to sort data on the given condition. The GROUP BY clause is also used with
the HAVING keyword. SYNTAX:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY expression
HAVING condition
ORDER BY expression
LIMIT value;
SUM()
QUERY:
20001003065
AVG()
To select those products whose price is greater than the average price of the products table.
Query:
SELECT product_name FROM products GROUP BY product_name HAVING AVG(product_cost) >
(SELECT AVG(product_cost) FROM products);
Here only those products are present whose average price is greater than the average price of the products
table.
COUNT()
We want to display those customer ids (s) that occurred at least 2 times.
Query:
SELECT customer_id FROM login GROUP BY customer_id HAVING COUNT(customer_id) >=2 ;
20001003065
EXPERIMENT 5: To implement various string functions in SQL
String functions are used to perform an operation on input string and return an output string. Following are
the string functions defined in SQL:
ASCII (): This function is used to find the ASCII value of a character.
CHAR_LENGTH (): Doesn’t work for SQL Server. Use LEN () for SQL Server. This function is used to
find the length of a word.
CHARACTER_LENGTH (): Doesn’t work for SQL Server. Use LEN () for SQL Server.
This function is used to find the length of a line.
FIND_IN_SET (): This function is used to find a symbol from a set of symbols.
20001003065
Output: 2
FORMAT (): This function is used to display a number in the given format.
LCASE (): This function is used to convert the given string into lower case.
LOCATE (): This function is used to find the nth position of the given word in a string.
LPAD (): This function is used to make the given string of the given size by adding the given symbol.
20001003065
MID (): This function is to find a word from the given position and of the given size.
POSITION (): This function is used to find position of the first occurrence of the given alphabet.
REPEAT (): This function is used to write the given string again and again till the number of times
mentioned.
REPLACE (): This function is used to cut the given string by removing the given sub string.
RPAD (): This function is used to make the given string as long as the given size by adding the given symbol
on the right.
SPACE (): This function is used to write the given number of spaces.
If string1 and string2 are the same, the STRCMP function will return 0.
If string1 is smaller than string2, the STRCMP function will return -1.
20001003065
SUBSTR (): This function is used to find a sub string from the a string from the given position.
SUBSTRING (): This function is used to find an alphabet from the mentioned size and the given string.
SUBSTRING_INDEX (): This function is used to find a sub string before the given symbol.
TRIM (): This function is used to cut the given symbol from the string.
20001003065
UCASE (): This function is used to make the string in upper case.
20001003065
EXPERIMENT 6: To implement various date functions in SQL
In SQL, dates are complicated for newbies, since while working with database, the format of the date in table
must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is
also involved with date) is used. In MySQL the default date functions are:
Output:
2017-01-13 08:03:52
Output:
2017-01-13
Output:
08:05:15
20001003065
EXTRACT (): Returns a single part of a date/time. Syntax:
There are several units that can be considered but only some are used such as:
MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc.
And ‘date’ is a valid date expression.
20001003065
DATEDIFF (): Returns the number of days between two dates.Syntax: DATEDIFF
(date,format); date is a valid date and format specifies the output format for the date/time. The formats that
%f-Microseconds (000000-999999)
%H-Hour (00-23)
%h-Hour (01-12)
%I-Hour (01-12)
%k-Hour (0-23)
%l-Hour (1-12)
%S-Seconds (00-59)
%s-Seconds (00-59)
%V-Week (01-53) where Sunday is the first day of week, used with %X
%v-Week (01-53) where Monday is the first day of week, used with %x
%X-Year for the week where Sunday is the first day of week, four digits, used with %V
%x-Year for the week where Monday is the first day of week, four digits, used with %v
Result:
13 Jan 17
20001003065
EXPERIMENT 7: To implement Data Control Language (DCL)
A Transaction is a set of SQL statements that are executed on the data stored in
DBMS. Whenever any transaction is made these transactions are temporarily happen in
database. So, to make the changes permanent, we use DCL commands.
The DCL commands are:
COMMIT
ROLLBACK
SAVEPOINT
1. COMMIT:
This command is used to save the data permanently.
Whenever we perform any of the DDL 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 save-point 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 save-point or if save-point is not done, then to the last committed state.
Syntax: rollback;
20001003065
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;
20001003065
EXPERIMENT 8: To implement Data Integrity Constraints in SQL
• Primary key
• Foreign Key
• Check
• Unique
• Null
• Not null
• Default
Also Enable Constraints, Disable Constraints, Drop Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints 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 table. If there is any violation between the constraint and the data
action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a
table
FOREIGN KEY - Prevents actions that would destroy links between tables
CREATE INDEX - Used to create and retrieve data from the database very quickly NULL
NOT NULL
20001003065
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
Constraints specified in the enable and disable clauses of a CREATE TABLE statement must be
defined in the statement.
20001003065
Enabling and disabling Oracle constraints can also be done with the ENABLE and DISABLE
keywords of the CONSTRAINT clause.
If we define a constraint but do not explicitly enable or disable it,SQL enables it by default.
Any SQL INSERT, UPDATE or DELETE command applied to a table with constraints enabled has
the possibility of failing.
For example,
Updates applied to a Parent Table may fail if the statement leaves orphaned rows in a child table,
INSERT command against a Child Table may fail if a matching foreign key value does not exist in
the parent table.
20001003065
EXPERIMENT 9: To implement different types of Views in SQL
• View
• Joint view
• Force View
• View with check option
The template database for all User Defined views is from the Master database. It contains many
predefined views that are templates for tables and other databases. It contains nearly 230 of the
predefined views.
System Defined Views will be automatically attached to all User Defined databases. And these
provide information about the database, tables, and all the properties of the database and tables.
There are three types of System defined views, Information Schema, Catalog View, and Dynamic
Management View.
Information Schema
There are twenty different schema views in the SQL server. They are used to display the physical
information of the database, such as tables, constraints, columns, and views. This view starts with
INFORMATION_SCHEMA and followed by the View Name.
A constraint is used on a particular column in a table to ensure that certain data rules are followed for
the column. INFORMATION_SCHEMA.COLUMNS is used to receive information about the table
columns such as table name, column name, the position of the column, default value, etc. To return
the views present in the current database, INFORMATION_SCHEMA.VIEWS is used.
Catalog View
These are used to return information used by the SQL server. Catalog views provide an efficient
way to obtain, present, and transform custom forms of information. But they do not include any
information about backup, replication, or maintenance plans, etc. These views are used to access
metadata of databases, and the names and column names are descriptive, helping a user to query
what is expected.
Simple View
These views can only contain a single base table or can be created only from one table. Group
functions such as MAX(), COUNT(), etc., cannot be used here, and it does not contain groups of
data.
By using Simple View, DML operations can be performed. Insert, delete, and update are directly
possible, but Simple View does not contain group by, pseudocolumn like rownum distinct,
columns defined by expressions. Simple view also does not include NOT NULL columns from the
base tables.
Complex View
These views can contain more than one base table or can be constructed on more than one base
table, and they contain a group by clause, join conditions, an order by clause. Group functions can
be used here, and it contains groups of data. Complex views cannot always be used to perform
DML operations.
Insert, delete, and update cannot be applied directly on complex views. But unlike Simple Views,
Complex Views can contain group by, pseudocolumn like rownum, distinct, columns defined by
expressions. NOT NULL columns can be included in complex views while they are not selected by
the Simple View.
1) VIEW
20001003065
3) VIEW WITH CHECK OPTION
20001003065
EXPERIMENT 10: To implement Nested Queries (Simple and Correlated) in
SQL
NESTED QUERIES
In nested queries, a query is written inside a query. The result of inner query is used in execution
of outer query. We will use STUDENT, COURSE, STUDENT_COURSE tables for
understanding nested queries.
IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’, we can
write it with the help of independent nested query and IN operator. From COURSE table, we
can find out C_ID for C_NAME ‘DSA’ or DBMS’ and we can use these C_IDs for finding
S_IDs from STUDENT_COURSE TABLE.
The inner query will return a set with members C1 and C3 and outer query will return those
S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case). So, it will
return S1, S2 and S4.
Note: If we want to find out names of STUDENTs who have either enrolled in ‘DSA’ or
‘DBMS’, it can be done as:
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));
NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled in ‘DSA’
nor in ‘DBMS’, it can be done as:
Select S_ID from STUDENT where S_ID NOT IN
(Select S_ID from STUDENT_COURSE where C_ID IN
5 20001003065
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));
The innermost query will return a set with members C1 and C3. Second inner query will
return those S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case)
which are S1, S2 and S4. The outermost query will return those S_IDs where S_ID is not a
member of set (S1, S2 and S4). So it will return S3.
• Co-related Nested Queries: In co-related nested queries, the output of inner query depends on
the row which is being currently executed in outer query. e.g.; If we want to find out
S_NAME of STUDENTs who are enrolled in C_ID ‘C1’, it can be done with the help of
corelated nested query as:
Select S_NAME from STUDENT S where EXISTS
( select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’);
For each row of STUDENT S, it will find the rows from STUDENT_COURSE where
S.S_ID = SC.S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists
in STUDENT_COURSE SC with C_ID=’C1’, then inner query will return true and
corresponding S_ID will be returned as output.
5 20001003065
EXPERIMENT 11: To implement JOINS in SQL
Implementation of Join Queries
• Inner join
• Left join
• Right join
• Full join
• Natural join
• Theta join
• Cross join
1) Inner join
2) Left join
3) Right Join
4) Full Join
5) Natural Join
5 20001003065
6) Theta Join
7) Cross Join
5 20001003065
EXPERIMENT 12: To implement SET Operations (UNION, INTER-
SECTION, SET DIFFERENCE) in SQL
SQL set operators are used to combine the results obtained from two or more queries into a single result.
The queries which contain two or more subqueries are known as compounded queries.
Intersect Returns only the common records obtained from two or more
SELECT statements.
Minus Returns only those records which are exclusive to the first
table.
The generic syntax for working with SQL set operators is as follows:
Syntax:
SELECT column_name
FROM table_name_1
SET OPERATOR
SELECT column_name
FROM table_name_2
SET OPERATOR
SELECT column_name
FROM table_name_3
.
.
.
The different parameters used in the syntax are :
WHERE, GROUP BY and HAVING clauses may be used in above query based on requirements.
UNION
The UNION operator is used to combine the result-set of two or more SELECT statements.
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order Syntax:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
INTERSECT
There are two mandatory conditions for using the INTERSECT operator:
• Each SELECT statement must have the same number of expressions.
• Each corresponding expression in the different SELECT statement should be of the same data
type.
Syntax:
SELECT expr_1, expr_2, ... expr_n
FROM table1
WHERE conditions
INTERSECT
SELECT expr_1, expr_2, ... expr_n
FROM table2
WHERE conditions;
Explanation:
The ‘students’ and the ‘teachers’ are the already existing tables. After the intersection, the common rows for
the ‘name’ field from the ‘students’ table and the ‘teachers’ table would appear.
5 20001003065
MINUS
There are two mandatory conditions for using the MINUS operator in Oracle.
• Each SELECT statement must have the same number of expressions.
• Each corresponding expression in the different SELECT statement should be of the same data
type.
• Syntax:
SELECT expr_1, expr_2, ... expr_n
FROM table1
WHERE conditions
MINUS
SELECT expr_1, expr_2, ... expr_n
FROM table2
WHERE conditions;
Explanation:
The ‘students’ and the ‘teachers’ are the already existing tables. After the subtraction, the uncommon or
unique rows for the ‘name’ field from the ‘students’ table would appear.
5 20001003065
EXPERIMENT 13: To implement different types of Index in SQL
• Normal Index
• Unique Index
• Bitmap Index
• Composite Index
INDEX
Indexes are special lookup tables that the database search engine can use to speed up data
retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very
similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic, you first
refer to the index, which lists all the topics alphabetically and are then referred to one or more
specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data
input, with the UPDATE and the INSERT statements. Indexes can be created or dropped with
no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the
index, to specify the table and which column or columns to index, and to indicate whether the
index is in an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate
entries in the column or combination of columns on which there is an index.
Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as follows.
ON table_name (column_name);
UNIQUE INDEXES
Unique indexes are used not only for performance, but also for data integrity. A unique index
does not allow any duplicate values to be inserted into the table. The basic syntax is as follows.
5 20001003065
on table_name (column_name);
COMPOSITE INDEXES
A composite index is an index on two or more columns of a table. Its basic syntax is as follows.
Whether to create a single-column index or a composite index, take into consideration the
column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there
be two or more columns that are frequently used in the WHERE clause as filters, the composite
index would be the best choice.
IMPLICIT INDEXES
Implicit indexes are indexes that are automatically created by the database server when an object
is created. Indexes are automatically created for primary key constraints and unique constraints.
INDEX
UNIQUE INDEX
BITMAP INDEX
THIS IS NOT SUPPORTED BY SQL
COMPOSITE INDEX
5 20001003065