Dbms Unit II

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Unit-II

Relational Model: Introduction to relational model, concepts of domain, attribute, tuple, relation,
importance of null values, constraints (Domain, Key constraints, integrity constraints) and their
importance.

BASIC SQL: Simple Database schema, data types, table definitions (create, alter), different DML
operations (insert, delete, update), basic SQL querying (select and project) using where clause,
arithmetic & logical operations, SQL functions (Date and Time, Numeric, String conversion).

Relational Model
Relational Model in DBMS

After designing the conceptual model of the Database using ER diagram, we need to convert
the conceptual model into a relational model which can be implemented using any RDBMS
language like Oracle SQL, MySQL, etc.

What is the Relational Model?


The relational model represents how data is stored in Relational Databases. A relational
database stores data in the form of relations (tables). Consider a relation STUDENT with
attributes ROLL_NO, NAME, ADDRESS, PHONE, and AGE shown in Table 1.
Student

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 18
Table-A database table is a structure that organises data into rows and columns
row represent record and column represent attribute

Attribute: Attributes are the properties that define a relation. e.g.; ROLL_NO, NAME
Domain: All attributes have some pre-defined scope and value which is called attribute
domain.
Relation Schema: A relation schema represents the name of the relation with its attributes.
e.g.; STUDENT (ROLL_NO, NAME, ADDRESS, PHONE, and AGE) is the relation schema for
STUDENT.
If a schema has more than 1 relation, it is called Relational Schema.

Tuple: Each row in the relation is known as a tuple. The above relation contains 4 tuples,
one of which is shown as:

1 RAM DELHI 9455123451 18

Relation Instance: The set of tuples of a relation at a particular instance of time is called a
relation instance. Table 1 shows the relation instance of STUDENT at a particular time. It can
change whenever there is an insertion, deletion, or update in the database.

Column: The column represents the set of values for a particular attribute. The column
ROLL_NO is extracted from the relation STUDENT. Example: ROLL_NO

NULL Values: The value which is not known or unavailable is called a NULL value. It is
represented by blank space. e.g.; PHONE of STUDENT having ROLL_NO 4 is NULL.

Importance of NULL value:

● It is important to understand that a NULL value is different from a zero value.


● A NULL value is used to represent a missing value, but that it usually has one of
three different interpretations:
○ The value unknown (value exists but is not known)
○ Value not available (exists but is purposely with held)
○ Attribute not applicable (undefined for this tuple)
● It is often not possible to determine which of the meanings is intended. Hence,
SQL does not distinguish between the different meanings of NULL.

Constraints in Relational Model:

While designing the Relational Model, we define some conditions which must hold for data
present in the database are called Constraints. These constraints are checked before
performing any operation (insertion, deletion, and updation ) in the database. If there is a
violation of any of the constraints, the operation will fail.

Domain Constraints: These are attribute-level constraints. An attribute can only take values
that lie inside the domain range. e.g; If a constraint AGE>0 is applied to STUDENT relation,
inserting a negative value of AGE will result in failure.

Key Integrity: Every relation in the database should have at least one set of attributes that
defines a tuple uniquely. Those set of attributes is called keys. e.g.; ROLL_NO in STUDENT is
a key. No two students can have the same roll number. So a key has two properties:
● It should be unique for all tuples.
● It can’t have NULL values.

Referential Integrity: When one attribute of a relation can only take values from another
attribute of the same relation or any other relation, it is called referential integrity. Let us
suppose we have 2 relations
STUDENT

ROLL_NO NAME ADDRESS PHONE AGE BRANCH_CODE

1 RAM DELHI 9455123451 18 CS

2 RAMESH GURGAON 9652431543 18 CS


3 SUJIT ROHTAK 9156253131 20 ECE

4 SURESH DELHI 18 IT

BRANCH

BRANCH_CODE BRANCH_NAME

CS COMPUTER SCIENCE

IT INFORMATION TECHNOLOGY

ECE ELECTRONICS AND COMMUNICATION ENGINEERING

CV CIVIL ENGINEERING

BRANCH_CODE of STUDENT can only take the values which are present in BRANCH_CODE
of BRANCH which is called referential integrity constraint. The relation which is referencing
another relation is called REFERENCING RELATION (STUDENT in this case) and the relation
to which other relations refer is called REFERENCED RELATION(BRANCH in this case).

Basic SQL
Database Schema
The overall design of the database is called schema.

A database schema is a structure that represents the logical storage of the data in a
database. It represents the organization of data and provides information about the
relationships between the tables in a given database

A database schema contains schema objects that may include tables, fields, packages,
views, relationships, primary key, foreign key,

The database schema is divided into three types, which are:


1 Logical Schema
2 Physical Schema
3 View Schema
EXAMPLE—

STUDENT (ROLL_NO varchar, NAME varchar, ADDRESS varchar, PHONE num, AGE num,
Subjectname string)
Faculty(Faculty id num,fname string,address string, Subjectname string)
Teaches(Faculty id num, ROLL_NO varchar,Subjectname string)

SQL Data Types:

Data types are used to represent the nature of the data that can be stored in the database
table.
Data types mainly classified into three categories for every database.
o String Data types
o Numeric Data types
o Date and time Data types

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

SQL 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().

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

DDL is a Data Definition Language that is used to define data structures. For example:
creating a table, and altering a table are instructions in SQL. DML is a Data Manipulation
Language that is used to manipulate data itself. For example: insert, update, and delete are
instructions in SQL
Data Definition Language
 DDL is used to specify a database’s structure, which includes its tables, views,
indexes, and constraints.
 DDL commands come in the following types: CREATE, ALTER, DROP, RENAME,
and TRUNCATE.
 DDL statements only modify the database’s schema; they have no direct effect
on the data within the database.
 DDL declarations are irreversible and difficult to undo.
Data Manipulation Language
 Inserting, updating, removing, and retrieving data from a database are all
possible with DML.
 DML commands come in the following types: SELECT, INSERT, UPDATE, DELETE,
and MERGE.
 DML statements have a direct impact on the database’s data.
 In the event of an error, data can be recovered thanks to the reversibility of DML
statements.

TABLE DEFINITION:

SQL Table is a collection of data which is organized in terms of rows and columns. In DBMS,
the table is known as relation and row as a tuple.

Operation on Table
1. Create table
2. Drop table
3. Delete table
4. Alter table

SQL Create Table


SQL create table is used to create a table in the database. To define the table, you should
define the name of the table and also define its columns and column's data type.

Syntax
create table table_name ("column1" "data type", "column2" "data type",
"column3" "data type", ... "columnN" "data type");
Example
SQL> CREATE TABLE EMPLOYEE (EMP_ID INT NOT NULL, EMP_NAME VARCHAR (25) NO
T NULL, PHONE_NO INT NOT NULL,ADDRESS CHAR (30),
PRIMARY KEY (ID) );

SQL> DESC EMPLOYEE;


If you create the table successfully, you can verify the table by looking at the message
by the SQL server. Else you can use DESC command as follows:

Field Type Null Key Default Extra

EMP_ID int(11) NO PRI NULL

EMP_NAME varchar(25) NO NULL

PHONE_NO NO int(11) NULL

ADDRESS YES NULL char(30)

Drop Table:
A SQL drop table is used to delete a table definition and all the data from a table. When this
command is executed, all the information available in the table is lost forever

Syntax
DROP TABLE "table_name";

SQL DELETE table

In SQL, DELETE statement is used to delete rows from a table. We can use WHERE condition
to delete a specific row from a table. If you want to delete all the records from the table, then
you don't need to use the WHERE clause.
Syntax
1. DELETE FROM table_name WHERE condition;

The following query will DELETE an employee whose ID is 3.

SQL> DELETE FROM EMPLOYEE WHERE EMP_ID = 3;

SQL ALTER TABLE


The ALTER TABLE statement in Structured Query Language allows you to add, modify, and
delete columns of an existing table.
Syntax:

ALTER TABLE table_name ADD column_name column-definition;

ALTER TABLE table_name ADD (column_Name1 column-


definition, column_Name2 column-definition, .....
column_NameN column-definition);

Example 1: Let's take an example of a table named Cars:

Car Name Car Color Car Cost

Hyundai Creta White 10,85,000

Hyundai Venue White 9,50,000

Hyundai i20 Red 9,00,000

Kia Sonet White 10,00,000


Kia Seltos Black 8,00,000

Swift Dezire Red 7,95,000

Suppose, you want to add the new column Car_Model in the above table. For this, you have
to type the following query in the SQL:

ALTER TABLE Cars ADD Car_Model Varchar(20);

DML Commands in SQL


DML is an abbreviation of Data Manipulation Language.
The DML commands in Structured Query Language change the data present in the SQL
database. We can easily access, store, modify, update and delete the existing records from
the database using DML commands.

Following are the four main DML commands in SQL:

1. SELECT Command
2. INSERT Command
3. UPDATE Command
4. DELETE Command

SELECT DML Command:


SELECT is the most important data manipulation command in Structured Query Language.
The SELECT command shows the records of the specified table.
Syntax of SELECT DML command:
SELECT column_Name_1, column_Name_2, ….., column_Name_N FROM
Name_of_table;

Here, column_Name_1, column_Name_2, ….., column_Name_N are the names of those


columns whose data we want to retrieve from the table.

If we want to retrieve the data from all the columns of the table, we have to use the following
SELECT command:

SELECT * FROM table_name;


INSERT DML Command:
INSERT is another most important data manipulation command in Structured Query
Language, which allows users to insert data in database tables.
Syntax of INSERT Command:
INSERT INTO TABLE_NAME ( column_Name1 , column_Name2 , column_Name3 , .... column
_NameN ) VALUES (value_1, value_2, value_3, .... value_N ) ;

INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES (104, Anmol, 89, 19)
;

Stu_Id Stu_Name Stu_Marks Stu_Age

101 Ramesh 92 20

201 Jatin 83 19

104 Anmol 89 19

UPDATE DML Command:


UPDATE is another most important data manipulation command in Structured Query
Language, which allows users to update or modify the existing data in database tables.
Syntax of UPDATE Command:
UPDATE Table_name SET [column_name1= value_1, ….., column_nameN = value_N]
WHERE CONDITION;

Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and 'Table_name' is the name of
the table whose values you want to update.

Examples of the UPDATE command:

Example 1: This example describes how to update the value of a single field.

Let's take a Product table consisting of the following records:

Product_Id Product_Name Product_Price Product_Quantity

P101 Chips 20 20

P102 Chocolates 60 40

P103 Maggi 75 5
P201 Biscuits 80 20

P203 Namkeen 40 50

Suppose, you want to update the Product_Price of the product whose Product_Id is P102. To
do this, you have to write the following DML UPDATE command:

UPDATE Product SET Product_Price = 80 WHERE Product_Id = 'P102' ;

DELETE DML Command:


DELETE is a DML command which allows SQL users to remove single or multiple existing
records from the database tables.
Syntax of DELETE Command:
DELETE FROM Table_Name WHERE condition;

Product_Id Product_Name Product_Price Product_Quantity

P101 Chips 20 20

P102 Chocolates 60 40

P103 Maggi 75 5

P201 Biscuits 80 20

P202 Namkeen 40 50

DELETE FROM Product WHERE Product_Id = 'P202' ;

DELETE FROM Product;

Product_Id Product_Name Product_Price Product_Quantity


To implement conversion functions, String, and Date functions

Date functions
Function Description

Add_months(d, n) Returns a date after adding a specified date with the


specified number of months

Last_day(d) Returns the date corresponding to the last day of the


month

Months_between(d1, d2) Returns the number of months between two dates

Next_day(d, day) Displays the next day

Round(d, [fmt]) Returns the date which is rounded to the unit specified
by the format model

Trunc(d, [fmt]) Returns the date with the time portion of day
truncated to the unit

specified by format model

Greatest(d1, d2, d3…) Returns the latest date present in the arguments

select Last_day(sysdate) from dual;


select to_char(sysdate) from dual;
select Last_day('01-mar-23') from dual;
select Months_between('01-jan-23','01-jun-23') from dual;
select Next_day('28-feb-23','tue') from dual;
select round (to_date('28-feb-2023'),'year') from dual;
select round (to_date('28-feb-2023'),'month') from dual;
select trunc (to_date('28-aug-2023'),'year') from dual;
select trunc (to_date('28-aug-2023'),'month') from dual;
select greatest('28-feb-23','01-aug-2021') from dual;
select add_months('28-feb-23',5) from dual;

Character Functions

Function Example

Initcap(char) Select initcap(‘hello’) from dual;

Lower(char) Select lower(‘FUN’) from dual;

Upper(char) Select upper(‘sun’) from dual;

Ltrim(char, set) Select ltrim(‘xyzadams’,’xyz’) from dual;

Rtrim(char, set) Select rtrim(‘xyzadams’,’ams’) from dual;

Translate(char, from, to) Select translate(‘jack’, ’j’, ’b’) from dual;

Replace(char, searchstring, [rep Select replace(‘jack and jue’, ‘j’, ‘bl’) from dual;
string])

Substr(char, m, n) Select substr(‘abcdefg’, 3, 2) from dual;

Select initcap(‘hello’) from dual;=Hello

Select lower(‘FUN’) from dual;=fun


Select rtrim(‘xyzadams’,’ams’) from dual=xyzad

Select ltrim(‘xyzadams’,’xyz’) from dual=adams

Select translate(‘jack’, ’j’, ’b’) from dual=back

Select replace(‘jack and jue’, ‘j’, ‘bl’) from dual=black and blue

Select substr(‘abcdefg’, 3, 4) from dua=defg

Conversion Functions
Function Description

Converts date to a value of varchar2 datatype in a form


To_char(d, [fmt]) specified by date format fmt. If fmt is neglected then it
converts date to varchar2 in the default date format

To_date(char, [fmt]) Converts char or varchar datatype to date datatype.

select sysdate from dual;


select to_char(sysdate) from dual;

Numeric Functions
Function Example

Abs Select abs(-15) from dual;=15

Ceil(n) Select ceil(44.778) from dual;=45

Cos(n) Select cos(180) from dual;=-.59846

Cosh(n) Select cosh(0) from dual;=7446921003

Exp(n) Select exp(4) from dual;=54.5982


Floor(n) Select floor(100.2) from dual;=100

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

Mod(m,n) Select mod(10,2) from dual;=0

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

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

Sqrt(n) Select sqrt(4) from dual;

After undergoing this laboratory module, the student should be able to write queries using
conversion functions, stri ng, number and date functions.

Exercise
1. Convert 12345 to string.

2. Display system date after converting to varchar2 data type.

3. Display system date in ‘MON-DD-YYYY‘ format after converting to varchar2 data type.

4. Convert string ‘123.45‘ to number data type.

5. Concate the string ‘Rajesh‘ with ‘Raghu‘

6. Concate bid & bname of Boats & display along with color.

7. Lpad the string ‘Rajesh‘ to length 30 with the set of characters in string ‘*‘

8. Lpad the string bname to length 20 with ‘*’ set of characters and string color by ‘/‘.
9. Rpad the string ‘Rajesh‘ to length 30 with the set of characters in string ‘*’

10. Rpad the string sname to length 25 with ‘*‘ set of characters and remaining attributes in
normal way.

11. Rpad the string bname to length 20 with ‘*‘ set of characters and lpad the same to
make it length 30 with ‘#‘ and remaining attributes in normal way.

12. Display all sailors information by removing characters of sname if starts with ‘R‘.

13. Display all sailors information by removing characters of sname if starts with ‘H‘

14. Display all sailors information by removing characters of sname if ends with ‘o‘.

15. Display all Boats information by removing characters of color if ends with ‘r‘.

16. Display all Boats information by showing their names in lower case.

17. Display all Sailors information by showing their names in lower case.

18. Display all Sailors information by showing their names in upper case.

19. Display all Boats information by showing their color in Upper case.

20. Display all Sailors information by showing their names in Capitalizing first char.

21. Capitalize first letter of each word in ‘rajesh raghu’.

22. Find the number of characters in the string ‘Computer Science and Engineering ‘.

23. Display length of string SID, SNAME from Sailors along with their values.

24. Display boats information by starting their names with 3rd character & show only 4
characters.

25. Display the index of string ‘AB‘ after 2nd character & 3rd occurrence in the given string
‘ABCDABCDABABAB‘.
26. Replace ‘A‘ with ‘D‘ in the given string ‘ABCDABCDABABAB‘.

27. Display Sailors information by replacing ‘A‘ with ‘I‘ from SNAME, if any.

28. Display BNAME by replacing ‘ER‘ with ‘MA‘.

29. Display the system date for a system.

30. Display next date on DAY after date D. Ex: Display date on Thu after 20th Feb, 2018.

31. Display SID, Day of Reservation by adding 20 months to given day.


32. Display SID, Day of Reservation and date corresponding to last date of the month.

33. Display SID, Day of Reservation and months between System Date & day of reservation.

34. Find least value in 12, 53, 17, 2.

35. Find least value in '12', '53', '17', '2'

36. Find least value in 'APPLES', 'ORANGES', and ‗BANANAS‘

37. Find greatest value in 12, 13, 17, 2.

38. Find greatest value in '12', '13', '17', '2'


39. Find greatest value in 'APPLES', 'ORANGES', 'BANANAS'

40. Truncate the 5632.98345 number to 0, 1, 2 decimal places.

41.Round off the 5632.98345 number to 0, 1, 2 decimal places.

You might also like