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

7sql

Uploaded by

birungiderick887
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)
6 views

7sql

Uploaded by

birungiderick887
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/ 49

CHAPTER 7

Database Implementation Using the Relational


Model
By: Mumbere Sam - FICT.

Bachelor of Information Technology


Relational Model in DBMS

□ The relational model in DBMS is an abstract model used to organize


and manage the data stored in a database.
□ It stores data in two-dimensional inter-related tables, also known as
relations in which each row represents an entity and each column
represents the properties of the entity.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


model is known as a relational database management system
(RDBMS).
□ Hence, the relational model describes how data is stored in relational

databases.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Relational Model Concepts

□ Relation : Two-dimensional table used to store a collection of data


elements.
□ Tuple : Row of the relation, depicting a real-world entity.

□ Attribute/Field : Column of the relation, depicting properties that

define the relation.


□ Attribute Domain : Set of pre-defined atomic values that an attribute

can take i.e., it describes the legal values that an attribute can take.
□ Degree : It is the total number of attributes present in the relation.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Relational Model Concepts (2)

□ Cardinality : It specifies the number of entities involved in the relation


i.e., it is the total number of rows present in the relation.
□ Relational Schema : It is the logical blueprint of the relation i.e., it
describes the design and the structure of the relation. It contains the
table name, its attributes, and their types:
TABLE_NAME(ATTRIBUTE_1 TYPE_1, ATTRIBUTE_2 TYPE_2, ...)

□ Relational Instance : It is the collection of records present in the


relation at a given time.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


□ Relation Key : It is an attribute or a group of attributes that can be
used to uniquely identify an entity in a table or to determine the
relationship between two tables.
□ Relation keys can be of 6 different types:

□ Candidate Key
□ Super Key
□ Composite Key
□ Primary Key
□ Alternate Key
□ Foreign Key

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Constraints in Relational Model

□ Relational models make use of some rules to ensure the accuracy and
accessibility of the data.
□ These rules or constraints are known as Relational Integrity

Constraints.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Constraints

□ Domain Constraint : It specifies that every attribute is bound to have a


value that lies inside a specific range of values. It is implemented with
the help of the Attribute Domain concept.
□ Key Constraint : It states that every relation must contain an attribute or

a set of attributes (Primary Key) that can uniquely identify a tuple in that
relation. This key can never be NULL or contain the same value for two
different tuples.
□ Referential Integrity Constraint : It is defined between two inter-

related tables. It states that if a given relation refers to a key


attribute of a different or same table, then that key must exist in the
given relation.
© ISBAT UNIVERSITY - 2020. 21-Jan-23
Anomalies in Relational Model

□ Insertion Anomalies: It is the inability to insert data in the database


due to the absence of other data.

□ Deletion Anomalies - It is the accidental loss of data in the database


upon deletion of any other data element.

□ Modification/Update Anomalies - It is the data inconsistency that


arises from data redundancy and partial updation of data in the
database.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Advantages of using the relational model

□ Simple and Easy To Use -


□ Storing data in tables is much easier to understand and implement as compared to other storage
techniques.
□ Manageability -
□ Because of the independent nature of each relation in a relational database, it is easy to manipulate
and manage.
□ Query capability -
□ With the introduction of relational algebra, relational databases provide easy access to data via
high-level query language like SQL.
□ Data integrity -
□ With the introduction and implementation of relational constraints, the relational model can
maintain data integrity in the database.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Disadvantages of using the relational model

□ The performance of the relational model depends upon the number of


relations present in the database.
□ Hence, as the number of tables increases, the requirement of physical
memory increases.
□ The structure becomes complex and there is a decrease in the response

time for the queries.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


SQL
Introduction

□ SQL is the universal language used in the database world.

□ Most modern RDBMS products use some type of SQL dialect as their primary
query language.

□ SQL can be used to create or destroy objects, such as tables, on the database server
and to do things with those objects, such as put data into them or query for data.

□ Transact-SQL is Microsoft's implementation of the standard SQL.


□ Usually referred to as T-SQL, this language implements a standardized way to
communicate to the database.

□ The Transact-SQL language is an enhancement to SQL, the American National Standards Institute
(ANSI) standard relational database language.
□ It provides a comprehensive language that supports defining tables, inserting, deleting, updating, and
accessing the data in the table.
© ISBAT UNIVERSITY - 2020. 21-Jan-23
Transact-SQL 1-2

Transact-SQL is a powerful language offering features such as data types, temporary


objects, and extended stored procedures.

Scrollable cursors, conditional processing, transaction control, and exception and


error-handling are also some of the features which are supported by Transact-SQL.

The Transact-SQL language in SQL Server provides improved performance, increased


functionality, and enhanced features.

Enhancements include scalar functions, paging, sequences, meta-data discovery,


and better error handling support.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Transact-SQL 2-2
UNIVERSITY

SELECT LoginID
FROM Employee
WHERE JobTitle = 'Design Engineer'
□ Following figure shows the result of the SELECT statement:

□ Transact-SQL includes many syntax elements that are used by or that influence
most statements.
□ These elements include data types, predicates, functions, variables, expressions
21-Jan-23
TYPES OF SQL
(SUB LANGUAGES OR COMMANDS)
16

□ Data Definition Language (DDL)


0 CREATE , ALTER , DROP

□ Data Manipulation Language (DML)


D INSERT ,UPDATE ,DELETE

□ Data Query Language (DQL)


D SELECT

□ Data Control Language (DCL)


D GRANT , REVOKE

□ Transaction Control Language (TCL)


□ ROLLBACK , COMMIT , SAVEPOINT

© ISBAT UNIV 21-Jan-23


Data Definition Language (DDL)

DDL is used to define and manage all attributes and properties of a database,
including row layouts, column definitions, key columns, file locations, and storage
strategy.

DDL statements are used to build and modify the structure of tables and other
objects such as views, triggers, stored procedures, and so on.

For each object, there are usually CREATE, ALTER, and DROP statements (such
as, CREATE TABLE, ALTER TABLE, and DROP TABLE).

Most DDL statements take the following form:

CREATE ALTER DROP object_na


object_na me object_na me
me
In DDL statements, object_name can be a table, view, trigger, stored
procedure, and so on.
21-Jan-23
CREATE TABLE Command

CREATE TABLE statement syntax:

CREATE TABLE <table name>


( column 1 datatype , column2
datatype
)

c ISBAT UNIVERSITY - 2020.


Alter:
Adding a column

Syntax: Alter Table Tablename Add ColumnName


Example: Alter Table Person Add Dob datetime

Alter the Data type of a Column:


Syntax: Alter Table Tablename Alter Column ColumnName
Example: Alter Table Person Alter column First_name
varchar(50)

Drop a Column
Syntax: Alter Table Tablename Drop Column ColumnName
Example: Alter Table Person Drop Column DOB

Drop:

Drop Table Person

21-Jan-23
Data Manipulation Language (DML)

All database users can use these commands during the routine operations on a
database.

The different DML statements are as follows:

INSERT UPDATE DELETE statement


statement statement

21-Jan-23
INSERT Command

To insert a row into a table ;


INSERT statement syntax:

INSERT into <table name>


VALUES (‘valuel’,
‘value2’);
UPDATE Command

To Update the content of the table;


UPDATE statement syntax:

UPDATE <table name> set <attribute>


WHERE <condition>;

c ISBAT UNIVERSITY - 2020.


DELETE Command

To Delete the rows from the table;


DELETE statement syntax:

DELETE FROM <table


name>
WHERE <condition>;

c ISBAT UNIVERSITY - 2020.


DQL

To Retrieve the desired information from a table;


SELECT statement syntax:

SELECT * FROM <table name>;

SELECT statement

© ISBAT UNIVERSITY - 2020. 21-Jan-23


SELECT Statement

□ Used for queries on single or multiple tables


□ Clauses of the SELECT statement:
□ SELECT
□ List the columns (and expressions) to be returned from the query
□ FROM
□ Indicate the table(s) or view(s) from which data will be obtained
□ WHERE
□ Indicate the conditions under which a row will be included in the result
□ GROUP BY
□ Indicate categorization of results
□ HAVING
□ Indicate the conditions under which a category (group) will be included
□ ORDER BY

© ISBAT UNIVERSITY - 2020.


0 Sorls the result accord to specified criteri'a 21-Jan-23
Data Control Language (DCL)

Data is an important part of database, so proper steps should be taken to check that
no invalid user accesses the data.

DCL is used to control permissions on database objects.

Permissions are controlled by using the GRANT, REVOKE, and DENY statements.

DCL statements are also used for securing the database. The three basic DCL
statements are as follows:

GRANT statement REVOKE DENY


statement statement

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Transaction Control Language (DCL)
27

□ COMMIT: make all the changes in the database during a transaction


permanent.
COMMIT;

□ SAVEPOINT: Sets a mark or save point within a transaction. It defines a


location to which a transaction can return if part of the transaction is
conditionally cancelled or is not required.
SAVEPOINT <identifier>
□ ROLLBACK: Reverses all database modifications made in the active
transaction
ROLLBACK;

© ISBAT UNIV 21-Jan-23


Data Types

□ A data type is an attribute defining the type of data that an object can contain.
□ Data types must be provided for columns, parameters, variables, and functions that
return data values, and stored procedures that have a return code.
□ Transact-SQL includes a number of base data types, such as varchar, text, and int.
□ All data that is stored in SQL Server must be compatible with one of the base data
types.
□ The following objects have data types:
Columns present in tables and views

Parameters in stored procedures

Variables
Transact-SQL functions that return one or more data values of a specific data type

Stored procedures that have a return code belonging to the integer data type

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Data Types
□ SQL Server supports three kinds of data types:

System-defined Data Types

□ These data types are provided by SQL Server .


□ Following table shows the commonly used system-defined data types of SQL Server .

Description
int
A column of this type occupies 4 bytes of memory space. Is
typically used to hold integer values. Can hold integer data
from -2*31 (-2,147,483,648) to 2*31-1 (2,147,483,647).
smallint A column of this type occupies 2 bytes of memory space.
Can hold integer data from -32,768 to 32,767.
tiny int A column of this type occupies 1 byte of memory space. Can
hold integer data from 0 to 255.
bigint
A column of this type occupies 8 bytes of memory space. Can
hold data in the range -2A63 (-9,223,372,036,854,7 75,808) to
2A63-1 (9,223,372,036,854,775,807).
numeric A column of this type has fixed precision and scale.
money
A column of this type occupies 8 bytes of memory space.
Represents monetary data values ranging from -2A63/10000
(-922,337,203,685,477.5808) to 2A63-1
© ISBAT UNIVERSITY - 2021 (922,337,203,685,477.5807). 21-Jan-23
Data Types

Category Data Type Description


float A column of this type occupies 8 bytes of memory space.
Represents floating point number ranging from -1.79E
+308 through 1.79E+308.
Approximate Numerics
real A column of this type occupies 4 bytes of memory space.
Represents floating precision number ranging from -
3.40E+38 through 3.40E+38.
datetime
Date and Time Represents date and time. Stored as two 4-byte integers.
smalldatetime Represents date and time.
char
Stores character data that is fixed-length and non-Unicode.
varchar Stores character data that is variable-length and non-
Character String Unicode with a maximum of 8,000 characters.
text Stores character data that is variable-length and non-
Unicode with a maximum length of 2A31 - 1
(2,147,483,647) characters.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


DDL

DDL Commnds:
1. Create
2. Alter
3. Drop

Create Syntax:

Create table Tablename( column_name1 datatype,


column_name2 datatype...,)

Example:

create table person ( pid int, first_name varchar(30))

c ISBAT UNIVERSITY - 2020.


Alter:
Adding a column

Syntax: Alter Table Tablename Add ColumnName


Example: Alter Table Person Add Dob datetime

Alter the Data type of a Column:


Syntax: Alter Table Tablename Alter Column
ColumnName
Example: Alter Table Person Alter column First_name
varchar(50)

© ISBAT UNIVERSITY - 2020. 21-Jan-23


Drop a Column
Syntax: Alter Table Tablename Drop Column
ColumnName
Example: Alter Table Person Drop Column DOB

Drop:

Drop Table Person

c ISBAT UNIVERSITY - 2020.


SQL Constraints

© ISBAT UNIVERSITY - 2020. 21-Jan-23


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 - Uniquely identifies a row/record in another table
□ CHECK - Ensures that all values in a column satisfies a specific condition
□ DEFAULT - Sets a default value for a column when no value is specified ( not a constraint in Oracle
SQL )

© ISBAT UNIVERSITY - 2020. 21-Jan-23


You can define constraints syntactically in two ways:

□ As part of the definition of an individual column or attribute. This is called inline


specification.

□ As part of the table definition. This is called out-of-line specification.

NOT NULL constraints must be declared inline. All other constraints


can be declared either inline or out of line.

© ISBAT UNIVERSITY - 2020. 21-Jan-23


SQL NOT NULL Constraint

CREATE TABLE Persons


(

PID int NOT NULL,


LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
)
Age int

© ISBAT UNIVERSITY - 2020. 21-Jan-23


SQL UNIQUE Constraint

CREATE TABLE Persons (


PID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

ALTER TABLE Persons ADD UNIQUE (PID);

ALTER TABLE Persons ADD CONSTRAINT UC_Person UNIQUE


(PID);

ALTER TABLE Persons DROP CONSTRAINT UC Person;


© ISBAT UNIVERSITY - 2020. 21-Jan-23
SQL PRIMARY KEY Constraint UNIVERSITY
ISBAT^l

£Xv<c »

CREATE TABLE Persons (


PID int PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int

CREATE TABLE Persons ( PID int NOT NULL,


LastName varchar(255) NOT NULL, FirstName
varchar(255),
Age int,

© ISBAT UNIVERSITY - 2020. 21-Jan-23


SQL FOREIGN KEY Constraint
UIVTVERSITY

CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT
NULL, PersonID int, PRIMARY KEY (OrderID), CONSTRAINT
FK_PersonOrder FOREIGN KEY (PersonID )

REFERENCES Persons(PersonID)

ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
ALTER TABLE Employee
ADD FOREIGN KEY (DID) REFERENCES Department(DID);

ALTER TABLE Employee


ADD DID varchar2(10) REFERENCES Department(DID);

ALTER TABLE Orders


alter table employee add DID varchar(20) foriegn key
DROP CONSTRAINT FK PersonOrder; (did) references Department(did)
© ISBAT UNIVERSITY - 2020. 21-Jan-23
SQL CHECK Constraint

CREATE TABLE Persons (


ID int NOT NULL,
ALTER TABLE Persons ADD
LastName varchar2(255) NOT NULL,
FirstName varchar2(255), Constraint
Age int CHECK (Age>=18) Chk_age CHECK (Age>=18);
);

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar2(255) NOT NULL,
FirstName varchar2(255),
Age int,
City varchar2(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes') );

© ISBAT UNIVERSITY - 2020. 21-Jan-23


CREATE INDEX Syntax

The CREATE INDEX statement is used to create indexes in tables.

CREATE INDEX index_name


ON table_name (column1, column2, ...);

CREATE INDEX idx_pname ON Persons (LastName,


FirstName);

DROP INDEX index_name;

© ISBAT UNIVERSITY - 2020. 21-Jan-23


SQL DEFAULT
UNIVERSITY

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT ‘kampala'
);

Insert into persons values(50, ‘kayango', ‘mark', 25,default)


ALTER TABLE Persons MODIFY City DEFAULT ‘kampala';

ALTER TABLE Persons MODIFY City DEFAULT NULL;

© ISBAT UNIVERSITY - 2020. 21-Jan-23


( supplier_id numeric(4), supplier_name
varchar2(50), CONSTRAINT check_supplier_id
CHECK (supplier_id BETWEEN 100 and 9999)
);

© ISBAT UNIVERSITY - 2020. 21-Jan-23


ADD CONSTRAINT check_supplier_name
CHECK (supplier_name IN ('IBM', 'Microsoft', 'NVIDIA'));

© ISBAT UNIVERSITY - 2020. 21-Jan-23


DML

INSERT:
Syntax:
insert into tablename values (value1, value2....valueN)

Example:
insert into employee values(100,'George','Cloony',0781464113,
'15-Mar-2015',1500,'Entebbe')
using custom order:
insert into employee(EID,FIRST_NAME,LAST_NAME,SALARY,
HIRE-DATE,CITY,PHONE)
values(100,'ryan','reynolds',3000,'21-JUL-16','Entebbe',0752242243)

© ISBAT UNIVERSITY - 2020. 21-Jan-23


'V'V'V'V'V'V'V'V'V'VX'V'V'V'V'V'V'V'V'V'V'V'V'V

insert into employee values (102,'jack','reacher',074654114,'15-Nov-


2013',2500,'Jinja'), (103,'nick','Johanson',0747654327,'05-Sep-
2010',3500,'Mbarara'), (104,'reese','witherspoon',0787654329,'21-
May-2016',1500,Default),
(105,'katherine','langford',0756782100,'11-Jul-2015',1800,Default)

INSERT INTO first_table_name [(column1, column2, ... columnN)]


SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];

© ISBAT UNIVERSITY - 2020. 21-Jan-23


UPDATE:

Syntax:

Update tablename set column=value [where (condition)]

Example:

Update Employee set salary=2000 where eid=105

Update Employee set first_name='kathy' where eid=105

Update Employee set salary=2000,first_name='kathy' where eid=105

select * from employee

© ISBAT UNIVERSITY - 2020. 21-Jan-23


DELETE:
syntax:
Delete from Tablename [ where
(Condition) ]

Example:
Delete from Employee where eid=105
Delete from Employee where eid in(105,106,109) (or)
Delete from Employee where eid=105 or eid=106 or eid=109

© ISBAT UNIVERSITY - 2020. 21-Jan-23

You might also like