0% found this document useful (0 votes)
49 views96 pages

Dbmsfile (43518002718)

The document describes experiments conducted on Database Management Systems. It includes introductions to relational database concepts like RDBMS, tables, records, fields, SQL, constraints, integrity, and commands. The first experiment defines key terms and the second experiment describes DDL commands used to define and modify database structure and objects like tables. Examples are provided for the CREATE command to build a table.

Uploaded by

JHanvi
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)
49 views96 pages

Dbmsfile (43518002718)

The document describes experiments conducted on Database Management Systems. It includes introductions to relational database concepts like RDBMS, tables, records, fields, SQL, constraints, integrity, and commands. The first experiment defines key terms and the second experiment describes DDL commands used to define and modify database structure and objects like tables. Examples are provided for the CREATE command to build a table.

Uploaded by

JHanvi
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/ 96

DELHI TECHNICAL CAMPUS,GREATER

NOIDA

DATABASE MANAGEMENT SYSTEM


LAB CODE : ETCS 256
SUBMITTED BY: SUBMITTED TO:
RINKAJ SOLANKI MS. UPASNA JOSHI
43518002718
Page | 1
B.TECH (CSE) 2ND YEAR
INDEX
S.No Name of the Date Teacher’s
Experiment Signature
1. Introduction to
RDBMS and SQL
2. Introduction to
DDL COMMANDS
3. Introduction to
DML
COMMANDS
4. Introduction to
DCL COMMANDS
5. Assignment-1 09/01/2020
6. Assignment-2 16/01/2020
7. Study
&Implementation
of different types
of Constraints.
8. Assignment-3 23/01/2020
9. Implementation
of different types
of functions with
suitable
examples.
10. Assignment-4 30/01/2020
11. Assignment-5 06/02/2020
12. Assignment-6 13/02/2020

Page | 2
INDEX
S.No Name of the Date Teacher’s
Experiment Signature
13. Study & Implementation of
• Sub queries
• Views
14. Assignment-7 20/02/2020
15. Implementation of
different types of joins
16. Assignment-8 27/02/2020
17. • Study and
Implementation of
Database Backup &
Recovery Commands.
• Study &
Implementation of
Rollback,Commit,Save
point.

Page | 3
EXPERIMENT-1 INTRODUCTION TO RDBMS AND
SQL

What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS
is the basis for SQL, and for all modern database systems like MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

A Relational database management system (RDBMS) is a database


management system (DBMS) that is based on the relational model as
introduced by E. F. Codd.

Features:
• Provides data to be stored in tables
• Persists data in the form of rows and columns
• Provides facility primary key, to uniquely identify the
rows
• Creates indexes for quicker data retrieval
• Provides a virtual table creation in which sensitive data
can be stored and simplified query can be
applied.(views)
• Sharing a common column in two or more
tables(primary key and foreign key)
• Provides multi user accessibility that can be controlled
by individual user

Page | 4
What is a table?
The data in an RDBMS is stored in database objects which are called
as tables. This table is basically a collection of related data entries
and it consists of numerous columns and rows.

Remember, a table is the most common and simplest form of data


storage in a relational database. The following program is an
example of a CUSTOMERS table :

What is a field?
Every table is broken up into smaller entities called fields. The fields
in the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and
SALARY.

A field is a column in a table that is designed to maintain specific


information about every record in the table.

What is a Record or a Row?


A record is also called as a row of data is each individual entry that
exists in a table.

Page | 5
A record is a horizontal entity in a table.

For example, there are 7 records in the above CUSTOMERS table.


Following is a single row of data or record in the CUSTOMERS table :

What is a column?
A column is a vertical entity in a table that contains all information
associated with a specific field in a table.

For example, a column in the CUSTOMERS table is ADDRESS, which


represents location description and would be as shown below :

What is a NULL value?


A NULL value in a table is a value in a field that appears to be blank,
which means a field with a NULL value is a field with no value.

It is very important to understand that a NULL value is different than


a zero value or a field that contains spaces. A field with a NULL value
is the one that has been left blank during a record creation.

Page | 6
SQL Constraints
Constraints are the rules enforced on data columns on a table. These
are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the database.

Constraints can either be column level or table level. Column level


constraints are applied only to one column whereas, table level
constraints are applied to the entire table.

Following are some of the most commonly used constraints available


in SQL :

NOT NULL Constraint − Ensures that a column cannot have a NULL


value.

DEFAULT Constraint − Provides a default value for a column when


none is specified.

UNIQUE Constraint − Ensures that all the values in a column are


different.

PRIMARY Key − Uniquely identifies each row/record in a database


table.

FOREIGN Key− Uniquely identifies a row/record in any


another database table.

CHECK Constraint − The CHECK constraint ensures that all values in a


column satisfy certain conditions.

INDEX − Used to create and retrieve data from the database very
quickly.

Page | 7
Data Integrity
The following categories of data integrity exist with each RDBMS :

Entity Integrity − There are no duplicate rows in a table.

Domain Integrity − Enforces valid entries for a given column by


restricting the type, the format, or the range of values.

Referential integrity − Rows cannot be deleted, which are used by


other records.

User-Defined Integrity − Enforces some specific business rules that


do not fall into entity, domain or referential integrity.

What is SQL?
SQL is Structured Query Language, which is a computer language for
storing, manipulating and retrieving data stored in a relational
database.

SQL is the standard language for Relational Database System. All the
Relational Database Management Systems (RDMS) like MySQL, MS
Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as
their standard database language.

Also, they are using different dialects, such as :

• MS SQL Server using T-SQL,


• Oracle using PL/SQL,
• MS Access version of SQL is called JET SQL (native format)
etc.

Features:

Page | 8
• Allows users to access data in the relational database
management systems.

• Allows users to describe the data.

• Allows users to define the data in a database and


manipulate that data.

• Allows to embed within other languages using SQL modules,


libraries & pre-compilers.

• Allows users to create and drop databases and tables.

• Allows users to create view, stored procedure, functions in


a database.

• Allows users to set permissions on tables, procedures and


views.

A Brief History of SQL


1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of
relational databases. He described a relational model for databases.

1974 − Structured Query Language appeared.

1978 − IBM worked to develop Codd's ideas and released a product


named System/R.

Page | 9
1986 − IBM developed the first prototype of relational database and
standardized by ANSI. The first relational database was released by
Relational Software which later came to be known as Oracle.

Page | 10
SQL Process
When you are executing an SQL command for any RDBMS, the
system determines the best way to carry out your request and SQL
engine figures out how to interpret the task.

There are various components included in this process.

These components are :

• Query Dispatcher
• Optimization Engines
• Classic Query Engine
• SQL Query Engine, etc.
A classic query engine handles all the non-SQL queries, but a SQL
query engine won't handle logical files.

Following is a simple diagram showing the SQL Architecture:

Page | 11
SQL Commands
The standard SQL commands to interact with relational databases
are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These
commands can be classified into the following groups based on their
nature −

DDL - Data Definition Language

1. CREATE

2. ALTER

3. DROP

DML - Data Manipulation Language

1. SELECT

2. INSERT

3. UPDATE

4. DELETE

DCL - Data Control Language

1. GRANT

2. REVOKE

Page | 12
EXPERIMENT-2 INTRODUCTION TO DDL
COMMANDS

Definition:
• DDL stands for Data Definition Language.
• It is a language used for defining and modifying the data and its
structure.
• It is used to build and modify the structure of your tables and
other objects in the database.

DDL commands are as follows :

1. CREATE

2. DROP

3. ALTER

4. RENAME

5. TRUNCATE

These commands can be used to add, remove or modify tables


within a database.

DDL has pre-defined syntax for describing the data.

1. CREATE COMMAND
• CREATE command is used for creating objects in the database.
• It creates a new table.

Page | 13
Syntax:

CREATE TABLE <table_name> (

column_name1 datatype,

column_name2 datatype,

column_name_n datatype

);

Example : CREATE command

CREATE TABLE employee

empid INT,

ename CHAR,

age INT,

city CHAR(25),

phone_no VARCHAR(20)

);

2. DROP COMMAND
• DROP command allows to remove entire database objects from
the database.
• It removes entire data structure from the database.
Page | 14
• It deletes a table, index or view.
Syntax:

DROP TABLE <table_name>;

OR

DROP DATABASE <database_name>;

Example : DROP Command

DROP TABLE employee;

OR

DROP DATABASE employees;

If you want to remove individual records, then use DELETE command


of the DML statement.

3. ALTER COMMAND
• An ALTER command allows to alter or modify the structure of
the database.
• It modifies an existing database object.
• Using this command, you can add additional column, drop
existing column and even change the data type of columns.

Syntax:

ALTER TABLE <table_name>

ADD <column_name datatype>;

OR

ALTER TABLE <table_name>

CHANGE <old_column_name><new_column_name>;
Page | 15
OR

ALTER TABLE <table_name>

DROP COLUMN <column_name>;

Example : ALTER Command

ALTER TABLE employee

ADD (address varchar2(50));

OR

ALTER TABLE employee

CHANGE (phone_no) (contact_no);

OR

ALTER TABLE employee

DROP COLUMN age;

To view the changed structure of table, use 'DESCRIBE' command.

For example:

DESCRIBE TABLE employee;

4. RENAME COMMAND
• RENAME command is used to rename an object.
• It renames a database table.
Syntax:

RENAME TABLE <old_name> TO <new_name>;

Page | 16
Example:

RENAME TABLE emp TO employee;

5. TRUNCATE COMMAND
• TRUNCATE command is used to delete all the rows from the
table permanently.
• It removes all the records from a table, including all spaces
allocated for the records.
• This command is same as DELETE command, but TRUNCATE
command does not generate any rollback data.

Syntax:

TRUNCATE TABLE <table_name>;

Example:

TRUNCATE TABLE employee;

Page | 17
EXPERIMENT-3 INTRODUCTION TO DML
COMMANDS

Definition
• DML stands for Data Manipulation Language.
• It is a language used for selecting, inserting, deleting and
updating data in a database.
• It is used to retrieve and manipulate data in a relational
database.
DDL commands are as follows:
1. SELECT
2. INSERT
3. UPDATE
4. DELETE

• DML performs read-only queries of data.

1. SELECT COMMAND
• SELECT command is used to retrieve data from the database.
• This command allows database users to retrieve the specific
information they desire from an operational database.
• It returns a result set of records from one or more tables.

Syntax:
Page | 18
SELECT * FROM <table_name>;
Example : SELECT Command
SELECT * FROM employee;
OR
SELECT * FROM employee where salary >=10,000;

2. INSERT COMMAND
• INSERT command is used for inserting a data into a table.
• Using this command, you can add one or more records to
any single table in a database.
• It is also used to add records to an existing code.
Syntax:
INSERT INTO <table_name> (`column_name1` <datatype>,
`column_name2` <datatype>, . . . , `column_name_n` <database>)
VALUES (`value1`, `value2`, . . . , `value n`);
Example:
INSERT INTO employee (`eid` int, `ename` varchar(20), `city`
varchar(20))
VALUES (`1`, `ABC`, `PUNE`);

3. UPDATE COMMAND
• UPDATE command is used to modify the records present in
existing table.
• This command updates existing data within a table.
• It changes the data of one or more records in a table.
Syntax:
UPDATE <table_name>
Page | 19
SET <column_name = value>
WHERE condition;
Example : UPDATE Command
UPDATE employee
SET salary=20000 WHERE
ename='ABC';

4. DELETE COMMAND
• DELETE command is used to delete some or all records from
the existing table.
• It deletes all the records from a table.
Syntax:
DELETE FROM <table_name> WHERE <condition>;
Example : DELETE Command
DELETE FROM employee WHERE emp_id = '001';
If we does not write the WHERE condition, then all rows will get
deleted.

EXPERIMENT NO.-4 INTRODUCTION TO DCL


COMMANDS
Page | 20
Definition
• DCL stands for Data Control Language.
• DCL is used to control user access in a database.
• This command is related to the security issues.
• Using DCL command, it allows or restricts the user from
accessing data in database schema.

DCL commands are as follows:

1. GRANT

2. REVOKE

• It is used to grant or revoke access permissions from any


database user.

1. GRANT COMMAND
• GRANT command gives user's access privileges to the database.
• This command allows specified users to perform specific tasks.
Syntax:

GRANT <privilege list>

ON <relation name or view name>

TO <user/role list>;

Example : GRANT Command

GRANT ALL ON employee

TO ABC;

Page | 21
[WITH GRANT OPTION]

In the above example, user 'ABC' has been given permission to view
and modify the records in the 'employee' table.

2. REVOKE COMMAND
• REVOKE command is used to cancel previously granted or
denied permissions.
• This command withdraw access privileges given with the
GRANT command.
• It takes back permissions from user.
Syntax:

REVOKE <privilege list>

ON <relation name or view name>

FROM <user name>;

Example : REVOKE Command

REVOKE UPDATE

ON employee

FROM ABC;

ASSIGNMENT-1
Q.1 Create a table student which contain attributes like roll
no.,dob,gender,class,college,city and marks.

Page | 22
Q.2 Insert any 5 records

Q.3 Display the information of all the students

Page | 23
Q.4 Display detailed structure of student table

Q.5 Display rollno,name and class of Noida students

Page | 24
Q.6 Display all the information in descending of marks

Q.7 Change the marks of roll no 5 to 89

Page | 25
Q.8 Change the name and city of roll no 3

Q.9 Delete the names of Noida students

Page | 26
Q.10 Delete the records of students where marks is less than 85

ASSIGNMENT-2
Q.1 Create a table employee(emp
no.,empname,job,hire_date,salary,commission,department no.,age).

Page | 27
Q.2 Insert any 5 records

Q.3 Display the info of all employee

Page | 28
Q.4 Display total salary paid to clerk

Q.5 Display max salary of employee who belongs to department


no.=10
Page | 29
Q.6 Display max,min,average salary of department no.=30

Maximum Salary

Minimum Salary

Page | 30
Average Salary

Q.7 Count no. of employee where job is salesman

Page | 31
Q.8 What is the difference between maximum and minimum salary
of employee in organisation?

Q.9 How many jobs are available in organisation?

Page | 32
Q.10 How many job titles are available?

Q.11 List all employee name,salary,15% rise in salary

Page | 33
Q.12 Print list of employee whose salary lies between 15,000 to
30,000.

Q.13 Print list of employee whose hiring date is lies between 17-
Feb2000 to 31-Dec-2019.

Page | 34
Q.14 Display employee details who belongs to department
no.=10,20,30

Q.15 List all the employee whose names starts with J or with T.

Page | 35
Q.16 List all employee whose job include M.

Q.17 List all employee have two ‘a’/’A’ in name.

Page | 36
Q.18 List all employee whose name’s second character is a.

EXPERIMENT-5

Page | 37
Title : Study & Implementation of different types of constraints.

Objective:

• To practice and implement constraints Theory:

CONSTRAINTS:
Constraints are used to specify rules for the data in a table. If there is
any violation between the constraint and the data action, the action
is aborted by the constraint. It can be specified when the table is
created (using CREATE TABLE statement) or after the table is created
(using ALTER TABLE statement).

1. NOT NULL: When a column is defined as NOTNULL, then that


column becomes a mandatory column. It implies that a value must
be entered into the column if the record is to be accepted for
storage in the table.
Syntax:

CREATE TABLE Table_Name (column_name data_type (size) NOT


NULL);

Example:

CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));

2. UNIQUE: The purpose of a unique key is to ensure that


information in the column(s) is unique i.e. a value entered in
column(s) defined in the unique constraint must not be repeated
across the column(s). A table may have many unique keys.

Syntax:
Page | 38
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE,
….);

Example:

CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));

3. CHECK: Specifies a condition that each row in the table must


satisfy. To satisfy the constraint, each row in the table must make
the condition either TRUE or unknown (due to a null).

Syntax:

CREATE TABLE Table_Name(column_name data_type(size)


CHECK(logical expression));

Example:

CREATE TABLE student (sno NUMBER (3), name CHAR(10),class


CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));

4. PRIMARY KEY: A field which is used to identify a record


uniquely. A column or combination of columns can be created as
primary key, which can be used as a reference from other tables. A
table contains primary key is known as Master Table.

• It must uniquely identify each record in a table.


• It must contain unique values.
• It cannot be a null field.
• It cannot be multi port field.

• It should contain a minimum no. of fields necessary to be called


unique.

Syntax:

CREATE TABLE Table_Name(column_name data_type(size)

Page | 39
PRIMARY KEY);

Example:

CREATE TABLE faculty (fcode NUMBER(3) PRIMARY


KEY, fname CHAR(10));

5. FOREIGN KEY: It is a table level constraint. We cannot add this


at column level. To reference any primary key column from other
table this constraint can be used. The table in which the foreign key
is defined is called a detail table. The table that defines the primary
key and is referenced by the foreign key is called the master table.

Syntax:

CREATE TABLE Table_Name(column_name data_type(size)

FOREIGN KEY(column_name) REFERENCES table_name);

Example:

CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY, subname


CHAR(10), fcode NUMBER(3),FOREIGN KEY(fcode) REFERENCE
faculty);

Defining integrity constraints in the alter table command:


Syntax: ALTER TABLE Table_Name ADD PRIMARY KEY
(column_name);

Example: ALTER TABLE student ADD PRIMARY KEY (sno);

Page | 40
(Or)

Syntax: ALTER TABLE table_name ADD CONSTRAINT


constraint_name PRIMARY KEY(colname)

Example: ALTER TABLE student ADD CONSTRAINT SN PRIMARY


KEY(SNO)

Dropping integrity constraints in the alter table command:


Syntax: ALTER TABLE Table_Name DROP constraint_name;

Example: ALTER TABLE student DROP PRIMARY KEY;

(or)

Syntax: ALTER TABLE student DROP CONSTRAINT constraint_name;

Example: ALTER TABLE student DROP CONSTRAINT SN;

6. DEFAULT : The DEFAULT constraint is used to insert a default value


into a column. The default value will be added to all new records, if
no other value is specified.

Syntax:

CREATE TABLE Table_Name(col_name1,col_name2,col_name3


DEFAULT ‘<value>’);

Example: CREATE TABLE student (sno NUMBER(3) UNIQUE, name


CHAR(10),address VARCHAR(20) DEFAULT’Aurangabad’)

ASSIGNMENT-3
PRIMARY and FOREIGN KEY

Q.1 Create table emp(emp_id primary key,emp_name,emp_salary)

Page | 41
Q.2 Create table dept(dept_id primary key,dept_name,emp_id
foreign key(emp_id) references emp(emp_id))

Page | 42
UNIQUE Constraint

Q.3 Create table emp(emp_id unique,emp_name)

Page | 43
NOT NULL Constraint

Q.4 Create table student(std_id not null,std_name)

CHECK Constraint

Q.5 Create table student(std_id,class(check IN(‘CSE’,’ECE’,’MAE’)

DEFAULT Constraint

Q.6 Create table std(std_id,name,address default ‘NOIDA’)

Page | 44
EXPERIMENT-6

Page | 45
Title: Implementation of different types of functions with suitable
examples.

Number Function

• Aggregate Function
• Character Function
• Conversion Function
• Date Function Objective:
To understand and implement various types of function in SQL.

NUMBER FUNCTION:
Abs(n): Select abs(-15) from dual;

Exp(n): Select exp(4) from dual;

Power(m,n): Select power(4,2) from dual;

Mod(m,n): Select mod(10,3) from dual;

Round(m,n): Select round(100.256,2) from dual;

Trunc(m,n): Select trunc(100.256,2) from dual;

Sqrt(m,n): Select sqrt(16) from dual;

Develop aggregate plan strategies to assist with summarization of


several data entries.

Aggregative operators: In addition to simply retrieving data, we


often want to perform some computation or summarization. SQL
allows the use of arithmetic expressions. We now consider a
powerful class of constructs for computing aggregate values such as
MIN and SUM.
Page | 46
1. Count: COUNT following by a column name returns the count
of tuple in that column. If DISTINCT keyword is used then it will
return only the count of unique tuple in the column. Otherwise, it
will return count of all the tuples (including duplicates) count (*)
indicates all the tuples of the column.

Syntax: COUNT (Column name)

Example: SELECT COUNT (Sal) FROM emp;

2. SUM: SUM followed by a column name returns the sum of all


the values in that column.

Syntax: SUM (Column name)

Example: SELECT SUM (Sal) From emp;

3. AVG: AVG followed by a column name returns the average


value of that column values.

Syntax: AVG (n1, n2...)

Example: Select AVG (10, 15, 30) FROM DUAL;

4. MAX: MAX followed by a column name returns the maximum


value of that column.

Syntax: MAX (Column name)

Example: SELECT MAX (Sal) FROM emp;

SQL> select deptno, max(sal) from emp group by deptno;


DEPT NO. MAX(SAL)
10 5000
20 3000
30 2850

Page | 47
SQL> select deptno, max (sal) from emp group by deptno having
max(sal)<3000;
DEPT NO. MAX(SAL)
30 2850

5. MIN: MIN followed by column name returns the minimum


value of that column.

Syntax: MIN (Column name)

Example: SELECT MIN (Sal) FROM emp;

SQL>select deptno,min(sal) from emp group by deptno having


min(sal)>1000;
DEPT NO. MIN(SAL)
10 1300

CHARACTER FUNCTION:
initcap(char): select initcap(“hello”) from dual; lower

(char): select lower (‘HELLO’) from dual; upper

(char): select upper (‘hello’) from dual; ltrim

(char,[set]): select ltrim (‘cseit’, ‘cse’) from dual;

rtrim (char,[set]): select rtrim (‘cseit’, ‘it’) from dual;

replace (char,search ): select replace(‘jack and

jue’,‘j’,‘bl’) from dual;

Page | 48
CONVERSION FUNCTIONS:
To_char: TO_CHAR (number) converts n to a value of VARCHAR2
data type, using the optional number format fmt. The value n can be
of type NUMBER, BINARY_FLOAT or BINARY_DOUBLE.

SQL>select to_char(65,'RN') from dual;

LXV

To_number: TO_NUMBER converts expr to a value of NUMBER data


type.

SQL>Select to_number ('1234.64') from Dual;

1234.64

To_date: TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or


NVARCHAR2 data type to a value of DATE data type.

SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.') FROM DUAL;

TO_DATE

---------

15-JAN-89

STRING FUNCTIONS :
Concat: CONCAT returns char1 concatenated with char2. Both char1
and char2 can be any of the datatypes

SQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’)FROM DUAL;

ORACLECORPORATION

Lpad: LPAD returns expr 1, left-padded to length n characters


with the sequence of characters in expr 2.
Page | 49
SQL>SELECT LPAD(‘ORACLE’,15,’*’) FROM DUAL;

*********ORACLE

Rpad: RPAD returns expr1, right-padded to length n characters


with expr2, replicated as many times as necessary.

SQL>SELECT RPAD (‘ORACLE’,15,’*’) FROM DUAL;

ORACLE*********

Ltrim: Returns a character expression after removing leading blanks.

SQL>SELECT LTRIM(‘SSMITHSS’,’S’) FROM DUAL;

MITHSS

Rtrim: Returns a character string after truncating all trailing blanks

SQL>SELECT RTRIM(‘SSMITHSS’,’S’) FROM DUAL;

SSMITH

Lower: Returns a character expression after converting


uppercase character data to lowercase. SQL>SELECT
LOWER(‘DBMS’) FROM DUAL;

dbms

Upper: Returns a character expression with lowercase character data


converted to uppercase

SQL>SELECT UPPER(‘dbms’) FROM DUAL;

DBMS

Length: Returns the number of characters, rather than the number


of bytes, of the given string expression, excluding trailing blanks.

Page | 50
SQL>SELECT LENGTH(‘DATABASE’) FROM DUAL;

Substr: Returns part of a character, binary, text, or image expression.

SQL>SELECT SUBSTR(‘ABCDEFGHIJ’3,4)FROM DUAL;

CDEF

Instr: The INSTR functions search string for substring. The function
returns an integer indicating the position of the character in string
that is the first character of this occurrence.

SQL>SELECT INSTR('CORPORATE FLOOR','OR',3,2)FROM DUAL;

14

DATE FUNCTIONS:
Sysdate:

SQL>SELECT SYSDATE FROM DUAL;

29-DEC-08

next_day:

SQL>SELECT NEXT_DAY(SYSDATE,’WED’) FROM DUAL;

05-JAN-09

add_months:

SQL>SELECT ADD_MONTHS(SYSDATE,2) FROM DUAL;

28-FEB-09 last_day:

SQL>SELECT LAST_DAY(SYSDATE) FROM DUAL;

31-DEC-08
Page | 51
months_between:

SQL>SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE) FROM EMP;

Least:

SQL>SELECT LEAST('10-JAN-07','12-OCT-07') FROM DUAL;

10-JAN-07

Greatest:

SQL>SELECT GREATEST('10-JAN-07','12-OCT-07') FROM DUAL;

10-JAN-07

Trunc:

SQL>SELECT TRUNC(SYSDATE,'DAY') FROM DUAL;

28-DEC-08

Round:

SQL>SELECT ROUND(SYSDATE,'DAY') FROM DUAL;

28-DEC-08

to_char:

SQL> select to_char(sysdate, "dd\mm\yy") from dual;

24-mar-05. to_date:

SQL> select to date (sysdate, "dd\mm\yy") from dual;

24-mar-05.

Page | 52
ASSIGNMENT-4 Use of
Character Function
1. CHR(n): select chr(65) from dual;

2. CONCAT(Char 1, Char 2):

select concat(‘TEST’,’CASE’) from dual;

Page | 53
3. INSTR(String,Char):

select instr(‘TEST’,’E’) from dual;

4. LENGTH(n): select length(‘TEST’) from dual;

5. LPAD(Char 1, n, [Char 2]): select lpad(‘TEST’,6,’+’) from dual;

6. LTRIM(String,[Char(s)]):

select ltrim(‘CSEIT’,’CSE’) from dual;

7. RPAD(Char 1, n, [Char2]): select rpad(‘ORACLE,9,’&’) from dual;

8. RTRIM(String, [Char(s)]):

select rtrim(‘CSEITIT’,’IT’) from dual;

Page | 54
9. REPLACE(char,search_string,replacement_string):

select replace(‘JACK AND JONES’,’J’,’*’)from dual;

10. SUBSTR(string,position,substring length):

select substr(‘ABCDEFGHIJ’,3,4) from dual;

11. INITCAP(char):

select initcap(‘hello’) from dual;

12. LOWER(string):

select lower(‘HELLO’) from dual;

13.UPPER(string): select

upper(‘hello’) from dual;

Page | 55
14. TRANSLATE(char,from
string,to string):

select translate(‘+91 25-2469782464’,’0123456789-


+’+’,6789012345+-‘) from dual;

15. ABS(n): select abs(‘-9’)

from dual;

16. CEIL(n): select ceil(-9.99)

from dual;

17. COS(n): select cos(‘0’)

from dual;

18. EXP(n): select exp(‘-9’)

from dual;

Page | 56
19. FLOOR(n): select

floor(‘9.99’) from dual;

20. MOD(m,n): select

mod(25,5) from dual;

21. POWER(x,y): select

power(3,2) from dual;

22. ROUND(x [,y]):

select round(-9.55) from dual;

23. SIGN(n): select sign(-9)

from dual;

24. SQRT(n): select sqrt(9)

from dual;
Page | 57
25. TRUNC(x,n): select

trunc(22.33,1) from dual;

26. SYSDATE: select sysdate

from dual;

27. ADD_MONTHS(d,n):

select add_months(sysdate,2) from dual;

28. LAST_DAY(): select

last_day(current_date)

from dual;

29. MONTHS_BETWEEN(dat
e1,date2):

select months_between(current_date+120,current_date) from dual;

Page | 58
30. NEXT_DAY(date,char):

select next_day(sysdate,’Monday’) from dual;

31. GREATEST(expr): select

greatest(10,28,33) from

dual;

32. LEAST(expr): select

least(10,28,33) from

dual;

Page | 59
ASSIGNMENT-5
Q.1 Display current time in hour:min:sec format?

Q.2 Display salary+commission of employee table.

Page | 60
Q.3 Store any data value in hire_date column of table?

Q.4 Display name of employee(s) who join the company in 2015?

Page | 61
Q.5 Display name of employee(s) who join the company this year?

Q.6 Display the system date.

Q.7 Display the current day.


Page | 62
Q.8 Display the current month and spell out year.

Q.9 Check whether it is AM or PM right now.

Page | 63
Q.10 Display the date of next Friday.

Q.11 Round the system date on month.

Page | 64
Q.12 Truncate the system date on month.

Q.13 Round the system date on year.

Page | 65
Q.14 Truncate the system date on year.

Q.15 Find the day after three days.

Page | 66
Q.16 Display day of date of joining column.

Q.17 Display those employees who join the company on Monday.

Page | 67
Q.18 Display those employees who join the company.

Q.19 Display those employees who join the company in last 30 days.

Page | 68
Q.20 Display spell out current date.

ASSIGNMENT-6
Q.1 Display total salary spent on each job.
Page | 69
Q.2 Display lowest paid employees under each department.

Q.3 Display the sales cost of software developed by each


programmer.

Page | 70
Q.4 Display number of software sold by each programmer.

Q.5 Display number of software in each language for which


development cost is less than 1000.

Page | 71
Q.6 Which is the costlier software developed in Pascal.

EXPERIMENT-7

Page | 72
Title : Study & Implementation of
• Sub queries
• Views

Objective:
• To perform nested Queries and joining Queries using DML
command
• To understand the implementation of views.

Theory:
SUBQUERIES: The query within another is known as a sub query. A
statement containing sub query is called parent statement. The rows
returned by sub query are used by the parent statement or in other
words.A subquery is a SELECT statement that is embedded in a
clause of another SELECT statement

You can place the subquery in a number of SQL clauses:

• WHERE clause
• HAVING clause
• FROM clause
• OPERATORS( IN.ANY,ALL,<,>,>=,<= etc..)

Types
1. Sub queries that return several values

Sub queries can also return more than one value. Such results should
be made use along with the operators in and any.

2. Multiple queries

Here more than one sub query is used. These multiple sub queries
are combined by means of ‘and’ & ‘or’ keywords.
Page | 73
3. Correlated sub query

A sub query is evaluated once for the entire parent statement


whereas a correlated Sub query is evaluated once per row processed
by the parent statement.

VIEW: In SQL, a view is a virtual table based on the result-set of an


SQL statement.

A view contains rows and columns, just like a real table. The fields
in a view are fields from one or more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view
and present the data as if the data were coming from one single
table.

A view is a virtual table, which consists of a set of columns from one


or more tables. It is similar to a table but it does not store in the
database. View is a query stored as an object.

Syntax: CREATE VIEW <view_name> AS SELECT <set of fields> FROM


relation_name WHERE (Condition)

Example:

SQL> CREATE VIEW employee AS SELECT empno,ename,job FROM


EMP WHERE job = ‘clerk’;

SQL> View created.

Example:

CREATE VIEW [Current Product List] AS

SELECT ProductID, ProductName

Page | 74
FROM Products

WHERE Discontinued=No;

UPDATING A VIEW : A view can updated by using the following


syntax :

Syntax : CREATE OR REPLACE VIEW view_name AS SELECT


column_name(s)

FROM table_name

WHERE condition

DROPPING A VIEW: A view can deleted with the DROP VIEW


command.

Syntax: DROP VIEW <view_name> ;

ASSIGNMENT-7
Q1. Create a table emp1(emp
no.,empname,job,hire_date,salary,commission,department no.,age)

Insert any 5 records and display the information of all employees.

Page | 75
Q2. Create a view from emp1 table containing all columns from the
emp1 table .

Q3. Create a view from emp1 table

Page | 76
Q4. Insert the information of a new employee in view2 .

Q5. Create a table emp2(emp

Page | 77
no.,empname,job,hire_date,salary,commission,department no.,age)

Insert any 5 records and display the information of all employees.

Q6. Display all the employees of view1 and view2 as in a new view
inform.

Page | 78
Q7. Display all the employees of view1 and view2 as in a new view
new where the jobs are common.

Q8. To delete the view.

Page | 79
EXPERIMENT-8

Title : Implementation of different types of Joins


• Inner Join
• Outer Join
• Natural Join…..etc Objective :

• To implement different types of joins

Theory :
The SQL Joins clause is used to combine records from two or more
tables in a database. A JOIN is a means for combining fields from two
tables by using values common to each.The join is actually
performed by the ‘where’ clause which combines specified rows

of tables.

Syntax:

SELECT column 1, column 2, column 3...

FROM table_name1, table_name2

WHERE table_name1.column name = table_name2.columnname;

Types of Joins :
1. Simple Join

2. Self Join

Page | 80
3. Outer Join

Simple Join :
It is the most common type of join. It retrieves the rows from 2
tables having a common column and is further classified into Equi-
join :
A join, which is based on equalities, is called equi-join.

Example:

Select * from item, cust where item.id=cust.id;

In the above statement, item-id = cust-id performs the join


statement. It retrieves rows from both the tables provided they both
have the same id as specified by the where clause. Since the where
clause uses the comparison operator (=) to perform a join, it is said
to be equijoin. It combines the matched rows of tables. It can be
used as follows:

• To insert records in the target table.


• To create tables and insert records in this table.
• To update records in the target table.
• To create views.

Non Equi-join :
It specifies the relationship between columns belonging to different
tables by making use of relational operators other than’=’.

Example:
Page | 81
Select * from item, cust where item.id<cust.id;

Table Aliases

Table aliases are used to make multiple table queries shorted and
more readable. We give an alias name to the table in the ‘from’
clause and use it instead of the name throughout the query.

Self join :
Joining of a table to itself is known as self-join. It joins one row in a
table to another. It can compare each row of the table to itself and
also with other rows of the same table.

Example:

select * from emp x ,emp y where x.salary >= (select avg(salary) from
x.emp where x. deptno =y.deptno); Outer Join :
It extends the result of a simple join. An outer join returns all the
rows returned by simple join as well as those rows from one table
that do not match any row from the table. The symbol(+) represents
outer join.

• Left outer join


• Right outer join
• Full outer join

Left Outer Join (A B):


In the left outer join, operation allows keeping all tuple in the left
relation. However, if there is no matching tuple is found in right
relation, then the attributes of right relation in the join result are
filled with null values.

Syntax:
Page | 82
SELECT column_name(s)

FROM table1

LEFT JOIN table2

ON table1.column_name = table2.column_name;

Example:

Consider the following 2 Tables


A
Num Square
2 4
3 9
4 16

B
Num Cube
2 8
3 27
5 125

A B
Num Square Cube
2 4 8
3 9 27
4 16 -

Page | 83
Right Outer Join ( A B ):
In the right outer join, operation allows keeping all tuple in the right
relation. However, if there is no matching tuple is found in the left
relation, then the attributes of the left relation in the join result are
filled with null values.

Syntax:

SELECT column_name(s)

FROM table1

RIGHT JOIN table2

ON table1.column_name = table2.column_name; Example:


A B
Num Cube Sqaure
2 8 4
3 27 9
4 64 16

Full Outer Join ( A B):


In a full outer join, all tuples from both relations are included in the
result, irrespective of the matching condition.

Syntax:

SELECT column_name(s)

FROM table1

FULL OUTER JOIN table2

ON table1.column_name = table2.column_name

Page | 84
WHERE condition; Example:
A B

Num Square Cube


2 4 8
3 9 18
4 16 -
5 - 125

NATURAL JOIN( ):
Natural join does not use any comparison operator. It does not
concatenate the way a Cartesian product does. We can perform a
Natural Join only if there is at least one common attribute that exists
between two relations. In addition, the attributes must have the
same name and domain.

Natural join acts on those matching attributes where the values of


attributes in both the relations are same..

Syntax:

SELECT *

FROM table1

NATURAL JOIN table2; Example:


Courses

CID Course Dept


CS01 Automata CS
EC01 Database ECE

Page | 85
EE01 Electronics EE

HOD
Dept Head
CS Divya
ECE Upasana
EE Shivam

Courses HOD
Dept CID Course Head
CS CS01 Automata Divya
ECE EC01 Database Upasana
EE EE01 Electronics Shivam

Page | 86
ASSIGNMENT-8
Q1. Create a table student(s_id,s_name) .Insert any 5 records and
display the information of 5 students.

Q2. Create a table marks(school_id,s_id,score,status) .Insert any 5


records and display the information.

Page | 87
Q3.Display the student name along with their student id and their
corresponding score and status.(INNER JOIN)

Q4.Display the names of all students with their ids and score whose
score is more than 23 .(LEFT JOIN)

Page | 88
Q5. Display the status and school id of all students with their s_id
and s_name from student table where status is pass.(RIGHT JOIN)

Page | 89
Q6. Display all the information as outer join of both the table student
and marks.(FULL JOIN)

EXPERIMENT-9
TITLE: To perform the operations for demonstrating the insertion,
deletion, updation using the referential integrity.

THEORY:
Referential Integrity is set of constraints applied to foreign key which
prevents entering a row in child table (where you have foreign key) for
which you don't have any corresponding row in parent table i.e.
entering NULL or invalid foreign keys. Referential Integrity prevents
your table from having incorrect or incomplete relationship e.g. If you
have two tables Order and Customer where Customer is parent table
with primary keycustomer_id and Order is child table with foreign key
customer_id. Since as per business rules you can not have an Order

Page | 90
without a Customer and this business rule can be implemented using
referential integrity in SQL on relational database.

Referential Integrity will cause failure on any INSERT or UPDATE SQL


statement changing value of customer_id in child table, If value of
customer_id is not present in Customer table. By the way What is
Referential Integrity in SQL is also an important SQL question similar
to finding second highest salary in SQL or difference between truncate
and delete and should be prepared well before going for any job
interview, where knowledge of SQL is one of the requirement.

Referential Integrity example:


Another example of Referential Integrity is Employee and Department
relationship. If we have dept_id as foreign key in Employee table than
by using referential integrity constraints we can avoid creating
Employee without department or non existing department. In short
Referential Integrity makes primary key foreign key relationship
viable. Let's first create Employee and Department table with primary
key, foreign key and referential Integrity constraints.

CREATE TABLE Department (dept_id INT NOT NULL, dept_name


VARCHAR(256), PRIMARY KEY (dept_id));

CREATE TABLE Employee (emp_id INT NOT NULL, emp_name


VARCHAR(256), dept_id INT, FOREIGN KEY (dept_id) REFERENCES
Department(dept_id) ON DELETE CASCADE);

Above SQL statements will create both Department and Employee


table. dept_id is now foreign key in Employee table. In this SQL, while
creating foreign key we have specified ON DELETE clause which tells,
Page | 91
what needs to done when a record from parent table is deleted.
CASCADE referential action allows to delete or update all matching
rows from child table, after deleting a record in parent table. This way
Refrential Integrity preserve data integrity of relationship.

Let's see How Referential Integrity disallow INSERT and UPDATE for a
record in child table for which there is no matching record in parent
table. To check this Refrential Integrity example execute following
queries:

INSERT INTO Department VALUES (1, 'Fin');

INSERT INTO Employee VALUES (101, 'Rajeev', 2)

When we inserted first record in Department table it ran fine but when
we insert a record in Employee table with dept_id = 2 which is not
present in Department i.e. parent table, failed to Referential integrity
or foreign key constraint check.

ORA-02291: integrity constraint (SYSTEM.SYS_C004028) violated - parent


key not found

Page | 92
If you modify your query and correct dept_id to 1, query will run fine,
as shown below

Page | 93
Now let's delete our only record from Department table and see if
matching records on child table is automatically deleted or not.

DELETE FROM Department;

You see there is no record in Employee table because of ON DELETE


CASCADE, matching records in child table is delete. Similarly you can

Page | 94
use ON UPDATE CASCADE to automatically propagate UPDATE from
parent table to child tables.
SELECT * FROM Employee;

You see there is no record in Employee table because of ON DELETE


CASCADE, matching records in child table is delete. Similarly you
can use ON UPDATE CASCADE to automatically propagate
UPDATE from parent table to child tables.

Advantage of Referential Integrity in RDBMS and SQL


There are several benefit of Referential Integrity in relational
database and maintaining integrity of data among parent and child
tables. Here are some of the most noticed advantages of Referential
Integrity in SQL:

1) Referential Integrity prevents inserting records with incorrect


details in table. Any insert or update operation will fail if it doesn't
satisfy referential integrity rule.

Page | 95
2) If a records from parent table is deleted, referential integrity
allows to delete all related records from child table using
cascadedelete functionality.

3) Similar to second advantage if a record i.e. customer_id of a


customer is updated on parent table (Customer table) , Referential
Integrity helps to update customer_id in child table (Order) using
cascade-update.

Page | 96

You might also like