0% found this document useful (0 votes)
15 views52 pages

Ad22302-Dbms-Unit 2

Uploaded by

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

Ad22302-Dbms-Unit 2

Uploaded by

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

UNIT II - RELATIONAL

MODEL AND SQL

CO2: APPLY SQL QUERIES TO CREATE, MANIPULATE AND QUERY THE DATABASE.
● Relational model concepts

● Integrity constraints


TOPICS
SQL Data manipulation

● SQL Data definition

● Views

● SQL programming
RELATIONAL MODEL CONCEPTS

A relational database consists of a collection of tables, each of which is assigned a


unique name.

Or

 The relational model represents the database as a collection of relations.

 Informally, each relation resembles a table of values or a flat file of records.

 It is called a flat file because each record has a simple linear or flat structure.
EXAMPLE
EXAMPLE
COMPONENTS
Relation : two-dimensional table used to store a collection of data elements.

Tuple : row of the relation, showing a real-world entity.

Attribute/field : column of the relation, representing 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.


COMPONENTS
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, ...)

For our student relation example, the relational schema will be:

Student(roll_number integer, name varchar(20), cgpa float)


COMPONENTS

Relational instance : it is the collection of records present in the

relation at a given time.

Relation key : it is an attribute or a group of attributes that can be used

to uniquely identify an entity in a table.


OPERATIONS IN RELATIONAL MODEL
● Four basic operations performed on relational database model are
● Insert
● Update
● Delete and
● Select
● Insert is used to insert data into the relation
● Delete is used to delete tuples from the table.
● Modify allows you to change the values of some attributes in existing tuples.
● Select allows you to choose a specific range of data.
KEYS
A key is a set of attributes that can identify each tuple uniquely in the given relation.
There are various types of keys in dbms-
PRIMARY KEY
PRIMARY KEY is a column or group of columns in a table that uniquely identify
every row in that table.
A table cannot have more than one primary key.
Rules for defining Primary key:
Two rows can't have the same primary key value
It must for every row to have a primary key value.
The primary key field cannot be null.
EXAMPLE:

In the following example, <code>StudID</code> is a Primary Key.


FOREIGN KEY

• FOREIGN KEY is a column that creates a relationship between two tables. The
purpose of Foreign keys is to maintain data integrity.

• 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 "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.

• The "PersonID" column in the "Orders" table is a FOREIGN KEY in the


"Orders" table.
ALTERNATE KEYS
• ALTERNATE KEYS is a column or group of columns in a table that uniquely
identify every row in that table. A table can have multiple choices for a primary
key but only one can be set as the primary key. All the keys which are not
primary key are called an Alternate Key.
• Example:
• In this table, StudID, Roll No, Email are qualified to become a primary key. But
since StudID is the primary key, Roll No, Email becomes the alternative key.
SUPER KEY
• A super key is a set of one or more attributes that
can uniquely identify a row in a table.
• Example:

In the above-given example, EmpSSN and


EmpNum name are superkeys.
CANDIDATE KEY

The minimal set of attributes that can uniquely identify a tuple is known
as a candidate key. For Example, STUD_NO in STUDENT relation.
A table can have multiple candidate keys but only a single primary key.
Properties of Candidate key:
• It must contain unique values
• Candidate key may have multiple attributes
• Must not contain null values
• It should contain minimum fields to ensure uniqueness
• Uniquely identify each record in a table
Example: In the given table Stud ID, Roll No, and email are candidate
keys which help us to uniquely identify the student record in the table.
SCHEMA OF UNIVERSITY DATABASE
SCHEMA DIAGRAM OF UNIVERSITY DATABASE
INTEGRITY CONSTRAINTS

 Primary Key constraint

 Foreign Key constraint

 Not null constraint


PRIMARY KEY CONSTRAINT

create table department (dept name varchar (20), building varchar (15),
budget numeric (12,2), primary key (dept name));

- no tuple can have a null value for a primary-key attribute, and


- no two tuples in the relation can be equal on all the primary-key attributes
FOREIGN KEY CONSTRAINT
create table department (dept name create table course (course id varchar (7),
The definition of the course table has a declaration “foreign key
varchar (20), title varchar (50), dept name varchar (20),
(dept name) references department”. This foreign-key declaration specifies that
building varchar (15), budget numeric credits numeric (2,0), primary key (course
for each course tuple, the department name specified in the tuple must exist
(12,2), id),
in the primary key attribute (dept name) of the department relation.
primary key (dept name)); foreign key (dept name) references
department);
The definition of the course table has a declaration “foreign key

(dept name) references department”.

This foreign-key declaration specifies that, for each course tuple,

the department name specified in the tuple must exist in the

primary key attribute (dept name) of the department relation.


NOT NULL CONSTRAINT

The not null constraint on an attribute specifies that the null value is not allowed for
that attribute.
create table instructor(ID varchar (5), name varchar (20) not null, dept name varchar
(20), salary numeric (8,2), primary key (ID), foreign key (dept name) references
department);
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.
DATABASE LANGUAGES
DATA DEFINITION LANGUAGE

● The language is used to create database, tables, alter them, etc. With this, you can also rename the
database, or drop them. It specifies the database schema.
● The DDL statements include −
● CREATE: Create new database, table, etc.
● ALTER: Alter existing database, table, etc.
● DROP: Drop the database
● RENAME: Set a new name for the table.
● CREATE Command
● The create command defines each column of the table uniquely. Each column has minimum of
three attributes. Each table column definition is separated from the other by a comma. Finally, the
SQL statement is terminated with a semicolon.
● Syntax:
● Create table table_name
● {column_name1 data type1, column_name2 data type2,……….
● column_name n data type n};
● Example:
● Create table student(reg_no int,name char(20),address varchar2(10),dob date);
● DROP Command
● Drop command will destroy the table and all data which will be recorded in it.
● Syntax:
● Drop table table_name;
● Example:
● Drop table student;
RENAME Command
Rename command renames the table name with a new name.
Syntax:
RENAME <OldTableName> TO <NewTableName>
Example:
RENAME <Student> TO <Stu>

ALTER Command: By The use of ALTER TABLE Command we can modify our
exiting table.
Adding New ColumnsThis command is used to add new columns.
Syntax:
ALTER TABLE table_name ADD (NewColumnName DataType......n);
Example:
ALTER TABLE Student ADD (Age number(2), Marks number(3));
DATA MANIPULATION LANGUAGE

● The language used to manipulate the database like inserting data, updating table, retrieving record
from a table, etc. is known as Data Manipulation Language −
● SELECT: Retrieve data from the database
● INSERT: Insert data
● UPDATE: Update data
● DELETE: Delete all records
INSERT command
Insert command is used to insert data into a table.
Syntax:
INSERT into table_name values(data1,data2,..)
Example:
Consider a table Student with following fields.
INSERT into Stud values(101,'Adam’,’Nashik’,15);
Select- SELECT statement retrieves data from table
Syntax
SELECT attribute_list FROM table_list <WHERE condition>;
The attributes are those you want to see in the result, the tables are those required for the
query, the condition is a boolean expression that specifies which tuples are to be retrieved by
the query.
Example: Select * from Stud;
Select * from Stud where rno=101;
Select Name, Address from Stud;
Select Name, Address from Stud where rno=1
Select Name from Stud where address=‘Nashik’;
Update- UPDATE of one or more selected tuples
Syntax
UPDATE tablename SET attrx = new_value, <WHERE condition>;
Example:
Update Stud Set Name= ‘shruti’ where rollno=1 (Only name field of row
having rollno as 1 will be changed as ‘Shruti’)
Update Stud Set Name= ‘Shruti’ (name field of All row will be changed as
‘Shruti’)
Delete –DELETE tuples from relation
Syntax
DELETE FROM tablename <WHERE condition>
It removes zero, one or many tuples; The WHERE clause is optional; if it is left out
all tuples are removed, but the table still exists; it is empty.
Example: DELETE FROM Stud WHERE name= ‘shruti’;
( Only delete rows that satisfy the condition)
DELETE FROM Stud;
(Delete all rows)
UNIVERSITY DATABASE
VIEWS

• Views in SQL are considered as a virtual table. A view also contains rows and
columns.
• To create the view, we can select the fields from one or more tables present in
the database.
• A view can either have specific rows based on certain condition or all the rows
of a table.
• is a single table that is derived from other tables
VIEWS - SYNTAX

● CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;
● CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;
● SELECT * FROM DetailsView;
CREATING VIEW FROM MULTIPLE TABLES
● CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.
MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
● SELECT * FROM MarksView;
MATERIALIZED VIEWS
● Certain database systems allow view relations to be stored, but they make sure
that, if the actual relations used in the view definition change, the view is kept up-
to-date. Such views are called materialized views.
● a duplicate data table created by combining data from multiple existing tables for
faster data retrieval.
● The process of keeping the materialized view up-to-date is called materialized
view maintenance.
● View maintenance can be done immediately when any of the relations on which
the view is defined is updated.
DELETING VIEW

● A view can be deleted using the Drop View statement.


● Syntax
● DROP VIEW view_name;
ACCESSING SQL FROM A PROGRAMMING LANGUAGE

● SQL provides a powerful declarative query language.


● a database programmer must have access to a general-purpose
programming language for at least two reasons:
● Not all queries can be expressed in SQL, since SQL does not provide the
full expressive power of a general-purpose language. That is, there exist
queries that can be expressed in a language such as C, Java, or Python
that cannot be expressed in SQL. To write such queries, we can embed
SQL within a more powerful language.
Nondeclarative actions—such as printing a report, interacting with a
user, or sending the results of a query to a graphical user interface—
cannot be done from within SQL. Applications usually have several
components, and querying or updating data are only one component;
other components are written in general purpose programming
languages. For an integrated application, there must be a means to
combine SQL with a general-purpose programming language.
● There are two approaches to accessing SQL from a general-purpose programming
language:
● Dynamic SQL
● A general-purpose program can connect to and communicate with a database
server using a collection of functions (for procedural languages) or methods (for
object-oriented languages). Dynamic SQL allows the program to construct an SQL
query as a character string at runtime, submit the query, and then retrieve the
result into program variables a tuple at a time. The dynamic SQL component of
SQL allows programs to construct and submit SQL queries at runtime.
● Embedded SQL
● Like dynamic SQL, embedded SQL provides a means by which a program can
interact with a database server. However, under embedded SQL, the SQL
statements are identified at compile time using a preprocessor, which translates
requests expressed in embedded SQL into function calls. At runtime, these function
calls connect to the database using an API that provides dynamic SQL facilities but
may be specific to the database that is being used.
The SQL standard defines embeddings of SQL in a variety of
programming languages, such as C, C++, Cobol, Pascal, Java, PL/I,
and Fortran.
A language in which SQL queries are embedded is referred to as a
host language, and the SQL structures permitted in the host language
constitute embedded SQL.
Programs written in the host language can use the embedded SQL
syntax to access and update data stored in a database.
An embedded SQL program must be processed by a special
preprocessor prior to compilation.
To identify embedded SQL requests to the preprocessor, we use the
EXEC SQL statement; it has the form:
EXEC SQL <embedded SQL statement >;;
Before executing any SQL statements, the program must first
connect to the database.
Variables of the host language can be used within embedded SQL
statements, but they must be preceded by a colon (:) to distinguish
them from SQL variables.
To iterate over the results of an embedded SQL query, we must
declare a cursor variable, which can then be opened, and fetch
commands issued in a host language loop to fetch consecutive
rows of the query result.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy