0% found this document useful (0 votes)
75 views155 pages

DBMS Module - 2

The document provides an overview of SQL and relational databases. It defines SQL as a language used to communicate with relational databases and store, manipulate, and retrieve data. It explains why learning SQL is important as it is the standard language used by relational database management systems like MySQL. The document also defines key SQL concepts like tables, records, fields, data types, and common SQL statements for querying, manipulating, and defining data in a database.

Uploaded by

Tanai Thrinesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
75 views155 pages

DBMS Module - 2

The document provides an overview of SQL and relational databases. It defines SQL as a language used to communicate with relational databases and store, manipulate, and retrieve data. It explains why learning SQL is important as it is the standard language used by relational database management systems like MySQL. The document also defines key SQL concepts like tables, records, fields, data types, and common SQL statements for querying, manipulating, and defining data in a database.

Uploaded by

Tanai Thrinesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 155

MODULE 2

Relational Model
SQL
⚫ SQL is a database computer language
designed for the retrieval and
management of data in a relational
database. SQL stands for Structured
Query Language.
Why to Learn 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. All the Relational
Database Management Systems (RDMS) like
MySQL, MS Access, Oracle, Sybase,
Informix, Postgres and SQL Server use SQL
as their standard database language.
Why to Learn SQL?

▪ Allows users to access data in the relational database


management systems.
▪ Allows users to describe the data.
▪ Allows users to define the data in a database and
manipulate that data.
▪ Allows to embed within other languages using SQL
modules, libraries & pre-compilers.
▪ Allows users to create and drop databases and tables.
▪ Allows users to create view, stored procedure,
functions in a database.
▪ Allows users to set permissions on tables,
procedures and views.
What is RDBMS?

▪ RDBMS stands
for Relational Database Management
▪  System. RDBMS is the basis for SQL, and for
all modern database systems like MS SQL
Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.
▪ A Relational database management system
(RDBMS) is a database management system
(DBMS) that is based on the relational model
as introduced by E. F. Codd.
What is a table?

▪ The data in an RDBMS is stored in


database objects which are called
as tables. This table is basically a
collection of related data entries and it
consists of numerous columns and rows.
Fields and Records

Fields:
Every table is broken up into smaller entities
called fields. The fields in the CUSTOMERS
table consist of ID, NAME, AGE, ADDRESS.
A field is a column in a table that is designed
to maintain specific information about every
record in the table.
Fields and Records
▪ Records
A record is also called as a row of data is each
individual entry that exists in a table.
Following is a single row of data or record in the
CUSTOMERS table −
SQL SYNTAX
▪ SQL is followed by a unique set of rules
and guidelines called Syntax.
▪ All the SQL statements start with any of
the keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP,
CREATE, USE, SHOW and all the
statements end with a semicolon (;).
SQL DATA TYPE
• SQL Data Type is an attribute that specifies
the type of data of any object.
• Each column, variable and expression has a
related data type in SQL.
• You can use these data types while creating
your tables.
• You can choose a data type for a table column
based on your requirement.
DATA TYPES:
6 major Categories
DATA TYPES
DATA TYPES
DATA TYPES
DATA TYPES
SQL - CREATE Database

▪ The SQL CREATE DATABASE statement is


used to create a new SQL database.
Syntax
▪ The basic syntax of this CREATE DATABASE
statement is as follows −
▪ CREATE DATABASE DatabaseName;
▪ Always the database name should be unique
within the RDBMS.
Example
1) SQL> CREATE DATABASE testDB;
2) SQL> CREATE DATABASE orig;
SQL DROP DATABASE 
▪ The SQL DROP DATABASE statement
is used to drop an existing database in SQL
schema.
▪ Syntax:
▪ The basic syntax of DROP DATABASE
statement is as follows −
▪ DROP DATABASE DatabaseName;
SQL DROP DATABASE 
▪ If you want to delete an existing
database <testDB>, then the DROP
DATABASE statement would be as
shown below −
SQL> DROP DATABASE testDB;
SQL USE DATABASE
▪ When you have multiple databases in your SQL Schema,
then before starting your operation, you would need to
select a database where all the operations would be
performed.

▪ The SQL USE statement is used to select any existing


database in the SQL schema.

Syntax
▪ The basic syntax of the USE statement is as shown below −
▪ USE DatabaseName;

▪ Always the database name should be unique within the


RDBMS.
SQL CREATE TABLE
▪ The SQL CREATE TABLE statement is used to
create a new table.
▪ Syntax
▪ The basic syntax of the CREATE TABLE
statement is as follows −

CREATE TABLE table_name( column1 datatype,


column2 datatype,
column3 datatype, .....
columnN datatype,
PRIMARY KEY( one or more columns ) );
SQL DROP TABLE
▪ The SQL DROP TABLE statement is
used to remove a table definition and all
the data, indexes, triggers, constraints
and permission specifications for that
table.
▪ The basic syntax of this DROP TABLE
statement is as follows −
▪ DROP TABLE table_name;
SQL INSERT QUERY
▪ The SQL INSERT INTO Statement is used to
add new rows of data to a table in the database.

▪ There are two basic syntaxes of the INSERT


INTO statement which are shown below.
INSERT INTO TABLE_NAME

(column1,column2,column3,................columnN)
VALUES (value1, value2, value3,...valueN);

Here, column1, column2, column3,...columnN are


the names of the columns in the table into which
you want to insert the data.
SQL INSERT QUERY
▪ You may not need to specify the
column(s) name in the SQL query if you
are adding values for all the columns of
the table. But make sure the order of the
values is in the same order as the
columns in the table.
▪ The SQL INSERT INTO syntax will be as
follows −
2) INSERT INTO TABLE_NAME
VALUES(value1,value2,……valueN)
SQL SELECT QUERY
⚫ The SQL SELECT statement is used to fetch
the data from a database table which returns this
data in the form of a result table. These result
tables are called result-sets.

⚫ The basic syntax of the SELECT statement is as


follows −
1)SELECT column1, column2, columnN
FROM table_name;
⚫ Here, column1, column2... are the fields of a
table whose values you want to fetch. If you want
to fetch all the fields available in the field, then
you can use the following syntax.
2)SELECT * FROM table_name;
SQL WHERE CLAUSE
⚫ The SQL WHERE clause is used to specify a
condition while fetching the data from a
single table or by joining with multiple tables.
If the given condition is satisfied, then only it
returns a specific value from the table. You
should use the WHERE clause to filter the
records and fetching only the necessary
records.
⚫ The WHERE clause is not only used in the
SELECT statement, but it is also used in the
UPDATE, DELETE statement, etc.,
SQL WHERE CLAUSE
⚫ Syntax
⚫ The basic syntax of the SELECT
statement with the WHERE clause is as
shown below.
⚫ SELECT column1, column2, columnN
FROM table_name WHERE [condition]
You can specify a condition using
the comparison or logical operators like
>, <, =, LIKE, NOT, etc
SQL WHERE CLAUSE
⚫ The following code is an example which
would fetch the ID, Name and Salary
fields from the CUSTOMERS table, where
the salary is greater than 20000 −
⚫ SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS WHERE SALARY >
20000;
⚫ SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS WHERE NAME =
‘Mohan';
SELECT DISTINCT
The SELECT DISTINCT statement is used
to return only distinct (different) values.
Inside a table, a column often contains many
duplicate values; and sometimes you only
want to list the different (distinct) values.

Syntax:

SELECT DISTINCT column1, column2, ...


FROM table_name;
SQL AND and OR operator
SQL AND OPERATOR
SQL AND OPERATOR
⚫ SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS WHERE SALARY >
20000 AND age < 25;
SQL OR OPERATOR
SQL OR OPERATOR
⚫ SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS WHERE SALARY >
20000 OR age < 25;
SQL UPDATE QUERY
⚫ The SQL UPDATE Query is used to
modify the existing records in a table.
You can use the WHERE clause with the
UPDATE query to update the selected
rows, otherwise all the rows would be
affected.
SQL UPDATE QUERY
SQL UPDATE QUERY
⚫ The following query will update the
ADDRESS for a customer whose ID
number is 6 in the table.
⚫ SQL> UPDATE CUSTOMERS SET
ADDRESS = 'Pune' WHERE ID = 6;

⚫ SQL>UPDATE CUSTOMERS SET


ADDRESS = 'Pune', SALARY = 10000.00;
SQL DELETE QUERY WITH WHERE
CLAUSE
⚫ The SQL DELETE Query is used to
delete the existing records from a table.
⚫ You can use the WHERE clause with a
DELETE query to delete the selected
rows, otherwise all the records would be
deleted.
SQL DELETE QUERY WITH WHERE
CLAUSE
SQL DELETE QUERY WITH WHERE
CLAUSE
⚫ SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;
SQL LIKE CLAUSE
⚫ The SQL LIKE clause is used to compare a
value to similar values using wildcard
operators. There are two wildcards used in
conjunction with the LIKE operator.
⚫ The percent sign (%)
⚫ The underscore (_)
⚫ The percent sign represents zero, one or
multiple characters.
⚫ The underscore represents a single number
or character. These symbols can be used in
combinations.
SQL LIKE CLAUSE
⚫ Syntax:
SELECT FROM table_name
WHERE column LIKE 'XXXX%'
Or
SELECT FROM table_name WHERE column
LIKE '%XXXX%'
or
SELECT FROM table_name WHERE column
LIKE 'XXXX_'
or
SELECT FROM table_name WHERE column
LIKE '_XXXX'
SQL LIKE CLAUSE
SQL LIKE CLAUSE
SQL LIKE CLAUSE
SQL ORDER BY
SQL ORDER BY
SQL GROUP BY
Having clause
⚫ The HAVING Clause enables you to
specify conditions that filter which
group results appear in the results.
⚫ The WHERE clause places
conditions on the selected columns,
whereas the HAVING clause places
conditions on groups created by the
GROUP BY clause
1.COUNT FUNCTION
• COUNT function is used to Count the

number of rows in a database table. It can


work on both numeric and non-numeric
data types.
• COUNT function uses the COUNT(*)

that returns the count of all the rows in a


specified table. COUNT(*) considers
duplicate and Null.
2. SUM Function
⚫ Sum function is used to calculate the sum

of all selected columns. It works on


numeric fields only.

3. AVG function
⚫ The AVG function is used to calculate the

average value of the numeric type. AVG


function returns the average of all
non-Null values.
4. MAX Function
⚫ MAX function is used to find the maximum

value of a certain column. This function


determines the largest value of all selected
values of a column.

5. MIN Function
⚫ MIN function is used to find the minimum

value of a certain column. This function


determines the smallest value of all selected
values of a column.
SQL DISTINCT keyword
SQL TOP CLAUSE
SQL ALTER TABLE
SQL ALTER TABLE
SQL NULL
SQL NULL

⚫ You must use the IS NULL or IS NOT


NULL operators to check for a NULL
value.
SQL CONSTRAINTS
SQL CONSTRAINTS
SQL JOINS
⚫ The SQL Joins clause is used to combine
records from two or more tables in a
database. A JOIN is a means for
combining fields from two tables by using
values common to each.
SQL INNER JOIN
⚫  The most important and frequently used of the joins
is the INNER JOIN. They are also referred to as
an EQUIJOIN.

⚫ returns rows when there is a match in both tables.

⚫ The INNER JOIN creates a new result table by


combining column values of two tables (table1 and
table2) based upon the join-predicate. The query
compares each row of table1 with each row of table2
to find all pairs of rows which satisfy the
join-predicate. When the join-predicate is satisfied,
column values for each matched pair of rows of A and
B are combined into a result row.
SQL INNER JOIN
SQL LEFT JOIN
⚫ The SQL LEFT JOIN returns all rows from
the left table, even if there are no matches in
the right table. This means that if the ON
clause matches 0 (zero) records in the right
table; the join will still return a row in the
result, but with NULL in each column from
the right table.
⚫ This means that a left join returns all the
values from the left table, plus matched
values from the right table or NULL in case
of no matching join predicate.
SQL LEFT JOIN
SQL RIGHT JOIN
⚫ The SQL RIGHT JOIN returns all rows
from the right table, even if there are no
matches in the left table. This means that if
the ON clause matches 0 (zero) records in
the left table; the join will still return a row
in the result, but with NULL in each column
from the left table.
⚫ This means that a right join returns all the
values from the right table, plus matched
values from the left table or NULL in case of
no matching join predicate.
SQL RIGHT JOIN
SQL FULL JOIN
⚫ The SQL FULL JOIN combines the
results of both left and right outer joins.
⚫ The joined table will contain all records
from both the tables and fill in NULLs for
missing matches on either side.
SQL FULL JOIN
SQL FULL JOIN –UNION ALL
SQL SELF JOIN
⚫ The SQL SELF JOIN is used to join a
table to itself as if the table were two
tables; temporarily renaming at least one
table in the SQL statement.
SQL CARTESIAN JOIN
⚫ The CARTESIAN JOIN or CROSS JOIN
returns the Cartesian product of the sets
of records from two or more joined
tables. Thus, it equates to an inner join
where the join-condition always evaluates
to either True or where the
join-condition is absent from the
statement.
SQL CARTESIAN JOIN
SQL CARTESIAN JOIN
SQL USING VIEWS
⚫ A view is nothing more than a SQL statement that is stored
in the database with an associated name. A view is actually a
composition of a table in the form of a predefined SQL
query.
⚫ A view can contain all rows of a table or select rows from a
table. A view can be created from one or many tables which
depends on the written SQL query to create a view.
⚫ Views, which are a type of virtual tables allow users to do
the following −
⚫ Structure data in a way that users or classes of users find
natural or intuitive.
⚫ Restrict access to the data in such a way that a user can see
and (sometimes) modify exactly what they need and no
more.
⚫ Summarize data from various tables which can be used to
generate reports.
SQL USING VIEWS
SQL using views
SQL AGGREGATION FUNCTION
COUNT FUNCTION
1)SELECT COUNT(*)  
FROM PRODUCTS;  

2) SELECT COUNT(*)  
FROM PRODUCTS;  
WHERE RATE>=20; 

3)
SELECT COUNT(DISTINCT COMPANY) 
 FROM PRODUCTS;   
4)SELECT COMPANY, COUNT(*)  
FROM PRODUCTS  
GROUP BY COMPANY;  

5) SELECT COMPANY, COUNT(*)  
FROM PRODUCTS  
GROUP BY COMPANY  
HAVING COUNT(*)>2;  
2. SUM Function

⚫ Sum function is used to calculate the sum


of all selected columns. It works on
numeric fields only.
3. AVG function

⚫ The AVG function is used to calculate the


average value of the numeric type. AVG
function returns the average of all
non-Null values.
4. MAX Function

⚫ MAX function is used to find the


maximum value of a certain column. This
function determines the largest value of
all selected values of a column.
5. MIN Function

⚫ MIN function is used to find the minimum


value of a certain column. This function
determines the smallest value of all
selected values of a column
INTEGRITY CONSTRAINTS
⚫ Point-01:

• We may use logical operators like ∧ , ∨ , ! and


relational operators like = , ≠ , > , < , <= , >= with the
selection condition.

⚫ Point-02:

• Selection operator only selects the required tuples


according to the selection condition.
• It does not display the selected tuples.
• To display the selected tuples, projection operator is
used.
Point-03:

•Selection operator always selects the entire tuple. It can not select a section
or part of a tuple.

Point-04:

•Selection operator is commutative in nature i.e.


σ A ∧ B (R) = σ B ∧ A (R)
OR
σ B (σ A(R)) = σ A (σ B(R))
Point-05:

•Degree of the relation from a selection operation is same as degree of the input
relation.

Point-06:

•The number of rows returned by a selection operation is obviously less than or equal
to the number of rows in the original table.
Thus,
•Minimum Cardinality = 0
•Maximum Cardinality = |R|
Ex:Selects the records from EMPLOYEE table with
department ID = 20 and employees whose salary is more
than 10000.
σdept_id = 20 AND salary>=10000 (EMPLOYEE)

Ex: Selects tuples from relation Account where the


account type is ‘saving.’
σaccount_type = “saving”(Account)
Point-01:

•The degree of output relation (number of columns present) is equal to the number of
attributes mentioned in the attribute list.

Point-02:

•Projection operator automatically removes all the duplicates while projecting the
output relation.
•So, cardinality of the original relation and output relation may or may not be same.
•If there are no duplicates in the original relation, then the cardinality will remain
same otherwise it will surely reduce.

Point-03:

•If attribute list is a super key on relation R, then we will always get the same number
of tuples in the output relation.
•This is because then there will be no duplicates to filter.

Point-04:

•Projection operator does not obey commutative property i.e.


π <list2> (π <list1> (R)) ≠ π <list1> (π <list2> (R))
Point-05:

•Following expressions are equivalent because both finally projects columns


of list-1
π <list1> (π <list2> (R)) = π <list1> (R)

Point-06:

•Selection Operator performs horizontal partitioning of the relation.


•Projection operator performs vertical partitioning of the relation.

Point-07:

•There is only one difference between projection operator of relational


algebra and SELECT operation of SQL.
•Projection operator does not allow duplicates while SELECT operation
allows duplicates.
•To avoid duplicates in SQL, we use “distinct” keyword and write SELECT
distinct.
•Thus, projection operator of relational algebra is equivalent to SELECT
operation of SQL
Ex 1: Produce a list of salaries for all staff, showing only
the staffNo, fName, lName, and salary details.
ΠstaffNo, fName, lName, salary(Staff)

Ex 2: Select all the records from STUDENT table but only


selected columns – std_name, address and course. Suppose we
have to select only these 3 columns for particular student then we
have to combine both project and select operations.
∏std_name, address, course (STUDENT)

Ex 3: selects the record for ‘James’ and displays only std_ID,


address and his course columns. Here we can see two unary
operators are combined, and it has two operations performing.
First it selects the tuple from STUDENT table for ‘James’. The
resultant subset of STUDENT is also considered as intermediary
relation. But it is temporary and exists till the end of this
operation. It then filters the 3 columns from this temporary
relation.
∏STD_ID, address, course (σ STD_NAME = “James”(STUDENT))
Ex:
ρ STUDENT (STD_TABLE) – Renames
STD_TABLE table to STUDENT

Ex:
To rename the columns of the table. If the
STUDENT table has ID, NAME and ADDRESS
columns and if they have to be renamed to
STD_ID, STD_NAME, STD_ADDRESS, then we
have to write as follows.

⚫ ρ  STD_ID, STD_NAME, STD_ADDRESS(STUDENT) – It


will rename the columns in the order the names
appear in the table
Union Operator (∪)
⚫ Union operator is denoted by ∪ symbol
and it is used to select all the rows
(tuples) from two tables (relations).
⚫ Lets 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.
For a union operation to be applied, the
following rules must hold −
• r and s must have the same quantity of

attributes.
• Attribute domains must be compatible.

• Duplicate tuples get automatically

eliminated.
We have two courses table and we want to perform the
union operation on table Course_1(C_id, C_name) and
Course_2(C_id, C_name). Remember, we can perform
union operation only because both the tables have same
attribute.
Intersection Operator (∩)
⚫ Intersection operator is denoted by ∩ symbol and
it is used to select common rows (tuples) from two
tables (relations).
⚫ Lets say we have two relations R1 and R2 both
have same columns and we want to select all those
tuples(rows) that are present in both the relations,
then in that case we can apply intersection
operation on these two relations R1 ∩ R2.
Set Difference (-)

⚫ Set Difference is denoted by – symbol. Lets 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.
Cartesian product (X)
⚫ Cartesian Product is denoted by X symbol. Lets
say we have two relations R1 and R2 then the
cartesian product of these two relations (R1 X
R2) would combine each tuple of first relation
R1 with the each tuple of second relation R2. I
know it sounds confusing but once we take an
example of this, you will be able to understand
this.
⚫ If relation R has m tuples and relation S
has n tuples, then the resultant relation
will have mn tuples. For example, if we
perform cartesian product on
EMPLOYEE (5 tuples) and DEPT
relations (3 tuples), then we will have
new tuple with 15 tuples.
Ex:

Σcity = “Kolkata” (Depositor Χ


Borrower)
⚫ Output – It selects all tuples
from both relations Depositor
and Borrower where city is
Kolkata.
Consider two tables Emp_Address and Emp_Company as shown
below

EMP_NAME STREET CITY

Rahul Park Street Mumbai

Neha M.G Street Delhi

Pooja Nehru Nagar Kolkata

Arun H.L Street Hyderabad

EMP_NAME COMPANY SALARY

Rahul Wipro 35000

Neha Infosys 37000

Sujay HCL 33000

Arun TCS 32000


Left Outer Join(⟕):
• When applying join on two relations R and S, some tuples
of R or S does not appear in result set which does not satisfy
the join conditions.
• But Left Outer Joins gives all tuples of R in the result set.
• The tuples of R which do not satisfy join condition will have
values as NULL for attributes of S
⚫ Emp_address ⟕ Emp_Company

EMP_NA STREET CITY COMPANY SALARY


ME
Rahul Park Street Mumbai Wipro 35000

Neha M.G Street Delhi Infosys 37000

Pooja Nehru Nagar Kolkata Null Null

Arun H.L Street Hyderabad TCS 32000


⚫ Right Outer Join(⟖): When applying
join on two relations R and S, some
tuples of R or S does not appear in
result set which does not satisfy the
join conditions. But Right Outer Joins
gives all tuples of S in the result set.
The tuples of S which do not satisfy
join condition will have values as
NULL for attributes of R.
⚫ Emp_address ⟖ Emp_Company

EMP_NAME STREET CITY COMPANY SALARY

Rahul Park Street Mumbai Wipro 35000

Neha M.G Street Delhi Infosys 37000

Sujay Null Null HCL 33000

Arun H.L Street Hyderabad TCS 32000


⚫ Full Outer Join(⟗): When applying
join on two relations R and S, some
tuples of R or S does not appear in
result set which does not satisfy the
join conditions. But Full Outer Joins
gives all tuples of S and all tuples of R
in the result set. The tuples of S which
do not satisfy join condition will have
values as NULL for attributes of R
and vice versa.
⚫ Emp_address ⟗ Emp_Company

EMP_NAME STREET CITY COMPANY SALARY

Rahul Park Street Mumbai Wipro 35000

Neha M.G Street Delhi Infosys 37000

Sujay Null Null HCL 33000

Arun H.L Street Hyderabad TCS 32000

Pooja Nehru Nagar Kolkata Null Null


EQUI JOIN
⚫ The process is called joining when we combine two or more
tables based on some common columns and a join
condition. An equijoin is an operation that combines
multiple tables based on equality or matching column
values in the associated tables.
⚫ We can use the equal sign (=) comparison operator to
refer to equality in the WHERE clause. This joining
operation returns the same result when we use the JOIN
keyword with the ON clause and then specifying the
column names and their associated tables.
⚫ Equijoin is a classified type of inner join that returns output
by performing joining operations from two tables based on
the common column that exists in them. This join returns
only those data that are available in both tables based on the
common primary field name. It does not display the null
records or unmatchable data into the result set.
⚫ Division Operator (÷): Division operator
A÷B can be applied if and only if:
• Attributes of B is proper subset of
Attributes of A.
• The relation returned by division operator
will have attributes = (All attributes of A –
All Attributes of B)
• The relation returned by division operator
will return those tuples from relation A
which are associated to every B’s tuple.
⚫ Consider two relations shown below

You might also like