0% found this document useful (0 votes)
5 views

dbms file

This document is a practical file for a Bachelor of Technology in Electronics and Communication Engineering, focusing on various SQL experiments. It includes an index of experiments related to Data Types, Data Definition Language (DDL), Data Manipulation Language (DML), and aggregate functions in SQL. Each experiment outlines specific SQL commands and their applications, along with examples for better understanding.

Uploaded by

golumittal2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

dbms file

This document is a practical file for a Bachelor of Technology in Electronics and Communication Engineering, focusing on various SQL experiments. It includes an index of experiments related to Data Types, Data Definition Language (DDL), Data Manipulation Language (DML), and aggregate functions in SQL. Each experiment outlines specific SQL commands and their applications, along with examples for better understanding.

Uploaded by

golumittal2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

BACHELOR OF TECHNOLOGY

IN
ELECTRONICS AND COMMUNICATION
ENGINEERING

DBMS
PRACTICAL FILE

SUBMITTED TO: SUBMITTED BY :


Ms. GARIMA NAME :- LAKSHIT SHARMA
CLASS:-B.TECH (ECE) 4thSem
ROLL NO:- 20001003065

20001003065
INDEX

S.NO EXPERIMENT DATE SIGN

To study various Data Types and Data Objects


1.
in SQL

To implement Data Definition Language (DDL)


2.
commands in SQL

To implement Data Manipulation Language


3.
(DML) commands in SQL
To implement various aggregate functions in
4.
SQL with GROUP BY and HAVING clause

5. To implement various string functions in SQL

6. To implement various date functions in SQL

To implement Data Control Language (DCL)


7.
commands in SQL
To implement Data Integrity Constraints in
8.
SQL

9. To implement different types of Views in SQL

To implement Nested Queries (Simple and


10.
Correlated) in SQL
To implement JOINS (Natural, Equi, Theta,
11. Inner, Outer) in SQL

To implement SET Operations (UNION,


12.
INTER-SECTION, SET DIFFERENCE) in SQL

13. To implement different types of Index in SQL

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

CHAR(Size) A FIXED length string containing letters, numbers, and


0 - 255 bytes
special characters. The size parameter determines the
length of the column in characters. The default value is
1.
VARCHAR(size) A VARIABLE length string containing letters, numbers,
0 - 65535 bytes
and special characters. The size option sets the maximum
character length for a column.

TEXT(size) It stores a string. 65,535


characters

BOOL/ BOOLEAN Synonym for TINYINT(1). Nonzero values are deemed


true, while zero values are considered false.

INT(size) An integer value. The signed range is -2147483648 to - he 4 bytes


2147483647. The unsigned range is 0 to 4294967295. T
size parameter determines the maximum width of the
display (which is 255).

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'.

DATETIME(fsp) A combination of date and time. The range supported i YYYY-MM-DD


'1000-01-01 00:00:00' to '9999-12-31 23:59:59'. By hh:mm
including DEFAULT and ON UPDATE in the column
definition, automatic initialization and updating to the
current date and time is achieved.

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.

• Table – Basic unit of storage; composed rows and columns


• View – Logically represents subsets of data from one or more tables
• Sequence – Generates primary key values
• Index – Improves the performance of some queries
• Synonym – Alternative name for an object
Different database Objects:

1. Table – This database object is used to create a table in database.


Example:
CREATE TABLE dept
(deptno NUMBER (2),
dname VARCHAR2(14),
loc VARCHAR2(13));

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;

3. Sequence – This database object is used to create a sequence in database.A sequence


is a user created database object that can be shared by multiple users to generate unique integers.
A typical usage for sequences is to create a primary key value, which must be unique for each
row.The sequence is generated and incremented (or decremented) by an internal Oracle routine.
Example:
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;

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);

5. Synonym – This database object is used to create an index in database.


It simplify access to objects by creating a synonym (another name for an object). With synonyms, you can
Ease referring to a table owned by another user and shorten lengthy object names. To refer to a table
owned by another user, you need to prefix the table name with the name of the user who created it
followed by a period. Creating a synonym eliminates the need to qualify the object name with the schema
and provides you with an alternative name for a table, view, sequence, procedure, or other objects. This
method can be especially useful with lengthy object names, such as views.
Example:
CREATE SYNONYM d_sum FOR dept_sum_vu;

20001003065
EXPERIMENT 2: To study Data Definition Language (DDL) a)
Create
b) Alter
c) Drop
d) Truncate

DDL (Data Definition Language)


Data Definition Language actually consists of the SQL commands that can be used to define the
database schema. It simply deals with descriptions of the database schema and is used to create
and modify the structure of database objects in the database.DDL is a set of SQL commands used
to create, modify, and delete database structures but not data. These commands are normally not
used by a general user, who should be accessing the database via an application.

List of DDL commands


o CREATE: This command is used to create the database or its objects (like
table, index, function, views, store procedure, and triggers).
o DROP: This command is used to delete objects from the database.
o ALTER: This is used to alter the structure of the database.
o TRUNCATE: This is used to remove all records from a table, including
all spaces allocated for the records are removed.

o COMMENT: This is used to add comments to the data dictionary.

o RENAME: This is used to rename an object existing in the database.

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:

CREATE DATABASE database_name;

Database name is the name of the database

CREATE DATABASE Jatin;

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:

CREATE TABLE table name (

column1 data_type(size),

column2 data_type(size), column3

data_type(size), .... ); table_name: name of the table.

column1 name of the first column. data_type: Type of data we

want to store in the particular column.

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.

CREATE TABLE Students

( ROLL_NO int (3),

NAME varchar (20),

SUBJECT varchar (20) );

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:

ALTER TABLE table_name ADD

( 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:

DROP object object_name

Examples:

DROP TABLE table_name;

table_name: Name of the table to be deleted.

DROP DATABASE database_name;

database_name: Name of the database to be deleted.

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;

table_name: Name of the table to be truncated.

To truncate Student_details table from student_data database.

TRUNCATE TABLE Student_details;

After running the above query Student_details table will be truncated

20001003065
EXPIREMENT 3: To study Data Manipulation Language (DML)
(a) Insert
(b) Select
(c) Update
(d) Delete

DML (Data Manipulation Language)


The SQL commands that deals with the manipulation of data present in the database belong to
DML or Data Manipulation Language and this includes most of the SQL statements. It is the
component of the SQL statement that controls access to data and to the database. Basically, DCL
statements are grouped with DML statements.

List of DML commands:

INSERT: It is used to insert data into a table.

UPDATE: It is used to update existing data within a table.

DELETE : It is used to delete records from a database table.

SELECT: It is used to select records from a database table.

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.

INSERT INTO table_name VALUES (value1, value2, value3,…);


table_name: name of the table. value1, value2,.. : value of first column, second
column,… for the new record

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

SET column1 = value1, column2 = value2, ... WHERE condition;

SELECT
Syntax:

AND:

SELECT column1, column2, ...

FROM table_name

WHERE condition1 AND condition2 AND condition3 ...;

OR:

SELECT column1, column2, ...

FROM table_name

WHERE condition1 OR condition2 OR condition3 ...;

20001003065
NOT:

SELECT column1, column2, ...

FROM table_name

WHERE NOT condition;

DELETE
The DELETE statement is used to delete existing records in a table.

DELETE Syntax

DELETE FROM table_name WHERE condition;

Delete All Records

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.

Common aggregate functions are as follows:

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:

SELECT product_name, product_cost FROM products GROUP BY product_name, product_cost


HAVING SUM(product_cost) > 3.5 ORDER BY product_cost;
Here only those products are displayed whose cost is greater than 3.5

MAX() and MIN()

QUERY 1(To find products with a maximum price greater than 7)


SELECT product_name FROM products GROUP BY product_name HAVING MAX(product_cost) > 7;

QUERY 2(To find products with a minimum price less than 3)


SELECT product_name FROM products GROUP BY product_name HAVING MIN(product_cost) < 3;

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.

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

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.

INSTR (): This function is used to find the occurrence of an alphabet.

LCASE (): This function is used to convert the given string into lower case.

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

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.

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


20001003065
RIGHT (): This function is used to SELECT a sub string from the right end of the given size.

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.

STRCMP (): This function is used to compare 2 strings.

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.

If string1 is larger 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:

NOW (): Returns the current date and time. Example:

SELECT NOW ();

Output:

2017-01-13 08:03:52

CURDATE (): Returns the current date. Example:

SELECT CURDATE ();

Output:

2017-01-13

CURTIME (): Returns the current time. Example:

SELECT CURTIME ();

Output:

08:05:15

DATE (): Extracts the date


part of a date or date/time
expression. Example: For the
below table named ‘Test’

20001003065
EXTRACT (): Returns a single part of a date/time. Syntax:

EXTRACT (unit FROM date);

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.

DATE_ADD (): Adds a specified time interval to a date Syntax:

20001003065
DATEDIFF (): Returns the number of days between two dates.Syntax: DATEDIFF

(date1, date2); date1 & date2- date/time expression

DATE_FORMAT (): Displays date/time data in different formats.Syntax: DATE_FORMAT

(date,format); date is a valid date and format specifies the output format for the date/time. The formats that

can be used are: %a-Abbreviated weekday name (Sun-Sat)

%b-Abbreviated month name (Jan-Dec)

%c-Month, numeric (0-12)

%D-Day of month with English suffix (0th, 1st, 2nd, 3rd)

%d-Day of month, numeric (00-31)

%e-Day of month, numeric (0-31)

%f-Microseconds (000000-999999)

%H-Hour (00-23)

%h-Hour (01-12)

%I-Hour (01-12)

%i-Minutes, numeric (00-59)

%j-Day of year (001-366)

%k-Hour (0-23)

%l-Hour (1-12)

%M-Month name (January-December)

%m-Month, numeric (00-12)


20001003065
%p-AM or PM

%r-Time, 12-hour (hh:mm:ss followed by AM or PM)

%S-Seconds (00-59)

%s-Seconds (00-59)

%T-Time, 24-hour (hh:mm:ss)

%U-Week (00-53) where Sunday is the first day of week

%u-Week (00-53) where Monday is the first day of week

%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

%W-Weekday name (Sunday-Saturday)

%w-Day of the week (0=Sunday, 6=Saturday)

%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

%Y-Year, numeric, four digits

%y-Year, numeric, two digits Example:

DATE_FORMAT (NOW (),'%d %b %y')

Result:

13 Jan 17

20001003065
EXPERIMENT 7: To implement Data Control Language (DCL)

DCL/TCL stands for Data Control Language/Transaction Control Languages.


These commands are used for maintaining consistency of the database and for the
management of transactions made by the DML commands.

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.

The following constraints are commonly used in SQL:

NOT NULL - Ensures that a column cannot have a NULL value

UNIQUE - Ensures that all values in a column are different

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

CHECK - Ensures that the values in a column satisfies a specific condition

DEFAULT - Sets a default value for a column if no value is specified

CREATE INDEX - Used to create and retrieve data from the database very quickly NULL

CONSTRAINT is By default in the SQL

NOT NULL

20001003065
UNIQUE

PRIMARY KEY

FOREIGN KEY

CHECK

DEFAULT

Enabling and disabling of constraints


Enabling and disabling constraints can be accomplished by using

Drop constraint command

Disable constraint command

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

SYSTEM DEFINED VIEWS


The System Defined Views are predefined views that already exist in the SQL Server database, such
as Tempdb, Master, and temp. Each of the databases has its own properties and functions.

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.

INFORMATION_SCHEMA.CHECK_CONSTRAINTS is used to receive information about any


constraint available in the database.

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.

Dynamic Management View


These were introduced in the SQL server in 2005. The administer can get information about the
server state to diagnose problems, monitor the health of the server instance, and tune performance
through these views. The Server-scoped Dynamic Management View is only stored in the Master
database, whereas the Database-scoped Dynamic Management View is stored in each database.
20001003065
User Defined Views
These are the types of views that are defined by the users. There are two types under User Defined
views, Simple View and Complex View.

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

2) VIEW WITH JOIN


CREATE VIEW _VIEW_ AS SELECT ADDRESS FROM STUDENTS S,MENTOR M
WHERE S.ADDRESS=M.ADDRESS

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.

There are mainly two types of nested queries:


• Independent Nested Queries: In independent nested queries, query execution starts from
innermost query to outermost queries. The execution of inner query is independent of outer
query, but the result of inner query is used in execution of outer query. Various operators like
IN, NOT IN, ANY, ALL etc are used in writing independent 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.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’


Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’
STEP 2: Using C_ID of step 1 for finding S_ID
Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME=’DBMS’);

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

FULL JOIN IS NOT SUPPORTED BY SQL

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.

There are 3 major types of SQL operators, namely:


• Union
• Intersect
• Minus/ set difference

SQL Set Operator Function

Union Combines distinct results of two or more SELECT


statements.

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 :

SET OPERATOR: Mention the type of set operation to be performed


column_name: Mention the column name on which you want to perform the set operation
and want in the result set
FROM table_name_1: Mention the first table name from which the column has to be fetched
5 20001003065
FROM table_name_2: Mention the second table name from which the column has to be fetched

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.

The CREATE INDEX Command


The basic syntax of a CREATE INDEX is as follows.

CREATE INDEX index_name ON table_name;

Single-Column Indexes

A single-column index is created based on only one table column. The basic syntax is as follows.

CREATE INDEX index_name

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.

CREATE UNIQUE INDEX index_name

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.

CREATE INDEX index_name

on table_name (column1, column2);

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

You might also like