0% found this document useful (0 votes)
27 views27 pages

DBMS FILE-12

DBMS Experiments

Uploaded by

guptanishant184
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views27 pages

DBMS FILE-12

DBMS Experiments

Uploaded by

guptanishant184
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

EXPERIMENT NO: 7

AIM: Implementation of various functions in SQL by using


Clauses.

MySQL queries are SQL functions that help us to access a particular set of records
from a database table. We can request any information or data from the database using
the clauses or, let’s say, SQL statements. For example, SQL Clauses receives a
conditional expression that can be a column name or valid term involving columns
where this supports the MySQL functions to calculate the result values for a table in
the database. There are generally four kinds of SQL Clauses in MySQL Server.

• WHERE Clause

• ORDER BY clause

• HAVING Clause

• GROUP BY Clause

WHERE Clause

WHERE clause allows filtering certain records that exactly match a specified condition.
Thus, it helps us to fetch only the necessary data from the database that satisfies the
given expressional conditions.. We can also use logical or comparison operators such
as LIKE,<,>,=, etc. with WHERE clause to fulfill certain conditions.

Syntax: SELECTColumn1,….ColumnFromTable_nameWHERE[condition];

Code

select Name,Roll_no from student where Gender= 'F';

OUTPUT:
ORDER BY Clause:
The ORDER BY clause is used in SQL for sorting records. It is used to arrange the
result set either in ascending or descending order. When we query using SELECT
statement the result is not in an ordered form. Hence, the result rows can be sorted
when we combine the SELECT statement with the ORDER BY clause.

Syntax:

SELECT column1, …,columnN FROM TableName ORDER BY column

Code

select Name,Marks from student where Gender='F' order by Marks;

OUTPUT:

GROUP BY Clause
The GROUP BY clause is used to group rows that have the same values in the result
set. This clause is generally used with aggregate functions that allow grouping the
query result rows by multiple columns. The aggregate functions are COUNT, MAX,
MIN, SUM, AVG, etc.

Syntax:
SELECT Column FROM Table WHERE condition GROUP BY Column [ORDER BY
Column];

Code

select count(Name),Marks from student where Gender ='F' group by Marks;

OUTPUT:

HAVING Clause
Actually, this clause is introduced to apply functions in the query with the WHERE
clause. In SQL, the HAVING clause was added because the WHERE clause could not
be applied with aggregate functions.

Syntax:

SELECT Column FROM Table HAVING condition [ORDER BY Column];

OUTPUT:
EXPERIMENT NO: 8

AIM: Implementation of various string functions in SQL.

MySQL has several pre-defined sets of string functions, which can be applied to string
characters to perform several operations in SQL programming scenarios. A few of the
commonly used operations are RIGHT, used to fetch the number of characters in the
rightmost part of the string, CONCAT used for string concatenation, SPACE used to
get the return value for a number of space characters in a string, INSERT used to insert
a new string within another string specific to the position with the number of characters
to be inserted, etc.

ASCII(str):
Returns the ASCII value of the leftmost character of the string str.

Syntax: Select FirstName, ASCII(FirstName) from Person

Code
select Name,ASCII(Name) from student;

OUTPUT:

CHAR_LENGTH(str)
Returns the length of the string str in characters.

Syntax: Select FirstName, CHAR_LENGTH(FirstName) from Person

OUTPUT:
CONCAT(str1, str2, …., strn)
Returns a string formed by joining str1 to strn. If any sub-string is NULL, the result is
NULL.

Syntax:

Select FirstName, LastName, CONCAT(FirstName, LastName) as DisplayName


from Person

Code
select Name,Gender,concat(Name,Gender) from student;

OUTPUT:

FIELD(str, str1, str2, …, strn)


Returns the index position of string str amongst str1 to strn. Returns 0 if not found.

Syntax:

Select FirstName, LastName, FIELD('John', FirstName, LastName) as IsJohn from Person

Code
select Name,Gender,field('F',Name,Gender) as final from student;

OUTPUT:
REPLACE(str, from_str, to_str)
Replaces all occurrences of sub-string from_str with sub-string to_str in the string str. It
is case-sensitive.

Syntax: Select Address, REPLACE(Address, 's', 'S') from Person

Code

select Name,replace(Name,'a','A') from student;

OUTPUT:

REVERSE(str)
Reverses the string str.

Syntax: Select FirstName, REVERSE(FirstName) from Person

Code

select Name,reverse(Name) from student;

OUTPUT:
EXPERIMENT NO: 9

AIM: Implementation of various date functions in SQL.

In SQL, dates are complicated for newbies, since while working with a database, the
format of the data in the table must be matched with the input data to insert. In various
scenarios instead of date, datetime (time is also involved with date) is used.
For storing a date or a date and time value in a database, MySQL offers the following
data types:

1.NOW()
Returns the current date and time.

Syntax:
SELECT NOW();
Code
Select now();

Output:

2.CURDATE()
Returns the current date.

Syntax:
SELECT CURDATE();

Output:

3.CURTIME()
Returns the current time.
Syntax:
SELECT CURTIME();
Output:

4.DATE()
Extracts the date part of a date or date/time expression.

Syntax:

SELECT DATE(date time value);

Output:

5.EXTRACT()
Returns a single part of a date/time.

Syntax:
EXTRACT(unit FROM date);

Output:
EXPERIMENT NO: 10

AIM: Implementation of various views in SQL.

Views in SQL are a kind of virtual table. A view also has rows and columns like tables,
but a view doesn’t store data on the disk like a table. View defines a customized query
that retrieves data from one or more tables and represents the data as if it was
coming from a single source.
We can create a view by selecting fields from one or more tables present in the
database. A View can either have all the rows of a table or specific rows based on
certain conditions.

CREATE VIEWS in SQL


We can create a view using CREATE VIEW statement. A View can be created from
a single table or multiple tables.

Syntax:
CREATE VIEW view name AS
SELECT column1,column2 ………
FROM table name;
Code
create view show_view as
select name,dept
from student;
select * from show_view;

Output:
DELETE VIEWS in SQL
SQL allows us to delete an existing View. We can delete or drop View using
the DROP statement.

Syntax:
DROP VIEW view name;

Code
Drop view show_view;

Output:

Update View to Insert a row in a view


We can insert a row in a View in the same way as we do in a table. We can use
the INSERT INTO statement of SQL to insert a row in a View.

Syntax:
INSERT INTO view name (column1, column2……) Values ( );

Code

insert into show_view (name , dept)

values("Siddharth","Biotech");

Output:

Deleting a row from a View


Deleting rows from a view is also as simple as deleting rows from a table. We can
use the DELETE statement of SQL to delete rows from a view. Also deleting a row
from a view first deletes the row from the actual table and the change is then reflected
in the view.

Syntax:
DELETE FROM Details view WHERE condition;
Code
Delete from show_view where name= “Rahul”;

Output:

LISTING ALL VIEWS IN A DATABASE


We can list View using the SHOW FULL TABLES statement or using
the information_schema table. A View can be created from a single table or multiple
tables.

Syntax:
USE database name;
SHOW FULL TABLES WHERE table type LIKE “%VIEW”;

Output:
EXPERIMENT NO: 6

AIM: A detailed study of SQL data types and data type objects.

SQL Data Types

Data types are used to represent the nature of the data that can be stored in the
database table. For example, in a particular column of a table, if we want to store a
string type of data then we will have to declare a string data type of this column.

Data types mainly classified into three categories for every database.

o String Data types


o Numeric Data types
o Date and time Data types

String Data Types

CHAR(Size) It is used to specify a fixed length string that can contain


numbers, letters, and special characters. Its size can be 0 to
255 characters. Default is 1.

VARCHAR(Size) It is used to specify a variable length string that can contain


numbers, letters, and special characters. Its size can be from
0 to 65535 characters.

BINARY(Size) It is equal to CHAR() but stores binary byte strings. Its size
parameter specifies the column length in the bytes. Default
is 1.

VARBINARY(Size) It is equal to VARCHAR() but stores binary byte strings. Its


size parameter specifies the maximum column length in
bytes.

TEXT(Size) It holds a string that can contain a maximum length of 255


characters.

TINYTEXT It holds a string with a maximum length of 255 characters.


MEDIUMTEXT It holds a string with a maximum length of 16,777,215.

LONGTEXT It holds a string with a maximum length of 4,294,967,295


characters.

ENUM(val1, val2, It is used when a string object having only one value, chosen
val3,...) from a list of possible values. It contains 65535 values in an
ENUM list. If you insert a value that is not in the list, a blank
value will be inserted.

SET( It is used to specify a string that can have 0 or more values,


val1,val2,val3,....) chosen from a list of possible values. You can list up to 64
values at one time in a SET list.

BLOB(size) It is used for BLOBs (Binary Large Objects). It can hold up to


65,535 bytes.

Numeric Data Types

BIT(Size) It is used for a bit-value type. The number of bits per value is
specified in size. Its size can be 1 to 64. The default value is 1.

INT(size) It is used for the integer value. Its signed range varies from -
2147483648 to 2147483647 and unsigned range varies from 0 to
4294967295. The size parameter specifies the max display width
that is 255.

INTEGER(size) It is equal to INT(size).

FLOAT(size, d) It is used to specify a floating point number. Its size parameter


specifies the total number of digits. The number of digits after the
decimal point is specified by d parameter.

FLOAT(p) It is used to specify a floating point number. MySQL used p


parameter to determine whether to use FLOAT or DOUBLE. If p is
between 0 to24, the data type becomes FLOAT (). If p is from 25
to 53, the data type becomes DOUBLE().
DOUBLE(size, It is a normal size floating point number. Its size parameter
d) specifies the total number of digits. The number of digits after the
decimal is specified by d parameter.

DECIMAL(size, It is used to specify a fixed point number. Its size parameter


d) specifies the total number of digits. The number of digits after the
decimal parameter is specified by d parameter. The maximum
value for the size is 65, and the default value is 10. The maximum
value for d is 30, and the default value is 0.

DEC(size, d) It is equal to DECIMAL(size, d).

BOOL It is used to specify Boolean values true and false. Zero is


considered as false, and nonzero values are considered as true.

Date and Time Data Types

DATE It is used to specify date format YYYY-MM-DD. Its supported


range is from '1000-01-01' to '9999-12-31'.

DATETIME(fsp) It is used to specify date and time combination. Its format is


YYYY-MM-DD hh:mm:ss. Its supported range is from '1000-01-
01 00:00:00' to 9999-12-31 23:59:59'.

TIMESTAMP(fsp) It is used to specify the timestamp. Its value is stored as the


number of seconds since the Unix epoch('1970-01-01 00:00:00'
UTC). Its format is YYYY-MM-DD hh:mm:ss. Its supported range
is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07'
UTC.

TIME(fsp) It is used to specify the time format. Its format is hh:mm:ss. Its
supported range is from '-838:59:59' to '838:59:59'

YEAR It is used to specify a year in four-digit format. Values allowed in


four digit format from 1901 to 2155, and 0000.
Database Objects in DBMS

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

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

Syntax :
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);
Example :
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));

Output :

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.
Syntax :
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];

Example :
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
SELECT *FROM salvu50;

Output :

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.

Syntax :
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];

Example :
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;
Check if sequence is created by :
SELECT sequence_name, min_value, max_value,
increment_by, last_number
FROM user_sequences;

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

Syntax :
CREATE INDEX index
ON table (column[, column]...);

Example :
CREATE INDEX emp_last_name_idx
ON employees(last_name);

Synonym –
This database object is used to create a indexes 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.

Syntax :
CREATE [PUBLIC] SYNONYM synonym FOR object;

Example :
CREATE SYNONYM d_sum FOR dept_sum_vu;
EXPERIMENT NO: 11

AIM: Implementation of relational algebra.

Relational Algebra

Relational algebra is a procedural query language. It gives a step by step process to


obtain the result of the query. It uses operators to perform queries.

Types of Relational operation

Select Operation:

o The select operation selects tuples that satisfy a given predicate.


o It is denoted by sigma (σ).

Syntax: σ condition(relation_name);

Code: σ BRANCH_NAME="perryride" (LOAN);

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300


Project Operation:
o This operation shows the list of those attributes that we wish to appear in the
result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.

Syntax: ∏ A1, A2, An (r);

Where A1, A2, A3 is used as an attribute name of relation r.

Code: ∏ NAME, CITY (CUSTOMER) ;

Output:

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

Union Operation:
o Suppose there are two tuples R and S. The union operation contains all the
tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.

Syntax: R ∪ S

Code: ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR) ;


Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation contains
all tuples that are in both R & S.
o It is denoted by intersection ∩.

Syntax: R ∩ S

Code: ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR) ;

Output:
CUSTOMER_NAME

Smith

Jones

Set Difference:
o Suppose there are two tuples R and S. The set intersection operation contains
all tuples that are in R but not in S.
o It is denoted by intersection minus (-).

Syntax: R - S

Code: ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR) ;

Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

Cartesian product
o The Cartesian product is used to combine each row in one table with each row
in the other table. It is also known as a cross product.
o It is denoted by X.

Syntax: E X D
Code: EMPLOYEE X DEPARTMENT ;

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

Rename Operation:

The rename operation is used to rename the output relation.

It is denoted by rho (ρ).

Syntax: ρ(STUDENT1, STUDENT);


EXPERIMENT NO: 12

AIM: Implementation of various join operations in SQL.


SQL JOIN clause is used to query and access data from multiple tables by
establishing logical relationships between them. It can access data from multiple
tables simultaneously using common key values shared across different tables.
We can use SQL JOIN with multiple tables. It can also be paired with other clauses,
the most popular use will be using JOIN with WHERE clause to filter data retrieval.

Types of JOIN in SQL


There are many types of Joins in SQL. Depending on the use case, you can use
different type of SQL JOIN clause. Here are the frequently used SQL JOIN types:

• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• NATURAL JOIN

INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied. This keyword will create the result-set by combining all rows
from both the tables where the condition satisfies i.e value of the common field will
be the same.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNERJOIN table2
ON table1.matching_column = table2.matching_column;
Code:
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
INNERJOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:

LEFT JOIN
LEFT JOIN returns all the rows of the table on the left side of the join and matches
rows for the table on the right side of the join. For the rows for which there is no
matching row on the right side, the result-set will contain null. LEFT JOIN is also
known as LEFT OUTER JOIN.

Syntax:
SELECTtable1.column1,table1.column2,table2.column1,....
FROMtable1
LEFTJOINtable2
ON table1.matching_column = table2.matching_column;
Code:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFTJOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:
RIGHT JOIN
RIGHT JOIN returns all the rows of the table on the right side of the join and matching
rows for the table on the left side of the join. It is very similar to LEFT JOIN For the
rows for which there is no matching row on the left side, the result-set will
contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.

Syntax:
SELECTtable1.column1,table1.column2,table2.column1,....
FROMtable1
RIGHTJOINtable2
ON table1.matching_column = table2.matching_column;
Code:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHTJOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT
JOIN. The result-set will contain all the rows from both tables. For the rows for which
there is no matching, the result-set will contain NULL values.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULLJOIN table2
ON table1.matching_column = table2.matching_column;
Code:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULLJOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:
NAME COURSE_ID

HARSH 1

PRATIK 2

RIYANKA 2

DEEP 3

SAPTARHI 1

DHANRAJ NULL

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5

NULL 4

You might also like