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

1096dbms

Sql file

Uploaded by

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

1096dbms

Sql file

Uploaded by

priyanshu.hr60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

DATABASE MANAGEMENT

SYSTEM
PRACTICAL
FILE

Submitted to:- Submitted by:-

Mr. Amit Singh Sahil


CSE Department 20001001096
3rd year CSE-B

Priyanshu 22001001081
INDEX

S.NO EXPERIMENT DATE SIGN


To study various Data Types and Data
1.
Objectsin SQL
To implement Data Definition Language
2.
(DDL)commands in SQL
To implement Data Manipulation
3.
Language(DML) commands in SQL
To implement various aggregate
4.
functions inSQL 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


7.
(DCL)commands in SQL
To implement Data Integrity Constraints
8.
inSQL

9. To implement different types of Views in


SQL
To implement Nested Queries (Simple
10.
andCorrelated) in SQL
To implement JOINS (Natural, Equi,
11. Theta,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

Priyanshu 22001001081
EXPERIMENT NO. 1

AIM:- 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, variableand 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 special


characters. The size parameter determines the length of the 0 - 255 bytes
column in characters. The default value is 1.

VARCHAR(size) A VARIABLE length string containing letters, numbers, and


special characters. The size option sets the maximum character 0 - 65535 bytes
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 ().
DATE It's a date. The permitted value range is '1000-01-01' to YYYY-MM-DD
'9999-12-31'.

Priyanshu 22001001081
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
including DEFAULT and ON UPDATE in the column
definition, automatic initialization and updating to the
current date and time is achieved.

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

Priyanshu 22001001081
pointer. Indexes can be created explicitly or automatically. If you do not have an
index on the column, then a full

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;

Priyanshu 22001001081
EXPERIMENT NO. 2

AIM:- To study Data Definition Language (DDL)

➢ Create
➢ Alter
➢ Drop
➢ 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 usedto 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


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

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

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


This query will create a new database in SQL and name the database as Pardeep.

Priyanshu 22001001081
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),


column3data_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 (4), 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 4. 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.

Syntax:

ALTER TABLE table_name ADD ( Columnname_1 datatype, Columnname_2


datatype );

Priyanshu 22001001081
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 COMMAND

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.

Priyanshu 22001001081
The 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

Priyanshu 22001001081
EXPERIMENT NO. 3

AIM:- To study Data Manipulation Language (DML)

➢ Insert
➢ Select
➢ Update
➢ 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:

Priyanshu 22001001081
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 ...;

NOT:

SELECT column1, column2, ... FROM table_name


WHERE NOT condition;

Priyanshu 22001001081
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:

Priyanshu 22001001081
EXPERIMENT NO. 4

AIM:- 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) > 4.5 ORDER BY product_cost;
Here only those products are displayed whose cost is greater than 4.5

MAX() and MIN()

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


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

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

Priyanshu 22001001081
SELECT product_name FROM products GROUP BY product_name HAVING
MIN(product_cost) < 2;

Priyanshu 22001001081
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) >=3 ;

Priyanshu 22001001081
EXPERIMENT NO. 5

AIM:- 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.

Priyanshu 22001001081
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.

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.

Priyanshu 22001001081
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.

POSITION (): This function is used to find position of the first occurrence of the
given alphabet.

SUBSTR (): This function is used to find a sub string from the a string from the given
position.

Priyanshu 22001001081
EXPERIMENT NO. 6

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

2022-12-12 18:09:35

CURDATE (): Returns the current date.


Example: SELECT CURDATE ();
Output:

2022-12-12

CURTIME (): Returns the current time.


Example: SELECT CURTIME ();
Output:

18:10:13

Priyanshu 22001001081
DATE (): Extracts the date part of a date or date/time expression.
Example: For the below table named ‘Test’

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.

Priyanshu 22001001081
EXPERIMENT NO. 8

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

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;

Priyanshu 22001001081
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;

Priyanshu 22001001081
EXPERIMENT NO. 9

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

Priyanshu 22001001081
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.

Priyanshu 22001001081
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.

Priyanshu 22001001081
EXPERIMENT NO. 10

AIM:- 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.

Priyanshu 22001001081
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.

VIEW

VIEW WITH JOIN


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

Priyanshu 22001001081
VIEW WITH CHECK OPTION

Priyanshu 22001001081
EXPERIMENT NO. 11

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

(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

Priyanshu 22001001081
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.

Priyanshu 22001001081
EXPERIMENT NO. 12

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

Priyanshu 22001001081
5. Natural Join

6. Theta Join

7. Cross Join

Priyanshu 22001001081
EXPERIMENT NO. 13

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


SELECTstatements.

Intersect Returns only the common records obtained from two or


moreSELECT statements.

Minus Returns only those records which are exclusive to the


firsttable.

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

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.

Priyanshu 22001001081
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;

Priyanshu 22001001081
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.

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.

Priyanshu 22001001081
EXPERIMENT NO. 14

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

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.

Priyanshu 22001001081
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

COMPOSITE INDEX

Priyanshu 22001001081
Priyanshu 22001001081

You might also like