Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Chapter 1 Creating Relational Database

The document discusses the concepts and components of relational database design including data structure, data integrity, data manipulation and characteristics of relational databases. It also describes various relational algebra operators, normalization, RDBMS software, database terminology and mapping cardinality.

Uploaded by

saniya kadmude
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Chapter 1 Creating Relational Database

The document discusses the concepts and components of relational database design including data structure, data integrity, data manipulation and characteristics of relational databases. It also describes various relational algebra operators, normalization, RDBMS software, database terminology and mapping cardinality.

Uploaded by

saniya kadmude
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

CHAPTER 1 08 MARKS

Creating Relational
Database
RELATIONAL DATABASE DESIGN
Concept of relational database design:
 Edgar Codd introduced the Relational Model as
general model of data.
 Definition: A relational database is collectively
combination of data structure, storage and
retrieval operations and integrity constraints.
 RDBMS is the basis for SQL, and for all modern
database systems like MS SQL Server, IBM DB2,
Oracle, MySQL and Microsoft Access.
COMPONENTS OF RELATIONAL
DATABASE:

 Data structure-
 set of relations and set of domains that define the
way data can be represented.
 Data integrity-
 integrity rules that define the procedure to protect
the data.
 Data manipulation-
 the operations that can be performed on the data.
RELATIONAL DATABASE CHARACTERISTICS:
 Data in the relational database must be represented
in tables, with values in columns within rows.
 Data within a column must be accessible by specifying
the table name, the column name, and the value of the
primary key of the row.
 The DBMS must support an active on-line catalogue.
 The DBMS must support at least one language that
can be used independently and from within programs,
and supports data definition operations, data
manipulation, constraints, and transaction
management.
 Views must be updatable by the system.
 The DBMS must support insert, update, and delete
operations on sets.
RELATIONAL DATABASE CHARACTERISTICS:
 The DBMS must support logical data independence.
 The DBMS must support physical data independence.

 Integrity constraints must be stored within the


catalogue, separate from the application.
 The DBMS must support distribution independence.
The existing application should run when the existing
data is redistributed or when the DBMS is
redistributed.
 If the DBMS provides a low level interface (row at a
time), that interface cannot bypass the integrity
constraints
ADVANTAGES OF USING RELATIONAL MODEL:
 Simplicity: A relational data model is simpler than the
hierarchical and network model.
 Structural Independence: The relational database is
only concerned with data and not with a structure. This
can improve the performance of the model.
 Easy to use: The relational model is easy as tables
consisting of rows and columns is quite natural and
simple to understand
 Query capability: It makes possible for a high-level
query language like SQL to avoid complex database
navigation.
 Data independence: The structure of a database can
be changed without having to change any application.
 Scalable: Regarding a number of records, or rows, and
the number of fields, a database should be enlarged to
enhance its usability.
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.
DATABASE NORMALIZATION
 Database normalization is the process of efficiently
organizing data in a database.
 There are two reasons of this normalization process −
 Eliminating redundant data, for example, storing the
same data in more than one table.
 Ensuring data dependencies make sense.
 Both these reasons are worthy goals as they reduce
the amount of space a database consumes and
ensures that data is logically stored.
 Here are the most commonly used normal forms:
 First normal form(1NF)
 Second normal form(2NF)
 Third normal form(3NF)
 Boyce & Codd normal form (BCNF)
DIFFERENT TYPES OF RDBMS SOFTWARE:

 MySQL,
 MS Access,

 Oracle,

 Sybase,

 Informix,

 Postgres and SQL Server .


DIFFERENT RELATIONAL ALGEBRA
OPERATORS:
 The relational algebra is a procedural query
language
 It consists of a set of operations that take one or two
relations as input and produce a new relation as
their result .
 The fundamental operations of relational algebra
are as follows −
 Select (σ)
 Project (π)

 Union (U)

 Set different (-)

 Cartesian product (X)

 Intersection

 Rename (ρ)
UNARY OPERATIONS

 These are those operations, which involve only


one relation or table
 These are:
 Select
 Project
BINARY OPERATIONS
 These are those operations, which involve pairs of
relations and are, therefore called binary
operations
 The input for these operations is two relations
and they produce a new relation without changing
the original relations
 These operations are:
 Union
 Set difference
 Cartesian product
SELECT OPERATION
 This is used to fetch rows(tuples) from table(relation)
which satisfies a given condition.
 The select operation is performed to select certain
rows or tuples of a table, so it performs its action on
the table horizontally.
 Denoted by lower Greek letter sigma (σ)

 In selection operation the comparison operators like


<, >, =, <=, >=, <> can be used in the predicate
 Syntax: σp(r)
SELECT OPERATION EXAMPLE:
PROJECTION OPERATOR(Π)
 Project operation is used to project only a certain
set of attributes of a relation.
 It produces a vertical subset of the table,
extracting the values of specified columns,
eliminating duplicates, and placing the values in
a new table
 Projection is denoted by a Greek letter (Π )

 Syntax: ∏A1, A2...(r)


 where A1, A2 etc are attribute names(column
names).
EXAMPLE OF PROJECTION
COMPOSITION OF RELATIONAL
OPERATORS

 The relational operators like select and project


can also be used in nested forms iteratively
 As the result of an operation is a relation so this
result can be used as an input for other operation
 Order is very important.
UNION OPERATOR (U):
 This operation is used to fetch data from two
relations(tables) or temporary relation(result of
another operation).
 For this operation to work, the relations(tables)
specified should have same number of
attributes(columns) and same attribute domain.
Also the duplicate tuples are automatically
eliminated from the result.
 It is denoted by U

 Syntax: A ∪ B
 where A and B are relations.
EXAMPLE OF UNION
INTERSECTION OPERATION

 The intersection operation also has the


requirement that both the relations should be
union compatible i.e they are of same degree and
same domains.
 It is represented by ∩.

 If R and S are two relations and we take


intersection of these two relations then the
resulting relation would be the set of tuples,
which are in both R and S .
 Just like union intersection is also commutative.
R∩ S=S∩ R
EXAMPLE OF INTERSECTION OPERATION
SET DIFFERENCE OPERATOR (-)
 This operation is used to find data present in one
relation and not present in the second relation.
This operation is also applicable on two relations,
just like Union operation.
 Syntax: A - B
 where A and B are relations.
EXAMPLE OF SET DIFFERENCE
CARTESIAN PRODUCT OPERATOR (X)
 This is used to combine data from two different
relations(tables) into one and fetch data from the
combined relation.
 Syntax: A X B
RENAME OPERATION OPERATOR (Ρ)
 This operation is used to rename the output
relation for any query operation which returns
result like Select, Project etc. Or to simply
rename a relation(table)
 Syntax:
 ρ(RelationNew, RelationOld)
NATURAL JOIN
 Allow us to combine certain selections and a
Cartesian product into one operation.
 Must be a common attribute between two table.
Denoted by (⋈)
 Syntax:
 πAttributes_name(σCommon_column_name=Commo
n_column_name(table1×table2)
 SQL-SELECT * FROM cricket natural join football;
OUTER JOIN
 Extension of Natural join.
 Deals with missing data in Natural Join.

 Normally 3 types
 Left outer Join( ):Returns all values of left table
 Right outer join(⟖):Returns all values of right table
 Full outer join(⟗):Returns all values of both table. If
no match found it returns NULL
RDBMS TERMINOLOGY:
RDBMS TERMINOLOGY:
 Relation(Table): a relation is a collection of data
elements organized in terms of rows and columns.
 Attribute(Field): A table consists of several
records(row), each record can be broken down into
several smaller parts of data known
as Attributes. Column are also called as attribute.
 Domain: Every attribute has some predefined value
scope, known as Attribute Domain.
 When an attribute is defined in a relation(table), it is
defined to hold only a certain type of values, which is
known as Attribute Domain.
 Tuple (Record): A single entry in a table is called a
Tuple or Record or Row. A tuple in a table represents
a set of related data.
CARDINALITY:
 cardinality refers to the relationship between two
tables. Relationship can be of four types
 One to One
 One to Many
 Many to One
 Many to Many
DIFFERENT TYPES OF MAPPING
CARDINALITY

 Consider a binary relationship set R on entity


sets A and B.
1. one-to-one (1:1)- an entity in A is related to at
most one entity in B, and an entity in B is related
to at most one entity in A.
DIFFERENT TYPES OF MAPPING
CARDINALITY

2. one-to-many (1:N)- an entity in A is related to


any number of entities in B, but an entity in B is
related to at most one entity in A.
DIFFERENT TYPES OF MAPPING
CARDINALITY

3.many-to-one(n:1) - an entity in A is related to at


most one entity in B, but an entity in B is related to
any number of entities in A.
DIFFERENT TYPES OF MAPPING
CARDINALITY

4. many-to-many(M:N) - an entity in A is related


to any number of entities in B, but an entity in B is
related to any number of entities in A.
DEGREE OF RELATIONSHIP

 It signifies the number of entities involved in a


relationship.
 Degree of a relationship can be classified into
following types:
 Unary relationship
 Binary relationships
 Ternary relationship
 Quaternary relationship
TYPES OF DEGREE OF RELATIONSHIP
 Unary relationship:
 If only single entity is involved in a relationship then
it is a unary relationship.
 For example, An employee(manager) supervises
another employee.
TYPES OF DEGREE OF RELATIONSHIP
 Binary relationships:-
 when two entities are associated to form a relation,
then it is known as a binary relationship.
 For example, teacher teaches student.
TYPES OF DEGREE OF RELATIONSHIP
 Ternary relationships:-
 when three entities are associated to form a relation,
then it is known as a ternary relationship.

 Quaternary relationships:-
 when four entities are associated to form a relation,
then it is known as a quaternary relationship.
INTRODUCTION TO SQL
 SQL is Structured Query Language, which is a
computer language for storing, manipulating and
retrieving data stored in a relational database.
 Characteristics of SQL
 SQL is easy to learn.
 SQL is used to access data from relational database
management systems.
 SQL can execute queries against the database.
 SQL is used to describe the data.
 SQL is used to define the data in the database and
manipulate it when needed.
 SQL is used to create and drop the database and table.
 SQL is used to create a view, stored procedure, function in
a database.
 SQL allows users to set permissions on tables, procedures,
and views.
ADVANTAGES OF SQL:
 High speed: Using the SQL queries, the user can
quickly and efficiently retrieve a large amount of records
from a database.
 No coding needed: In the standard SQL, it is very easy
to manage the database system. It doesn't require a
substantial amount of code to manage the database
system.
 Well defined standards: Long established are used by
the SQL databases that are being used by ISO and ANSI.
 Portability: SQL can be used in laptop, PCs, server and
even some mobile phones.
 Interactive language: SQL is a domain language used
to communicate with the database. It is also used to
receive answers to the complex questions in seconds.
 Multiple data view: Using the SQL language, the users
can make different views of the database structure.
DATATYPES IN SQL:
 SQL Datatype is used to define the values that a
column can contain.
 Every column is required to have a name and
data type in the database table.
DATATYPES IN SQL:
 char:It has a maximum length of 8000 characters.
It contains Fixed-length non-unicode characters.
 Varchar:It has a maximum length of 8000
characters. It contains variable-length non-unicode
characters.
 text:It has a maximum length of 2,147,483,647
characters. It contains variable-length non-unicode
characters.
 date:It is used to store the year, month, and days
value.
 Time:It is used to store the hour, minute, and
second values.
DATATYPES IN SQL:
 Int:It is used to specify an integer value.
 Smallint:It is used to specify small integer
value.
 Decimal:It specifies a numeric value that can
have a decimal number.
 Numeric:It is used to specify a numeric value.

 Binary:It has a maximum length of 8000 bytes.


It contains fixed-length binary data.
 Varbinary:It has a maximum length of 8000
bytes. It contains variable-length binary data.
PURPOSE OF DDL, DQL, DML, DCL
AND TCL COMMANDS:

 These SQL commands are mainly categorized


into following categories as:
 1. DDL – Data Definition Language
 2. DQL – Data Query Language
 3. DML – Data Manipulation Language
 4. DCL – Data Control Language
 5. TCL - Transaction Control Language
1. DDL(DATA DEFINITION LANGUAGE) :
 DDL or Data Definition Language actually consists of the
SQL commands that can be used to define the database
schema.
 It simply deals with descriptions of the database schema
and is used to create and modify the structure of database
objects in the database.
 Examples of DDL commands:
a)CREATE – is used to create the database or its objects (like
table, index, function, views, store procedure and triggers).
b)DROP – is used to delete objects from the database.
c)ALTER-is used to alter the structure of the database.
d)TRUNCATE–is used to remove all records from a table,
including all spaces allocated for the records are removed.
e)COMMENT –is used to add comments to the data dictionary.
f)RENAME –is used to rename an object existing in the database.
g)DESC-is used to show the structure (Schema)of database object.
DQL (DATA QUERY LANGUAGE) :
 DML statements are used for performing queries
on the data within schema objects.
 The purpose of DQL Command is to get some
schema relation based on the query passed to it.
 Example of DQL:
 SELECT – is used to retrieve data from the a
database
DML(DATA MANIPULATION LANGUAGE)
 The SQL commands that deals with the
manipulation of data present in the database
belong to DML or Data Manipulation Language
and this includes most of the SQL statements.
 Examples of DML:

 INSERT – is used to insert data into a table.


 UPDATE – is used to update existing data
within a table.
 DELETE – is used to delete records from a database
table.
DCL(DATA CONTROL LANGUAGE) :
 DCL includes commands such as GRANT and
REVOKE which mainly deals with the rights,
permissions and other controls of the database
system.
 Examples of DCL commands:

 GRANT-gives user’s access privileges to


database.
 REVOKE-withdraw user’s access privileges
given by using the GRANT command.
TCL(TRANSACTION CONTROL LANGUAGE) :

 TCL commands deals with the transaction within


the database.
 Examples of TCL commands:

 COMMIT– commits a Transaction.


 ROLLBACK– rollbacks a transaction in case
of any error occurs.
 SAVEPOINT–sets a savepoint within a
transaction.
 SET TRANSACTION–specify characteristics
for the transaction.
DDL COMMANDS:
A. CREATE:
1. CREATE DATABASE
 The SQL CREATE DATABASE statement is used
to create a new SQL database.
Syntax
CREATE DATABASE DatabaseName;
Example:
SQL> CREATE DATABASE College;
 Once a database is created, you can check it in the
list of databases as follows −
SQL> SHOW DATABASES;
A. CREATE:
2. CREATE TABLE
 The SQL CREATE TABLE statement is used to
create a new table.
CREATE TABLE TABLE_NAME (COLUMN_NAME D
ATATYPES(SIZE),…COLUMNName n
DATATYPE(SIZE));
 Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20),
Email VARCHAR2(100), DOB DATE);
B.ALTER COMMAND
B.ALTER command
 alter command is used for altering the table
structure, such as,
 to add a column to existing table
 to rename any existing column
 to change datatype of any column or to modify its size.
 to drop a column from the table.
B.ALTER COMMAND
 Add a new Column
Using ALTER command we can add a column to
any existing table.
Syntax:
ALTER TABLE table_name ADD(column_name
datatype);
Example:
ALTER TABLE student ADD(address VARCHAR(200));
B.ALTER COMMAND
 Modify an existing Column
ALTER command can also be used to modify data
type of any existing column.
 syntax:
ALTER TABLE table_name modify( column_name datatype);
 Example :
ALTER TABLE student MODIFY(address varchar(300));
 Rename a Column
Using ALTER command you can rename an existing
column.
 Syntax:
ALTER TABLE table_name RENAME old_column_name TO
new_column_name;
 Example:
ALTER TABLE student RENAME address TO location;
B.ALTER COMMAND
 Drop a Column
 ALTER command can also be used to drop or remove
columns.
 Syntax:
ALTER TABLE table_name DROP(column_name);
 Example:
ALTER TABLE student DROP(address);
C. TRUNCATE COMMAND

TRUNCATE command
 TRUNCATE command removes all the records
from a table. But this command will not destroy
the table's structure. When we use TRUNCATE
command on a table its (auto-increment) primary
key is also initialized.
 syntax:
TRUNCATE TABLE table_name;
 Example :
TRUNCATE TABLE student;
 The above query will delete all the records from the
table student.
D. DROP COMMAND
 DROP command
 DROP command completely removes a table from the
database. This command will also destroy the table
structure and the data stored in it.
syntax:
DROP TABLE table_name;
 Example:
DROP TABLE student;
 The above query will delete the Student table
completely.
 It can also be used on Databases, to delete the
complete database.
 For example, to drop a database,
DROP DATABASE Test;
 The above query will drop the database with name
Test from the system
E. RENAME QUERY
 RENAME query
 RENAME command is used to set a new name
for any existing table.
 syntax:
RENAME TABLE old_table_name to new_table_name;
 Example:
RENAME TABLE student to students_info;
 The above query will rename the table student to
students_info.
F. DESC QUERY:

 DESC Query:
 DESCRIBE or DESC(both are same) command
to describe the structure of a table.
Syntax:
DESCRIBE one;
OR
DESC one;
USE OF DATA CONSTRAINTS:
 Relational constraints are a set of rules. It is used to
maintain the quality of information.
 Integrity constraints ensure that the data insertion,
updating, and other processes have to be performed in
such a way that data integrity is not affected.
 Thus, integrity constraint is used to guard against
accidental damage to the database.
 Types of Relational integrity Constraints are as
follows
 1. Domain constraints
 2. Entity integrity constraints
 3. Referential Integrity Constraints
 4. Key Constraint
TYPES OF CONSTRAINTS:
 Entity integrity constraints -it provides a way
of ensuring that changes made to the database by
authorized users do not result in a loss of data
consistency.
 For example: Primary key, unique constraints
 Referential Integrity Constraints – It
establishes parent child relationship between two
tables.
 For example :Foreign key constraints
 Domain Constraint - It is used to maintain
value according to user specification .
 For example: Not null, check constraint.
FOLLOWING ARE SOME OF THE MOST
COMMONLY USED CONSTRAINTS AVAILABLE IN
SQL −
 a)NOT NULL Constraint − Ensures that a column
cannot have a NULL value.
 b)DEFAULT Constraint − Provides a default value
for a column when none is specified.
 c)UNIQUE Constraint − Ensures that all the values
in a column are different.
 d)PRIMARY Key − Uniquely identifies each
row/record in a database table.
 e)FOREIGN Key − Uniquely identifies a row/record in
any another database table.
 f)CHECK Constraint − The CHECK constraint
ensures that all values in a column satisfy certain
conditions.
 g)INDEX − Used to create and retrieve data from the
database very quickly.
SQL PRIMARY KEY CONSTRAINT

 The PRIMARY KEY constraint uniquely


identifies each record in a table.
 Primary keys must contain UNIQUE values, and
cannot contain NULL values.
 A table can have only ONE primary key; and in
the table, this primary key can consist of single
or multiple columns (fields).
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL PRIMARY KEY
 SQL PRIMARY KEY on ALTER TABLE

ALTER TABLE Persons


ADD PRIMARY KEY (ID);

DROP a PRIMARY KEY Constraint


ALTER TABLE Persons
DROP PRIMARY KEY;
SQL UNIQUE CONSTRAINT

 The UNIQUE constraint ensures that all values


in a column are different.
 Both the UNIQUE and PRIMARY KEY
constraints provide a guarantee for uniqueness
for a column or set of columns.
 A PRIMARY KEY constraint automatically has a
UNIQUE constraint.
 However, you can have many UNIQUE
constraints per table, but only one PRIMARY
KEY constraint per table.
SQL UNIQUE CONSTRAINT
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
 SQL UNIQUE Constraint on ALTER TABLE
ALTER TABLE Persons
ADD UNIQUE (ID);
SQL FOREIGN KEY CONSTRAINT
 A FOREIGN KEY is a key used to link two tables
together.
 A FOREIGN KEY is a field (or collection of fields)
in one table that refers to the PRIMARY KEY in
another table.
 The table containing the foreign key is called the
child table, and the table containing the
candidate key is called the referenced or parent
table.
EXAMPLE OF FOREIGN KEY
"Persons" table:
OrderID OrderNum PersonID
ber
1 77895 3
2 44678 3
3 22456 2
4
“ 24562 1

Orders" table:

PersonID LastName FirstName Age


1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
EXAMPLE OF FOREIGN KEY
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID
int FOREIGN KEY REFERENCES Persons(PersonID)
);
SQL NOT NULL CONSTRAINT
 The NOT NULL constraint enforces a column to
NOT accept NULL values.
 SQL NOT NULL on CREATE TABLE
 Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
 SQL NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age"
column when the "Persons" table is already created,
use the following SQL:
ALTER TABLE Persons MODIFY Age int NOT NULL;
SQL CHECK CONSTRAINT

 The CHECK constraint is used to limit the value


range that can be placed in a column.
 If you define a CHECK constraint on a single
column it allows only certain values for this
column.
 If you define a CHECK constraint on a table it
can limit the values in certain columns based on
values in other columns in the row.
EXAMPLE OF FOREIGN KEY
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
 SQL CHECK on ALTER TABLE
ALTER TABLE Persons
ADD CHECK (Age>=18);
SQL DEFAULT CONSTRAINT
 The DEFAULT constraint is used to provide a default value for a
column.
 The default value will be added to all new records IF no other
value is specified.
 SQL DEFAULT on CREATE TABLE
 The following SQL sets a DEFAULT value for the "City" column
when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
 SQL DEFAULT on ALTER TABLE
 To create a DEFAULT constraint on the "City" column when the
table is already created, use the following SQL:
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';
DIFFERENCE BETWEEN PRIMARY KEY
AND UNIQUE KEY

PARAMETER PRIMARY KEY UNIQUE KEY

Uniquely
Used to serve as a
determines a row
Basic unique identifier for
which isn’t primary
each row in a table.
key.

NULL value Cannot accept Can accept one


acceptance NULL values. NULL value.

Number of keys
Only one primary More than one
that can be defined
key unique key
in the table

Creates clustered Creates non-


Index
index clustered index
DIFFERENCE BETWEEN DELETE AND
TRUNCATE
No. DELETE TRUNCATE

1) DELETE is a DML command. TRUNCATE is a DDL


command.
2) We can use WHERE clause in We cannot use
DELETE command. WHERE clause with
TRUNCATE
3) DELETE statement is used to TRUNCATE statement is
delete a row from a table used to remove all the
rows from a table.

4) DELETE is slower than TRUNCATE statement


TRUNCATE statement. is faster than DELETE
statement.
5) You can rollback data after It is not possible to
using DELETE statement. rollback after using
TRUNCATE statement.

You might also like