DBMS_2_UNIT- aktu
DBMS_2_UNIT- aktu
Relational data Model and Language: Relational Data Model Concepts, Integrity Constraints, Entity
Integrity, Referential Integrity, Keys Constraints, Domain Constraints, Relational Algebra, Relational
Calculus, Tuple and Domain Calculus. Introduction on SQL: Characteristics of SQL, Advantage of SQL.
SQL Data Type and Literals. Types of SQL Commands. SQL Operators and Their Procedure. Tables,
Views and Indexes. Queries and Sub Queries. Aggregate Functions. Insert, Update and Delete
Operations, Joins, Unions, Intersection, Minus, Cursors, Triggers, Procedures in SQL/PL SQL
Relation
A relation, also known as a table or file, is a subset of the Cartesian product of a list of domains characterized
by a name. And within a table, each row represents a group of related data values. A row, or record, is also
known as a tuple. The columns in a table is a field and is also referred to as an attribute.
The steps below outline the logic between a relation and its domains.
Given n domains are denoted by D1, D2, … Dn
And r is a relation defined on these domains
A Relational Database management System (RDBMS) is a database management system based on the
relational model introduced by E.F Codd. In relational model, data is stored in relations (tables) and is
represented in form of tuples (rows).
RDBMS is used to manage Relational database. Relational database is a collection of organized set of tables
related to each other, and from which data can be accessed easily. Relational Database is the most commonly
used database these days.
Relational Model:
RELATIONAL MODEL (RM) represents the database as a collection of relations. A relation is nothing but
a table of values. Every row in the table represents a collection of related data values. These rows in the table
denote a real-world entity or relationship.
The table name and column names are helpful to interpret the meaning of values in each row. The data are
represented as a set of relations. In the relational model, data are stored as tables. However, the physical
storage of the data is independent of the way the data are logically organized.
1. Attribute: Each column in a Table. Attributes are the properties which define a relation.
e.g., Student_Rollno, NAME,etc.
2. Tables – In the Relational model the relations are saved in the table format. It is stored
along with its entities. A table has two properties rows and columns. Rows represent
records and columns represent attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single record.
4. Relation Schema: A relation schema represents the name of the relation with its
attributes.
5. Degree: The total number of attributes which in the relation is called the degree of the
relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is called relation
key.
10. Attribute domain – Every attribute has some pre-defined value and scope which is
known as attribute domain
1 Adam 34 13000
Name
Adam
Alex
Stuart - 9/401, OC Street, Amsterdam
Ross
Constraints in Relational Model
While designing Relational Model, we define some conditions which must hold for data present in database
are called Constraints. These constraints are checked before performing any operation (insertion, deletion and
updation) in database. If there is a violation in any of constrains, operation will fail.
1. Domain constraints:
• Domain constraints can be defined as the definition of a valid set of values for an
attribute.
• The data type of domain includes string, character, integer, time, date, currency,
etc.
The value of the attribute must be available in the corresponding domain.
Example:
• The entity integrity constraint states that primary key value can't be null.
• This is because the primary key value is used to identify individual rows in
relation and if the primary key has a null value, then we can't identify those
rows.
• A table can contain a null value other than the primary key field.
Example:
3. Referential Integrity Constraints:
4. Key constraints
• Keys are the entity set that is used to identify an entity within its entity set
uniquely.
• An entity set can have multiple keys, but out of which one key will be the
primary key.
• A primary key can contain a unique and null value in the relational table.
Example:
RELATION ALGEBRA:
Relational algebra is a set of basic operations used to manipulate the data in relational model. These
operations enable the user to specify basic retrieval request. The result of retrieval is a new relation,
formed from one or more relation. These operations can be classified in two categories.
Basic/Fundamental Operations:
1. Select (σ)
2. Project (∏)
3. Union (𝖴)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)
Derived Operations:
1. Natural Join (⋈)
2. Left, Right, Full outer join (⟕, ⟖, ⟗)
3. Intersection (∩)
4. Division (÷)
Table: CUSTOMER
Customer_Name Customer_City
Steve Agra
Raghu Agra
Chaitanya Noida
Ajeet Delhi
Carl Delhi
Union Operator (𝖴):
Union operator is denoted by 𝖴 symbol and it is used to select all the rows (tuples) from two
tables (relations).
Lets discuss union operator a bit more. Let’s say we have two relations R1 and R2 both have
same columns and we want to select all the tuples(rows) from these relations then we can apply
the union operator on these relations.
Note: The rows (tuples) that are present in both the tables will only appear once in the union set.
In short you can say that there are no duplicates present after the union operation.
Syntax of Union Operator (𝖴)
table_name1 𝖴 table_name2 Union
Operator (𝖴) Example Table 1:
COURSE
Course_Id Student_Name Student_Id
-
C101 Aditya S901
C104 Aditya S901
C106 Steve S911
C109 Paul S921
C115 Lucy S931
Table 2: STUDENT
Student_Id Student_Name Student_Age
S901 Aditya 19
S911 Steve 18
S921 Paul 19
S931 Lucy 17
S941 Carl 16
S951 Rick 18
Query:
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
Output:
Student_Name
Aditya
Carl
Paul
Lucy
Rick
Steve
Note: As you can see there are no duplicate names present in the output even
though we had few common names in both the tables, also in the COURSE table
we had the duplicate name itself.
Student_Name
Aditya
Steve
Paul
Lucy
Set Difference is denoted by – symbol. Let’s say we have two relations R1 and R2
and we want to select all those tuples (rows) that are present in Relation R1
but not present in Relation R2, this can be done using Set difference R1 – R2.
Query:
Lets write a query to select those student names that are present in STUDENT
table but not present in COURSE table.
Carl
Rick
AA 100
BB 200
CC 300
Table 2: S
Col_X Col_Y
XX 99
YY 11
ZZ 101
Query:
Lets find the cartesian product of table R and S.
RXS
Output:
Col_A Col_B Col_X Col_Y
-
AA 100 XX 99
AA 100 YY 11
AA 100 ZZ 101
BB 200 XX 99
BB 200 YY 11
BB 200 ZZ 101
CC 300 XX 99
CC 300 YY 11
CC 300 ZZ 101
Note: The number of rows in the output will always be the cross product of
number of rows in each table. In our example table 1 has 3 rows and table 2 has 3
rows so the output has 3×3 = 9 rows.
Rename (ρ)
Rename (ρ) operation can be used to rename a relation or an attribute of a relation.
Rename (ρ) Syntax:
ρ(new_relation_name, old_relation_name)
Rename (ρ) Example
Let’s say we have a table customer, we are fetching customer names and we are
renaming the resulted relation to CUST_NAMES.
Table: CUSTOMER
Customer_Id Customer_Name Customer_City
- -
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi
Query:
ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))
Output:
CUST_NAMES
Steve
Raghu
Chaitanya
Ajeet
Carl
Relational Calculus:
Relational calculus is a non-procedural query language that tells the system what data
to be retrieved but doesn’t tell how to retrieve it.
Note: A non-procedural query language is a programming language that requires the programmer
to specify what the program should do, rather than how to do it. Non-procedural languages are also
known as declarative languages.
Tuple Relational Calculus (TRC):
Tuple Relational Calculus (TRC) is a non-procedural query language used in relational
databases, where queries are expressed using variables that represent tuples. Unlike SQL, where you
specify how to retrieve data (procedural), TRC specifies what data to retrieve without specifying the
exact procedures or steps to get the result.
In TRC, user describe the properties of the result, rather than how to compute it. The result of the
query is a set of tuples that satisfy the specified conditions.
In tuple calculus, a query is expressed as
{t|P(t)} OR {t|Condition(t)}..
Where:
• t is a tuple variable representing a tuple in the result.
• P(t) is a predicate (condition) that must be satisfied by the tuple t.
First_Name Last_Name Age
-
Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28
Lets write relational calculus queries.
Query to display the last name of those students where age is greater than 30
In DRC, queries specify conditions on individual fields or domains of relations, and the result is a set of
domain variables (values) that satisfy these conditions.
In domain relational calculus the records are filtered based on the domains. Again we take the
same table to understand how DRC works.Table: Student
First_Name Last_Name Age
Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28
Query to find the first name and age of students where student age is greater than27
{< First_Name, Age > | ∈ Student 𝖠 Age > 27}
Note:
The symbols used for logical operators are: 𝖠 for AND, ∨ for OR and ┓ for NOT.
Output:
First_Name Age
Ajeet 30
Chaitanya 31
Carl 28
Introduction to SQL
Structure Query Language (SQL) is a database query language used for storing and managing data in Relational
DBMS. SQL was the first commercial language introduced for E.F Codd's Relational model of database. Today
almost all RDBMS (MySql, Oracle, Infomix, Sybase, MS Access) use SQL as the standard database query
language. SQL is used to perform all types of data operations in RDBMS.
SQL Command
SQL defines following ways to manipulate data stored in an RDBMS.
DDL: Data Definition Language
This includes changes to the structure of the table like creation of table,altering table, deleting a
table etc.
All DDL commands are auto-committed. That means it saves all thechanges permanently in the
database.
Command Description
Create to create new table or database
Alter for alteration
Truncate delete data from table
Drop to drop a table
Rename to rename a table
DQL: Data Query Language: Data query language is used to fetch data from tables based on conditions that we
can easily apply.
Command Description
select retrieve records from one or more table
SQL Syntax
A database is a organized collection of data. Data is stored in relational database in form of tables. To
create, retrieve, update and delete from relational database, we use SQL queries.
SQL Statements
SQL statement tells the database that what information you would like toretrieve or what operation
you want to perform on the data.
For example:
Consider this table: STUDENT
STUDENT_NAME STU_AGE STU_ADDRESS
- -
Ajeet 30 Chennai
Chaitanya 31 Noida
Steve 29 Agra
Rahul 30 Gurgaon
SQL statement to fetch STUDENT_NAME from the table STUDENT:
SELECT STUDENT_NAME FROM STUDENT;
SQL INSERT INTO Statement: The INSERT INTO statement is used to insert new records
in a table.To insert a record into the table.
INSERT INTO table_name( column_name1, column_name2 ....column_nameN)
VALUES (value_1, value_2 .... value_N);
Below is a selection from the "Customers" table in the Northwind sample database:
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
1
Alfreds Futterkiste Alfred Obere Str. 57 Frankfurt 12209 Germany
Schmidt
Ana Trujillo Juan Avda. de la México
2 Emparedados y Constitución D.F. 05021 Mexico
helados 2222
UPDATE Customers
SET ContactName='Juan'; } What will happen?
SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be
deleted. If you omit the WHERE clause, all records in the table will be deleted!
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden
snabbköp Berglund 8
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.
BINARY(Size) It is equal to CHAR() but stores binary byte strings. Its size parameter specifies
the column length in the bytes. Default is 1.
VARBINARY(Size) It is equal to VARCHAR() but stores binary byte strings. Its size parameter
specifies the maximum column length in bytes.
TEXT(Size) It holds a string that can contain a maximum length of 255 characters.
TINYTEXT It holds a string with a maximum length of 255 characters.
LONGTEXT It holds a string with a maximum length of 4,294,967,295 characters.
ENUM(val1, val2, It is used when a string object having only one value, chosen from a list of
val3,...) possible values. It contains 65535 values in an ENUM list. If you insert a value
that is not in the list, a blank value will be inserted.
SET( It is used to specify a string that can have 0 or more values, chosen from a list of
val1,val2,val3, ... ) possible values. You can list up to 64 values at one time in a SET list.
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.
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().
MySQL 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'.
String Literals:
String literals are always surrounded by single quotes (').
For example:
'TechOnTheNet.com'
'This is a literal'
'XYZ'
'123'
Integer Literals:
Integer literals can be either positive numbers or negative numbers, but do not
contain decimals. If you do not specify a sign, then a positive number is assumed.
Here are some examples of valid integer literals:
536
+536
-536
Decimal Literals:
Decimal literals can be either positive numbers or negative numbers and contain
decimals. If you do not specify a sign, then a positive number is assumed. Here are
some examples of valid decimal literals:
24.7
+24.7
-24.7
Datetime Literals:
Datetime literals are character representations of datetime values that are enclosed
in single quotes. Here are some examples of valid datetime literals:
'April 30, 2015'
'2015/04/30'
'2015/04/30 08:34:25'
- It subtracts right hand operand from left hand operand a-b will give -50
* It multiply both operand's values a*b will give 5000
/ It divides left hand operand by right hand operand b/a will give 2
% It divides left hand operand by right hand operand and returns reminder b%a will give 0
Operator Description
ALL This is used to compare a value to all values in another value set.
AND This operator allows the existence of multiple conditions in an SQL
statement.
ANY This operator is used to compare the value in list according to the
condition.
BETWEEN This operator is used to search for values, that are within a set of values.
IN This operator is used to compare a value to that specified list value.
NOT The NOT operator reverse the meaning of any logical operator.
OR This operator is used to combine multiple conditions in SQL statements
EXISTS The EXISTS operator is used to search for the presence of a row in a
specified table.
LIKE This operator is used to compare a value to similar values using
wildcard operator.
Views: Views in SQL are kind of virtual tables. A view also has rows and columns as they are in
a real table in the database. We can create a view by selecting fields from one or more tables
present in the database. A View can either have all the rows of a table or specific rows based on
certain condition.
Sample table:
Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
DROP VIEW view_name;
Example:
SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the database
very fast.
o An Index is used to speed up select queries and where clauses. But it shows
down the data input with insert and update statements. Indexes can be created or
dropped without affecting the data.
o An index in a database is just like an index in the back of a book.
For example: When you reference all pages in a book that discusses a certain topic, you
first have to refer to the index, which alphabetically lists all the topics and then referred
to one or more specific page numbers.
Syntax
2. Unique Index statement: It is used to create a unique index on a table. It does not
allow duplicate value.
Syntax
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
Example
CREATE UNIQUE INDEX websites_idx
ON websites (site_name);
3. Drop Index Statement
It is used to delete an index in a table.
Syntax
DROP INDEX index_name;
Example
DROP INDEX websites_idx;
SQL JOIN: SQL Join is used to fetch data from two or more tables, which is joined to appear
as single set of data. It is used for combining column from two or more tables by using values
common to both tables.
JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables. A table can also join to itself,
which is known as, Self Join.
Types of JOIN:
Following are the types of JOIN that we can use in SQL:
• Inner
• Outer
• Left
• Right
Sample Table:
INNER JOIN
Let’s say we wanted to get a list of those customers who placed an order and the details of the
order they placed. This would be a perfect fit for an inner join, since an inner join returns records
at the intersection of the two tables.
Sayntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1 INNER
JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Left Join
If we wanted to simply append information about orders to our customers table,
regardless of whether a customer placed an order or not, we would use a left join. A left
join returns all records from table A and any matching records from table B.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Right Join
Right join is a mirror version of the left join and allows to get a list of all orders,
appended with customer information.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Full Join
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join
tables have all the records from both tables. It puts NULL on the place of matches not
found.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further
into,
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
null null 7 NOIDA
null null 8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
null null 7 NOIDA
null null 8 PANIPAT