SlideShare a Scribd company logo
Unit-2:Relational Algebra and Relational Data Model
Relational Algebra Operations: SELECTION and
PROJECTION, Relational Algebra Operations from Set
Theory, the CARTESIAN PRODUCT (CROSS PRODUCT)
Operation,
Binary Relational Operations: JOIN and DIVISION.
Relational Calculus - Tuple Relational Calculus.
Relational Data Model: Basic SQL, SQL Data Types,
Specifying Constraints in SQL, DDL, DML and Basic
Retrieval Queries in SQL-SELECT, NULL values, Nested
queries, Correlated sub queries, Set operations, Aggregate
functions, Group by and HAVING Clauses.
Q.Explain different types of operators in Relational
Algebra?
• Relational algebra is a procedural Query language.
• It contains of a set of operations that take one or more relations(tables)
as input and produce a new relation as output.
• It mainly provides a theoretical foundation for relational databases and
SQL.
RELATIONAL ALGEBRA
Relational Algebra operations:
• The fundamental operations of relational algebra are:
• select(σ)
• project(π)
• union(U)
• intersect( )
Ո
• set difference(-)
• Cartesian product(x)
• rename(ƿ)
• joins(|x|)
1.Select:
• Selection is used to display set of tuples(rows) based on the condition
from the relation(table).
• It is a unary operation defined on a single table.
• It is denoted as σ
• It is used to select required tuples of the relations.
Notation: σ < select condition>(R)
Ex: σ(eid>3)(emp) will select the tuples which have Eid more than 3 in
emp table.
Ex: select * from emp where eid>3;
•Project:
•It is used to display required column data from a
table.
•It is denoted as π
•It is a unary operation defined on a single table.
 Notation: π<attributes> (R)
 Ex1: π (eno,name) (EMP)
 Ex in SQL:
 Select eno,name from emp;
•Union:
•It is denoted by U.
•If T1 and T2 are two tables, then it displays all
records from both the tables.
•It eliminates the duplicate data.
•It is a binary operation defined on pairs of tables.
• Ex: π(eno,name)T1 U π(eno,name)T2
• Sql:
• Select eno,name from T1 UNION Select eno,name from T2;
•Intersect:
•It is denoted by .
Ո
•It displays only common records from two or
more tables.
•It is a binary operation
Ex: π(eno,name)T1 π(eno,name)T2
Ո
Sql:
Select eno,name from T1 INTERSECT Select eno,name from
T2;
•Set Difference:
•It is denoted by –.
•It displays all the rows in first table which are not
in second table.
•It is a binary operation
• Ex: π(eno,name)T1 - π(eno,name)T2
• Sql:
• Select eno,name from T1 MINUS Select eno,name from T2;
•Cartesian Product:
•It allows all the combinations of rows from T1
and T2 in the result set.
•It is denoted by X
•It is also called as cross product.
• If A has ‘n’ tuples and B has ‘m’ tuples then AXB will have ‘n*m’ tuples.
•Rename:
•It is used for renaming tables and attributes.
•It is a unary operation.
•It is denoted by ρ
Ex: Ρ(A/B) will rename the attribute ‘B’ of the relation by ‘A’.
•Join:
•It is used to display data from two or more
tables. For Join, both tables must have one
common attribute.
•Different types of Joins are equi Join, Self
Join ,Left Outer Join , Right Outer Join, Full Outer
Join.
•It is denoted as |x|
• EX: emp |x| dept
Q. Explain how Cartesian product works in SQL.
Cartesian Product
• The cartesian product is a binary operation and is
denoted by (x). e.g. if A = {1, 2, 3} and B = {a, b, c}, find
A x B.
• In sql, the CROSS JOIN or CARTESIAN JOIN is used to
produce the cartesian product of two tables.
• It combines every row of one table with all rows of
another table, producing all the possible
combination.
• Ex: Let’s say A and B, so the cross product between
AXB will result in all the attributes of A followed by
each attribute of B. Each record of A will pair with
every record of B.
• A x B = ((1, a), (1, b), (1, c), (2, a),
(2, b), (2, c), (3, a), (3, b), (3, c))
e.g. Consider the following EMPLOYEES and DEPARTMENTS
tables:
To get the cartesian product, the following sql statement can be used:
SELECT EMP_name,Emp_id FROM EMPLOYEES CROSS JOIN
DEPARTMENTS;
(or)
SELECT EMP_name,EMP_id FROM EMPLOYEES,DEPARTMENTS;
Q. Explain about Tuple Relational
Calculus(TRC) with example?
Relational Calculus: Relational Calculus is a
non-procedural query language.
•Relational Calculus use “mathematical
predicate” to retreive data from a relation.
•A Predicate is a “Formula or expression
used”.
•A relational calculus says “What to do” but
never says “How to do”.
Types of Relational calculus:
•Tuple Relational Calculus
•Domain Relational Calculus.
1.Tuple Relational Calculus:
•It was introduced by E.F.Codd in 1972.
•It is a non-procedural query language.
•Tuple calculus is used to select “tuples in a
relation based on a condition”.
•Conditions used in tuple calculus are called
“Predicated or Well Formed Formulas(wff)”.
•The output is also a “relation”.
•It is denoted as
{ t | COND(t) }
•Where “t” is a tuple variable.
•COND is Condition applied on Relation.
•Example1:
• { t | EMP (t) and t.salary>10000 }
•It implies that the resulting employee tuple
will have salary greater than 10,000.
•t.salary is a tuple variable.
•Example 2:
• { t | EMP (t) and t.deptno=10 }
•It displays all the tuples from employee table
whose belongs to deptno 10
• t.deptno is a tuple variable.
•2. Domain Relational Calculus: Domain calculus
was introduced by Lacroix and Pirotte
•It is a non-procedural query language.
•Domain Calculus used “set of attributes from a
Relation”.
•It is same as TRC but differs by selecting
attributes rather than selecting the whole tuples.
•It is denoted as
•{ <A1, A2 ,A3,…. > | COND(<A1, A2, A3…..>) }
•Where “<A1, A2, A3 ....>” are “set of attributes
in a relation”.
•COND is Condition applied on Relation.
•Example1:
• { <eno, name | EMP (<eno,name>) and
salary>10000 }
•It displays eno and ename of employees whose
salary is greater than 10000
•Example 2:
• { <name> | EMP (<name>) and deptno=10 }
•It displays name of employees whose belongs to
department number 10
Q.Define join? Explain about different types of
JOINS in SQL.
Join in SQL
• SQL Join is used to fetch data from two or more tables based on
common column.
• SQL Join 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.
• A table can also join to itself known as, Self Join.
Types of Join
• Inner Joins: Theta, Natural, EQUI
• Outer Join: Left, Right, Full
INNER Join or EQUI Join
•It returns records that have matching values in both
tables based on the given condition.
•It is the most widely used join operation and can be
considered as a default join-type.
•Syntax:
SELECT * from table1
INNER JOIN table2 ON table1.column-name =
table2.column-name;
Ex:SELECT * from class join classinfo ON
class.id = classinfo.id;
ID NAME
1 ABHI
2 ADAM
3 ALEX
4 ANU
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME ID Address
1 ABHI 1 DELHI
2 ADAM 2 MUMBAI
3 ALEX 3 CHENNAI
Theta Join
•Theta Join allows you to merge two tables based on the
condition other than equality.
•Theta joins work for all comparison operators(<,>,<=,>=).
•It is denoted by symbol θ.
•The general case of JOIN operation is called a Theta join.
•Ex: select
employee.eid,employee.ename,depart.deptid,depart.dn
ame from employee join depart on
employee.eid<depart.deptid;
Natural JOIN
•Natural Join is a type of Inner join and is structured in
such a way that, columns with same name of associate
tables will appear only once.
•Don’t use ON clause in a natural join.
•Syntax
SELECT * from table1 NATURAL JOIN
table2;
Ex:SELECT * from class NATURAL JOIN classinfo;
class classinfo
ID NAME
1 ABHI
2 ADAM
3 ALEX
4 ANU
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME Address
1 ABHI DELHI
2 ADAM MUMBAI
3 ALEX CHENNAI
Outer JOIN
•Outer join is based on both matched and unmatched
data.
•An outer join will return all rows from one table and
the matched rows from the other table. If there is no
match, the result is NULL on the side where there is no
match.
Types of outer join:
•Left Outer Join
•Right Outer Join
•Full Outer Join
Left Outer Join
•A left outer join returns all rows from the left table
and the matched rows from the right table.
•If there is no match, the result is NULL from the right
table.
•Syntax:
•SELECT * FROM table1
LEFT JOIN table2 ON table1.column_name =
table2.column_name;
Ex:SELECT * FROM class LEFT JOIN classinfo ON (class.id=classinfo.id);
ID NAME
1 ABHI
2 ADAM
3 ALEX
4 ANU
5 ASHISH
ID NAME ID ADDRESS
1 ABHI 1 DELHI
2 ADAM 2 MUMBAI
3 ALEX 3 CHENNAI
4 ANU NULL NULL
5 ASHISH NULL NULL
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
Right Outer Join
•A right outer join returns all rows from the right table
and the matched rows from the left table.
•If there is no match, the result is NULL from the left
table.
•Syntax:
•SELECT * FROM table1
RIGHT JOIN table2 ON table1.column_name =
table2.column_name;
select * from class right outer join
classinfo on (class.id=classinfo.id);
ID NAME
1 ABHI
2 ADAM
3 ALEX
4 ANU
5 ASHISH
ID ADDRESS
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
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
Full Outer Join
•A full outer join combines rows when there is a match
based on a specified condition and includes unmatched
rows from both tables.
•Syntax:
•SELECT * FROM table1
FULL OUTER JOIN table2 ON table1.column_name =
table2.column_name;
SELECT * FROM class FULL OUTER JOIN classinfo on (class.id=classinfo.id);
ID NAME
1 ABHI
2 ADAM
3 ALEX
4 ANU
5 ASHISH
ID ADDRESS
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID ADDRESS
1 ABHI 1 DELHI
2 ADAM 2 MUMBAI
3 ALEX 3 CHENNAI
4 ANU NULL NULL
5 ASHISH NULL NULL
Q. Explain about Cross join with example?
Cross JOIN or Cartesian Product
•The SQL CROSS JOIN produces a result set which is the
number of rows in the first table multiplied by the
number of rows in the second table, if no WHERE
clause is used along with CROSS JOIN.
•This kind of result is called as Cartesian Product.
•If, WHERE clause is used with CROSS JOIN, it functions
like an INNER JOIN.
Cross JOIN Syntax is,
SELECT * from table1 CROSS JOIN table-name2;
SELECT * from class cross JOIN classinfo;
class classinfo
ID NAME
1 ABHI
2 ADAM
4 ALEX
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME ID Address
1 ABHI 1 DELHI
2 ADAM 1 DELHI
4 ALEX 1 DELHI
1 ABHI 2 MUMBAI
2 ADAM 2 MUMBAI
4 ALEX 2 MUMBAI
1 ABHI 3 CHENNAI
2 ADAM 3 CHENNAI
4 ALEX 3 CHENNAI
Q. Explain about self join with example.
Self Join
• A self join is a type of inner join in which a table is joined
with itself (which is also called unary relationship).
• To join a table itself means that each row of the table is
combined with itself and with every other row of the table.
• Syntax:
• Select column(s) from table1 t1, table1 t2 where condition;
Ex: select x.student_name ,y.student_name from student x ,
student y where x.id=y.friend_id;
REC-UNIT-2-DATABASEMANAGEMENTSYSTEMS.pptx
Introduction to SQL
•It is a structured query language , which is a
computer language for storing, manipulating, and
retrieving data stored in a relational data base.
•It is a programming language that is used to work
with data base.
•It is an ANSI (AMERICAN NATIONAL STANDARD
INSTITUTE) standard language.
•It includes database creation, fetching rows,
modifying rows etc..
•All the Relational Data Base Management
Systems (RDBMS) like MY SQL, MS-ACCESS,
Oracle, Sybase, Postgre sql and SQL Server use
SQL as their standard data base language.
History of SQL
• SQL is initially developed in IBM by DONOLD
D.CHAMBERLIN and RAYMOND F BOYCE in 1970.
1.1970:-
•DR.E.F.CODD published the paper “ A relational
model of data for large shared data banks” .
•CODD’S model is now accepted as a definitive
model for relational data base management
system(RDBMS).
2.1978:-
•IBM worked to developed codd’s ideas and released a
product name SYSTEM/R.
•Later the language structured English query language
(SEQUEL) was developed by IBM corporation to use
codd’s models.
3.1979:-
•SEQUEL later it became SQL in 1979.
•Today, sql is accepted as the standard RDBMS language
4.1986:-
•The first relational database was first released by
relational software which later came to be known as
“ORACLE”.
Q. Explain different types of datatypes
available in sql.
DATATYPES IN SQL
• In SQL, data type specifies what type of data a column can
contain.
• SQL has different types of datatypes. They are
• Exact numeric data types
• Approximate numeric data types .
• Date and time data type.
• Character string data types
• Other data types.
REC-UNIT-2-DATABASEMANAGEMENTSYSTEMS.pptx
DATA TYPES FROM TO
Int -2,147,483,648 +2,147,483,647
Small int -32,768 +32,767
Big int 922,337,203,685,477,5808 922,337,203,685,477,5807
Tinyint 0 255
Bit 0 1
Decimal -10^38+1 +10^38+1
Numeric -10^38+1 10^38+1
Money 922,337,203,685,477,5808 +922,337,205,685,477,5807
Small money -214,748,3648 214,748,3647
Exact numeric
• DECIMALS :-
• It accepts numeric values, which may define
precision &scale in the data type declaration.
•SYNTAX:- decimal(p,s)
•P-precision it represents the total no.of digits.
•S-scale it represents the number of digits accepted after
decimal point.
•EX: AVG DECIMAL(4,2)
45.2 is correct
45.22 is correct
456.22 is wrong
456.2 is wrong
Number datatype
• The Oracle NUMBER data type is used to store numeric values
that can be negative or positive. The following illustrates the
syntax of the NUMBER data type:
syntax: number(p,s)
• The Oracle NUMBER data type has precision and scale.
• The precision is the number of digits in a number. It ranges from 1
to 38.
• The scale is the number of digits to the right of the decimal point
in a number.
• For example, the number 1234.56 has a precision of 6 and a scale
of 2. So to store this number, you need NUMBER(6,2).
Approximate numeric
Datatypes from to
Float -1.79E+308 1.79E+308
Real/double -3.40E+38 3.40E+38
FLOAT :-
•It accepts real values which may define a precision of upto
a maximum of 64.
•SYNTAX :-
• float(p) / float
• Ex :- avg float(10)
REAL / DOUBLE :-
•it accepts real values of upto a precision of 64.
•no parameters are required when declaring a real type.
•SYNTAX :- Real Ex :- avg real.
DATE AND TIME DATATYPES
Datatype from To
Datetime Jan1,1753 Dec31,9999
Date Storesadatelikejun31,1991
Time Storestimeofdaylike12:00pm
Character datatypes
•It accepts character type data. The different
types of character data types are
•1.char
•2.varchar-variable character
•3.varchar2
char
•it accepts a fixed length non – Uni code character
data .
•it stores a maximum length upto 8000 characters.
•Syntax :- char(n)
• Here ‘n’ represents number of characters .
•Ex :- sname char(10)
varchar
•it accepts a variable length , non –unicode character
data.
•It stores a maximum length upto 4000 characters .
•Syntax :- varchar(n)
• Ex :- sname varchar(10).
REC-UNIT-2-DATABASEMANAGEMENTSYSTEMS.pptx
varchar2
•It accepts a variable length non -Unicode
character data.
•It stores a maximum length up to 4000
characters .
•Syntax :- varchar2(n)
•Ex :- sname varchar2(10).
Other Datatypes
•The other data types are CLOB (CHARACTER LARGE
OBJECT ) , BLOB (BINARY LARGE OBJECT ).
•CLOB :-
• It stores varaiable length character data that can
be a single byte ( or ) multi – byte (supports more than 4
gb )
•BLOB :-
• This type is used to store large amount of binary
data such as images ( or ) other type of files .
Q. Write about SQL commands?
SQL COMMANDS
• SQL is a software which is used to work with database.
It is a fourth generation language.
• It is a non-procedural language which contains set
of commands.
• All SQL commands are divided into four types.
They are
1. Data definition language (DDL).
2. Data manipulation language (DML).
3. Data control language (DCL).
4. Transaction control language (TCL).
REC-UNIT-2-DATABASEMANAGEMENTSYSTEMS.pptx
REC-UNIT-2-DATABASEMANAGEMENTSYSTEMS.pptx
Q. Explain about DDL commands with
examples.
DDL COMMANDS
• DDL stands for DATA DEFINITION LANGUAGE . DDL
commands are used to work with the structure of the
data base .
•There are six different commands in DDL. They are
1.create
2.Alter
3.drop
4.rename
5.truncate
6.comment
CREATE
• Create command is used to create data base object like
tables , indexes, views, sequences on data base .
Syntax :-
Create table tablename (column1
datatype(size),column2 datatype(size),……);
Ex :- command for creating customer table .
SQL>create table customer (cno varchar(5),ename
varchar(20), Addres varchar(20));
•
ALTER
•ALTER COMMAND TO ADD NEW COLUMN :-
•SYNTAX :- Alter table tablename add (columnname
datatype(size));
•Ex :- Alter table customer ADD (phnno char(10),email id
varchar(20));
Alter
add new
column
drop existing
column
modify existing
column
•ALTER COMMAND TO DROP A COLUMN:-
SYNTAX :- Alter table tablename drop (course
name );
Ex :- Alter table customer Drop (emailid);
•ALTER COMMAND TO MODIFY:-
SYNTAX :- Alter table tablename modify(column
datatype(size),…..);
•Ex :- SQL>Alter table book modify(ISBN
varchar(12));
DROP
•Drop command is used to destroy (delete)
an existing object from a database.
Syntax :- Drop table tablename ;
EX :- SQL>Drop table book ;
RENAME
•Rename command is used to rename a table .
•Syntax :-
Rename <old tablename> to <new
tablename>;
•Ex:- SQL>Rename employee to emp;
TRUNCATE
•This command is used to delete complete
data in a table . The data deleted from tables
cannot be rolled back.
•Syntax :- truncate table <table name>;
•Ex:- SQL>truncate table emp;
COMMENT
•This command is used to add comment to
the existing table.
•Syntax :- Comment on table <tablename> is
“comment sentence”;
•Ex :-comment on student is “to store
student personal details”;
•
•To view the table comment :-
•Syntax :-
SQL >select comments from user _tab_comments
where Table-name =’TABLE NAME’;
•the table name must be given in capital letters only.
Q. Explain about DML Commands.
(or)
Explain the form of a basic
SQL query in detail with examples.
DML
• DML is used to insert, modify, delete and
retrieve data in a data base.
• There are four types of DML commands
available in SQL. They are
1.INSERT
2.UPDATE
3.DELETE
4.SELECT
INSERT
•This command is used to add records to the
existing table.
•“&” is used to insert command to accept
values at SQL prompt.
•There are three ways to insert records in a
table.
•To insert values for one record :-
Syntax:- insert into tablename
values(value1,value2…..);
• To insert data for a particular columns in a table :-
• Syntax :- insert into tablename ((columname1,columname2….)
values(exp1,exp2….);
• To insert multiple records at a time :-
• Syntax:- insert into tablename values (&columname1…….);
• NOTE:-Put single quotes ( ’ ‘) for varchar data type column in insert
command.
• Ex :- SQL>insert into vijaya values(&sno,’&sname’,&marks);
• Enter value for s.no: 1
• Enter value for sname : lucky
• Enter value for marks : 98
• 1 row created
• SQL>/ Here ‘/ ‘ is a character used to enter another record in a
table.
UPDATE
•i) The update command is used to change
( or) modify data values in a table .
•ii) it is used to update either all rows from a
table.(or)set of selected rows from a table.
•Syntax :- update < tablename > set
colname = expression, colname=expression;
•This command is used to update all rows in a
table
•Syntax :- Update tablename set
colname=expression,colname = expression where
<condition>;
•To update selected row in a table
•Ex :- Update student set tot =sub1+sub2+sub3;
( or )
•Update student set tot = sub1+sub2+sub3 where
sno=2;
DELETE
•The delete command is used to delete the records
from a table.
•It is used to delete either all rows from a table
(or)set of selected rows from a table.
•Syntax :- to delete all rows from a table
Delete from <tablename>;
•To delete a particular row in a table .
•Syntax :- delete from<tablename>[where <
condition>];
•ex :- SQL>delete from student;
• (or)
• SQL> delete from student where sno =2;
SELECT
•Select command is used to retrieve the data
from a table in data base according to user
requirements .
• The complete syntax for select statement is :
•Syntax :-
•Select [distinct][*][colnames] [aggregate
operation] from <tablename>
[where <search condition>]
[Group by group –by-us]
[Having<search condition>]
[ order by orderlist [asc][desc]];
SELECT
•Ex :- select *from student;
(or)
•Select sub1,sub2,sub3 from student ;
(or)
•Select * from student where sno=3;
•Distinct clause:
• The SQL Distinct clause used along with the SELECT
command. It is a keyword which retrieves only unique data
entries depending on the column list.
•Ex: select distinct student from emppayroll;
•
•(*): Star:
• It retrieves all the records in a table.
•Ex: select * from emp;
•WHERE:
•Where clause – The Where clause is used to filter records.
•The WHERE clause is used to extract only those records that
fulfills a specified condition.
•Ex: select * from emp where eno=2;
•Group by clause:
•It is used to retrieve the records depending upon a
particular column.
•It divides the column data into different groups.
•It is often used with aggregate functions to group the results
with by one or more column.
•Ex: select dno, sum(sal) from emp group by dno;
•Having clause:
•The HAVING clause was added to SQL because the
WHERE keyword could not be used with aggregate
functions.
•It is used with group by statement.
•Ex: SQl>select dno, sum(sal) from emp group by dno
having dno>10;
•Order by:
• The order by keyword is used to sort the data in
ascending or descending order.
•It sorts the records in ascending order by default. To
sort the record in descending order, we use ‘Desc’
keyword.
•Ex: SQL> select * from emp order by eno;
• Or
• SQL> select * from emp order by eno desc;
Q. Explain about Aggregate functions
/Operators in SQL.
AGGREGATE FUNCTIONS
•These are the functions in SQL which are applied in a
group of records.
•These are used to find aggregate values like sum,
average etc…for a group of records in a database
•We can apply this function on a database by using a
special keyword known as ‘ GROUP BY’.
•GROUP BY is a keyword which is used to group the
records in a database on a particular column.
• 1.COUNT.
•2.SUM.
•3.AVG.
•4.MAX.
•5.MIN.
• 1.COUNT:- The function is used to count a number of
records in a database (table)
• Ex-1:Select count(*) from emp;
• 2.select dno,count(*)from emp group by dno;
• 2.SUM:- This function is used to get the sum of values for the
given attribute on the database .
• Ex-1:select sum(sal) from emp;
• 2: select dno,sum(sal)from emp group by dno having dno=1;
• 3.AVG :- This function is used to get the average of values of
given attribute from a database
• Ex-1: select avg(sal) from emp;
• select dno,avg(sal) from emp group by
• dno;
• 4.MAX :- This function is used to get maximum value for
the given attribute form a database.
•ex :- SQL>select dno,max(sal) from emp group by dno;
•5.MIN :- The function is used to get minimum value for a
given attribute from a datatype.
•Ex :- SQL>select dno,min(sal) from emp group by dno;
Q. Explain different types of operators
available in SQL.
SQL OPERATORS
•AND
•OR
•NOT
•BETWEEN AND
•IN
•LIKE
AND,OR,NOT
•The WHERE clause can be combined with AND, OR,
and NOT operators.
•The AND and OR operators are used to filter records
based on more than one condition:
•The AND operator displays a record if all the conditions
separated by AND are TRUE.
•The OR operator displays a record if any of the
conditions separated by OR is TRUE.
•The NOT operator displays a record if the condition(s) is
NOT TRUE.
•AND Syntax
•SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
•OR Syntax
•SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
•NOT Syntax
•SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
IN
•The SQL IN Operator
•The IN operator allows you to specify multiple values in
a WHERE clause.
•The IN operator is a shorthand for
multiple OR conditions.
•IN Syntax
•SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
•Ex: select * from emp where eid in(1,3,5);
BETWEEN
•The BETWEEN operator selects values within a given
range. The values can be numbers, text, or dates.
•The BETWEEN operator is inclusive: begin and end
values are included.
•BETWEEN Syntax
•SELECT * FROM table_name
WHERE column_name BETWEEN value1 AND value2;
•Ex: select * from emp where salary between 10000 and
20000;
LIKE
•The LIKE operator is used in a WHERE clause to search
for a specified pattern in a column.
•There are two wildcards often used in conjunction with
the LIKE operator:
• The percent sign (%) –It represents any number of
characters,even zero characters
• The underscore sign (_)-It can by any character or
number, but each _ represents one, and only one,
character.
•Ex: select * from emp where ename like ‘s%’;
LIKE Operator Description
• WHERE CustomerName LIKE 'a%' Finds any values that starts with
‘a’
• WHERE CustomerName LIKE '%a' Finds any values that end with ‘a’
• WHERE CustomerName LIKE '%or%' Finds any values that have "or" in
any position
• WHERE CustomerName LIKE '_r%' Finds any values that have "r" in
the second position
• WHERE CustomerName LIKE 'a_%' Finds any values that starts with
"a" and are at least 2 characters
in length
• WHERE CustomerName LIKE 'a__%' Finds any values that start with
"a" and are at least 3 characters
in length
• WHERE ContactName LIKE 'a%o' Finds any values that start with
"a" and ends with "o"
Q.What are the integrity
constraints(Ics) over relations? Explain
in details.
Integrity constraints :
•Constraints are used to limit the type of data
that can go into a table.
• This ensures the accuracy and reliability of
the data in the table.
•Constraints could be column level or table
level.
•Column level constraints are applied only to
one column, whereas table level constraints
are applied to the multiple columns.
•Following are commonly used constraints
available in SQL.
1. PRIMARY KEY
2. FOREIGN KEY
3. NOT NULL
4. UNIQUE
5. CHECK
6. DEFAULT
Primary Key
• The PRIMARY KEY constraint uniquely identifies each record in a
database table.
• Primary keys must contain UNIQUE values, and cannot contain
NULL values.
Primary Key at column level:
• Example >CREATE TABLE Persons (ID NUMBER PRIMARY KEY,
LastName varchar(255) NOT NULL, FirstName varchar(255));
Primary Key at table level:
Example >CREATE TABLE Persons (ID NUMBER , LastName
varchar(255) NOT NULL, FirstName varchar(255),primary
key(ID));
Foreign Key
• A FOREIGN KEY is a key used to link two tables together.
• A FOREIGN KEY is a field in one table(Child table) that refers to the
PRIMARY KEY in another table(Parent table).
• Example Creating parent table:
• > CREATE TABLE DEPT(DEPTNO NUMBER PRIMARY KEY, DNAME
VARCHAR2(10), LOC VARCHAR2(10); NUMBER PRIMARY
• Creating child table at column level:
• >CREATE TABLE EMP(EMPNO NUMBER PRIMARY KEY, ENAME
VARCHAR2(10), DEPTNO NUMBER REFERENCES DEPT(DEPTNO));
• Creating child table at table level:
• >CREATE TABLE EMP(EMPNO NUMBER PRIMARY KEY, ENAME
VARCHAR2(10), DEPTNO NUMBER ,FOREIGN KEY(DEPTNO) REFERENCES
DEPT(DEPTNO));
NOT NULL
• The NOT NULL constraint enforces a column to NOT accept
NULL values.
• It can be applied at column level only.
• Example
>CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL);
UNIQUE
•The UNIQUE constraint ensures that all values in a
column are different.
• Example:
• >CREATETABLE Persons (
ID NUMBER UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255));
CHECK
•The CHECK constraint is used to limit the value range
that can be placed in a column.
•EXAMPLES
>CREATE TABLE TEST(
EMPNO NUMBER,
SAL NUMBER CHECK(SAL>5000));
>CREATE TABLE TEST(EMPNO NUMBER , AGE NUMBER
CHECK(AGE>25)
DEFAULT
• 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.
• EXAMPLE
• >CREATE TABLE Persons (
ID NUMBER NOT NULL,
City varchar(255) DEFAULT ‘MEXICO');
Q. Explain different types of set operators?
SQL Set Operation
•The SQL Set operation is used to combine the
two or more SQL SELECT statements. Types of
Set Operation
•1. Union
•2. Union All
•3. Intersect
•4. Minus
1. Union
• The SQL Union operation is used to combine the result
of two or more SQL SELECT queries.
• In the union operation, all the number of datatype and
columns must be same in both the tables on which
UNION operation is being applied.
• The union operation eliminates the duplicate rows from
its resultset.
• Syntax :
• SELECT column_name FROM table1 UNION SELECT
column_name FROM table2;
REC-UNIT-2-DATABASEMANAGEMENTSYSTEMS.pptx
2. Union All
• Union All operation is equal to the Union operation.
• It returns the set without removing duplication and sorting the
data.
• Syntax: SELECT column_name FROM table1 UNION ALL SELECT
column_name FROM table2;
3. Intersect
• It is used to combine two SELECT statements. The Intersect operation returns
the common rows from both the SELECT statements.
• Syntax
SELECT column_name FROM table1 INTERSECT SELECT
column_name FROM table2;
• Ex:SELECT * FROM First INTERSECT SELECT * FROM Second;
4.Minus/Except
• It combines the result of two SELECT statements.
• Minus operator is used to display the rows which are present in the first
query but absent in the second query.
• It has no duplicates and data arranged in ascending order by default.
• Syntax:
• SELECT column_name FROM table1 MINUS SELECT column_name
FROM table2;
Q. Explain NESTED QUERIES with examples.
(or)
Explain any and all operators with examples.
Nested Query
•A nested query(also called a subquery) is a query
embedded within another SQL Query.
•A subquery is an SQL query nested inside another query.
•The query that contains a subquery is known as an outer
query.
•It is often used in the WHERE, HAVING, or FROM clauses
of a statement. Subqueries are commonly used
with SELECT, UPDATE, INSERT, and DELETE statements to
achieve complex filtering and data manipulation.
•The result of the inner query is used by the outer query
to perform further operations.
Types of Nested Queries in SQL
• Subqueries can be either correlated or non-correlated
Independent Nested Query
•In independent nested queries, the execution of the
inner query is not dependent on the outer query.
•The result of the inner query is used directly by the
outer query.
•The inner query is independent of the outer query.
•Operators like IN, NOT IN, ANY, and ALL are
commonly used with this type of nested query.
ANY and ALL:
•The ANY compares a value with any value returned by
the subquery, while ALL ensures comparison with all
values.
Syntax of Nested Queries
• SELECT column1, column2, ... FROM table1 WHERE column1 operator
( SELECT column1 FROM table2 WHERE condition );
Ex: A nested query has two SELECT STATEMENTS: one for the inner
query and another for the outer query.
Examples
1.SELECT first_name, salary FROM employees WHERE salary > (
SELECT AVG(salary) FROM employees ) ORDER BY salary;
2. SELECT first_name, salary FROM employees WHERE salary =
( SELECT MAX(salary) FROM employees );
3. Find details of customers who have ordered.
Query:
SELECT * FROM Customers WHERE CustomerID IN
(SELECT CustomerID FROM Orders);
4. SELECT ename from Employee where deptId=(SELECT deptId
from Department where dname=‘CSM’);
5.Select * from employees where salary> any(select salary
from depart where deptid=1);
5.Select * from employees where salary> all(select salary from
depart where deptid=1);
Correlated Nested Queries
•Correlated subqueries are dependent on the outer
query.
•A correlated nested query is a subquery that uses values
from the outer query.
•The inner query depends on the outer query for its
execution. For each row processed by the outer query,
the inner query is executed.
•The EXISTS keyword is often used with correlated
queries.
•EXISTS: The Exists operator checks for the existence of rows in a
subquery. It returns true if the subquery produces any rows.
• Syntax: SELECT column01 FROM table1 WHERE column02
operator ( SELECT column02 FROM table2 WHERE
table1.column03 = table2.column04 );
• Find details of customers who have ordered.
Query: SELECT * FROM Customers where EXISTS (SELECT
OrderID FROM Orders WHERE
Orders.OrderID=Customers.OrderID);
Example 2:
Select * from employee where exists(select * from
depart where employee.deptid=depart.deptid;
Difference b/w Nested & Correlated subquery
NESTED SUBQUERY CORRELATED SUBQUERY
A query is nested inside
another query in a nested query, and
the result of the inner query is used in
the execution of the outer query.
A query is nested inside another
query in a Correlated query, and the
inner query uses the values from the
outer query.
Inner query executes first, and
only once, in a bottom-up method.
The result of the Inner query is used to
run the outer query.
Top to Bottom Approach, in which
the outer query executes first,
followed by the inner query for each
row of the outer query.
The execution of an inner query
is independent of the
execution of an outer query.
The inner query is influenced by
the outer query.
Performance is superior than
Correlated Query, but slower than
Join Operation.
Performs slower than both
Nested Query and Join operations
since the inner query is executed for
Define Null Values?
1. Understanding NULL
• NULL represents the absence of a value in a column.
• It is different from zero, an empty string, or any other default value.
2. Checking for NULL
• To check for NULL values in SQL, use the IS NULL or IS NOT NULL operators.
Ex:
• SELECT * FROM employees WHERE department IS NULL;
3.Updating NULL Values
• To update NULL values in a table, use the UPDATE statement with IS NULL.
• Ex:
• UPDATE employees SET department = 'General' WHERE department IS NULL;
Q. Write about division operation with
example.
DIVISION operation
• The DIVISION operation, denoted by ÷, is useful for a special kind of
query that sometimes occurs in database applications.
• The DIVISION operation is a binary relational operation that divides one
set of rows into another set of rows based on specified conditions.
• It is similar to a JOIN operation, but the resulting table contains only the
rows that belong to the first set and satisfy the division condition.
• R1 ÷ R2 = tuples of R1 associated with all tuples of R2.
• Ex: Retrieve the name of the subject that is taught in all courses.
÷
Name Course
C Btech
DBMS Mtech
DBMS Btech
JAVA Btech
Course
Btech
Mtech
The result is as follows
Name
DBMS
Adding & Dropping Constraints
USING ALTER
SQL PRIMARY KEY Constraint on ALTER TABLE
• To create a PRIMARY KEY constraint on the "ID" column when the
table is already created, Example
• >ALTER TABLE Persons ADD PRIMARY KEY(ID);
• Dropping:
>ALTER TABLE persons drop PRIMARY KEY;
SQL FOREIGN KEY Constraint on ALTER TABLE
• To create a FOREIGN KEY constraint on the "ID" column which refers to
the primary key in persons1 table, when the table is already created,
Example
• >ALTER TABLE Persons ADD FOREIGN KEY(ID) REFERENCES Persons1(ID);
• Dropping:
>ALTER TABLE persons drop FOREIGN KEY(ID);
SQL UNIQUE Constraint on ALTER TABLE
• To create a UNIQUE constraint on the "ID" column when the table is
already created, Example
• >ALTER TABLE Persons ADD UNIQUE(ID);
• Dropping:
>ALTER TABLE persons drop unique(ID);
SQL CHECK Constraint on ALTER TABLE
• To create a CHECK constraint on the "ID" column when the table is
already created, Example
• >ALTER TABLE Persons ADD CHECK(ID BETWEEN 1 AND 1000);
• Dropping:
>ALTER TABLE persons drop CHECK(ID);
SQL NOT NULL Constraint on ALTER TABLE
• To create a NOT NULL constraint on the "ID" column when the table
is already created, Example
• >ALTER TABLE Persons MODIFY ID int NOT NULL;
• Dropping:
>ALTER TABLE persons MODIFY ID int NULL;
SQL default Constraint on ALTER TABLE
• To create a DEFAULT constraint on the "ID" column when the table is
already created, Example
• >ALTER TABLE Persons MODIFY ID int default 1;
• Dropping:
>ALTER TABLE persons MODIFY ID int default NULL;

More Related Content

PDF
Relational Algebra-23-04-2023.pdf
PPTX
lecture 4 Relational Algebra my sql work
PPT
Ch7
PPTX
Relational Algebra in DBMS power ppoint pesenetation
PPTX
BASICS OF STRUCTURED QUEERY LANGUAGE.PPT
PDF
Lesson 6 - Relational Algebra.pdf
PDF
Unit-II DBMS presentation for students.pdf
PDF
1695304562_RELATIONAL_ALGEBRA.pdf
Relational Algebra-23-04-2023.pdf
lecture 4 Relational Algebra my sql work
Ch7
Relational Algebra in DBMS power ppoint pesenetation
BASICS OF STRUCTURED QUEERY LANGUAGE.PPT
Lesson 6 - Relational Algebra.pdf
Unit-II DBMS presentation for students.pdf
1695304562_RELATIONAL_ALGEBRA.pdf

Similar to REC-UNIT-2-DATABASEMANAGEMENTSYSTEMS.pptx (20)

PPTX
relational algebra (joins)
PPT
joins IN DATA BASE MANAGEMENT SYSTEMSppt
PPTX
5th chapter Relational algebra.pptx
PPTX
Relational_Algebra Database management system
PPTX
dbmspresentation-161126155322.pptx
PPTX
Relational Database management Systems unit-II
PPTX
Relational Algebra,Types of join
PPT
Unit2 -DBMS.ppt with type of job operation
PPTX
Relational Algebra and it's Operations pptx
PPT
R Algebra.ppt
PDF
Relational model
PPTX
Relational algebra dbms (2130703) - 160920107003
PPT
Ra Revision
PDF
IT-243-L13-14-1. pdf
PPT
Relational algebra-and-relational-calculus
PPTX
Lect - 12 solve d.pptx
PPTX
joins in database
PPTX
sql joinsubdjbrjdbjrjnfkjcnkrnfknrkfkrfkrfkrk
PPTX
sqlyyybdbyehduheufhuehfuheuwehfiewifhewihfiehfiwf
PPT
relational algebra (joins)
joins IN DATA BASE MANAGEMENT SYSTEMSppt
5th chapter Relational algebra.pptx
Relational_Algebra Database management system
dbmspresentation-161126155322.pptx
Relational Database management Systems unit-II
Relational Algebra,Types of join
Unit2 -DBMS.ppt with type of job operation
Relational Algebra and it's Operations pptx
R Algebra.ppt
Relational model
Relational algebra dbms (2130703) - 160920107003
Ra Revision
IT-243-L13-14-1. pdf
Relational algebra-and-relational-calculus
Lect - 12 solve d.pptx
joins in database
sql joinsubdjbrjdbjrjnfkjcnkrnfknrkfkrfkrfkrk
sqlyyybdbyehduheufhuehfuheuwehfiewifhewihfiehfiwf
Ad

More from Uma Kakarlapudi (11)

PDF
DATABASE MANAGEMENT SYSTEMS-BTECH-UNIT-4.pdf
PDF
DataBaseManagementSystems-BTECH--UNIT-5.pdf
PPTX
UNIT-V-hashing and its techniques ppt.pptx
PPTX
UNIT-4-Transactionstates and processing ppt.pptx
PPTX
REC-UNIT-I-DataBaseManagementSystems.pptx
PPTX
Unit-5 (1).intelligent robotics and drone technoloy
PPT
3144-unit-1entityrmodel-171122051336.ppt
PPTX
Intelligent robotics and drone technology-UNIT-III.pptx
PPTX
History of Robots and Robotics by Slidesgo.pptx
PPTX
Unit-2(Surveillance Robot in Cyber Intelligence) (1).pptx
PPTX
Intelligent Robots and Drones Technology
DATABASE MANAGEMENT SYSTEMS-BTECH-UNIT-4.pdf
DataBaseManagementSystems-BTECH--UNIT-5.pdf
UNIT-V-hashing and its techniques ppt.pptx
UNIT-4-Transactionstates and processing ppt.pptx
REC-UNIT-I-DataBaseManagementSystems.pptx
Unit-5 (1).intelligent robotics and drone technoloy
3144-unit-1entityrmodel-171122051336.ppt
Intelligent robotics and drone technology-UNIT-III.pptx
History of Robots and Robotics by Slidesgo.pptx
Unit-2(Surveillance Robot in Cyber Intelligence) (1).pptx
Intelligent Robots and Drones Technology
Ad

Recently uploaded (20)

PDF
Categorization of Factors Affecting Classification Algorithms Selection
PDF
Soil Improvement Techniques Note - Rabbi
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PDF
PPT on Performance Review to get promotions
PDF
Integrating Fractal Dimension and Time Series Analysis for Optimized Hyperspe...
PPT
Occupational Health and Safety Management System
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Current and future trends in Computer Vision.pptx
PPTX
Information Storage and Retrieval Techniques Unit III
PPTX
communication and presentation skills 01
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
UNIT - 3 Total quality Management .pptx
PPTX
Artificial Intelligence
PDF
COURSE DESCRIPTOR OF SURVEYING R24 SYLLABUS
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PPT
Total quality management ppt for engineering students
PDF
737-MAX_SRG.pdf student reference guides
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
Categorization of Factors Affecting Classification Algorithms Selection
Soil Improvement Techniques Note - Rabbi
III.4.1.2_The_Space_Environment.p pdffdf
PPT on Performance Review to get promotions
Integrating Fractal Dimension and Time Series Analysis for Optimized Hyperspe...
Occupational Health and Safety Management System
Automation-in-Manufacturing-Chapter-Introduction.pdf
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Current and future trends in Computer Vision.pptx
Information Storage and Retrieval Techniques Unit III
communication and presentation skills 01
R24 SURVEYING LAB MANUAL for civil enggi
UNIT - 3 Total quality Management .pptx
Artificial Intelligence
COURSE DESCRIPTOR OF SURVEYING R24 SYLLABUS
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Total quality management ppt for engineering students
737-MAX_SRG.pdf student reference guides
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt

REC-UNIT-2-DATABASEMANAGEMENTSYSTEMS.pptx

  • 1. Unit-2:Relational Algebra and Relational Data Model Relational Algebra Operations: SELECTION and PROJECTION, Relational Algebra Operations from Set Theory, the CARTESIAN PRODUCT (CROSS PRODUCT) Operation, Binary Relational Operations: JOIN and DIVISION. Relational Calculus - Tuple Relational Calculus. Relational Data Model: Basic SQL, SQL Data Types, Specifying Constraints in SQL, DDL, DML and Basic Retrieval Queries in SQL-SELECT, NULL values, Nested queries, Correlated sub queries, Set operations, Aggregate functions, Group by and HAVING Clauses.
  • 2. Q.Explain different types of operators in Relational Algebra?
  • 3. • Relational algebra is a procedural Query language. • It contains of a set of operations that take one or more relations(tables) as input and produce a new relation as output. • It mainly provides a theoretical foundation for relational databases and SQL. RELATIONAL ALGEBRA
  • 4. Relational Algebra operations: • The fundamental operations of relational algebra are: • select(σ) • project(π) • union(U) • intersect( ) Ո • set difference(-) • Cartesian product(x) • rename(ƿ) • joins(|x|)
  • 5. 1.Select: • Selection is used to display set of tuples(rows) based on the condition from the relation(table). • It is a unary operation defined on a single table. • It is denoted as σ • It is used to select required tuples of the relations. Notation: σ < select condition>(R) Ex: σ(eid>3)(emp) will select the tuples which have Eid more than 3 in emp table. Ex: select * from emp where eid>3;
  • 6. •Project: •It is used to display required column data from a table. •It is denoted as π •It is a unary operation defined on a single table.  Notation: π<attributes> (R)  Ex1: π (eno,name) (EMP)  Ex in SQL:  Select eno,name from emp;
  • 7. •Union: •It is denoted by U. •If T1 and T2 are two tables, then it displays all records from both the tables. •It eliminates the duplicate data. •It is a binary operation defined on pairs of tables.
  • 8. • Ex: π(eno,name)T1 U π(eno,name)T2 • Sql: • Select eno,name from T1 UNION Select eno,name from T2;
  • 9. •Intersect: •It is denoted by . Ո •It displays only common records from two or more tables. •It is a binary operation Ex: π(eno,name)T1 π(eno,name)T2 Ո Sql: Select eno,name from T1 INTERSECT Select eno,name from T2;
  • 10. •Set Difference: •It is denoted by –. •It displays all the rows in first table which are not in second table. •It is a binary operation
  • 11. • Ex: π(eno,name)T1 - π(eno,name)T2 • Sql: • Select eno,name from T1 MINUS Select eno,name from T2;
  • 12. •Cartesian Product: •It allows all the combinations of rows from T1 and T2 in the result set. •It is denoted by X •It is also called as cross product. • If A has ‘n’ tuples and B has ‘m’ tuples then AXB will have ‘n*m’ tuples. •Rename: •It is used for renaming tables and attributes. •It is a unary operation. •It is denoted by ρ Ex: Ρ(A/B) will rename the attribute ‘B’ of the relation by ‘A’.
  • 13. •Join: •It is used to display data from two or more tables. For Join, both tables must have one common attribute. •Different types of Joins are equi Join, Self Join ,Left Outer Join , Right Outer Join, Full Outer Join. •It is denoted as |x| • EX: emp |x| dept
  • 14. Q. Explain how Cartesian product works in SQL.
  • 15. Cartesian Product • The cartesian product is a binary operation and is denoted by (x). e.g. if A = {1, 2, 3} and B = {a, b, c}, find A x B. • In sql, the CROSS JOIN or CARTESIAN JOIN is used to produce the cartesian product of two tables. • It combines every row of one table with all rows of another table, producing all the possible combination. • Ex: Let’s say A and B, so the cross product between AXB will result in all the attributes of A followed by each attribute of B. Each record of A will pair with every record of B. • A x B = ((1, a), (1, b), (1, c), (2, a), (2, b), (2, c), (3, a), (3, b), (3, c))
  • 16. e.g. Consider the following EMPLOYEES and DEPARTMENTS tables: To get the cartesian product, the following sql statement can be used: SELECT EMP_name,Emp_id FROM EMPLOYEES CROSS JOIN DEPARTMENTS; (or) SELECT EMP_name,EMP_id FROM EMPLOYEES,DEPARTMENTS;
  • 17. Q. Explain about Tuple Relational Calculus(TRC) with example?
  • 18. Relational Calculus: Relational Calculus is a non-procedural query language. •Relational Calculus use “mathematical predicate” to retreive data from a relation. •A Predicate is a “Formula or expression used”. •A relational calculus says “What to do” but never says “How to do”. Types of Relational calculus: •Tuple Relational Calculus •Domain Relational Calculus.
  • 19. 1.Tuple Relational Calculus: •It was introduced by E.F.Codd in 1972. •It is a non-procedural query language. •Tuple calculus is used to select “tuples in a relation based on a condition”. •Conditions used in tuple calculus are called “Predicated or Well Formed Formulas(wff)”. •The output is also a “relation”. •It is denoted as { t | COND(t) }
  • 20. •Where “t” is a tuple variable. •COND is Condition applied on Relation. •Example1: • { t | EMP (t) and t.salary>10000 } •It implies that the resulting employee tuple will have salary greater than 10,000. •t.salary is a tuple variable. •Example 2: • { t | EMP (t) and t.deptno=10 } •It displays all the tuples from employee table whose belongs to deptno 10 • t.deptno is a tuple variable.
  • 21. •2. Domain Relational Calculus: Domain calculus was introduced by Lacroix and Pirotte •It is a non-procedural query language. •Domain Calculus used “set of attributes from a Relation”. •It is same as TRC but differs by selecting attributes rather than selecting the whole tuples. •It is denoted as •{ <A1, A2 ,A3,…. > | COND(<A1, A2, A3…..>) }
  • 22. •Where “<A1, A2, A3 ....>” are “set of attributes in a relation”. •COND is Condition applied on Relation. •Example1: • { <eno, name | EMP (<eno,name>) and salary>10000 } •It displays eno and ename of employees whose salary is greater than 10000 •Example 2: • { <name> | EMP (<name>) and deptno=10 } •It displays name of employees whose belongs to department number 10
  • 23. Q.Define join? Explain about different types of JOINS in SQL.
  • 24. Join in SQL • SQL Join is used to fetch data from two or more tables based on common column. • SQL Join 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. • A table can also join to itself known as, Self Join.
  • 25. Types of Join • Inner Joins: Theta, Natural, EQUI • Outer Join: Left, Right, Full
  • 26. INNER Join or EQUI Join •It returns records that have matching values in both tables based on the given condition. •It is the most widely used join operation and can be considered as a default join-type. •Syntax: SELECT * from table1 INNER JOIN table2 ON table1.column-name = table2.column-name;
  • 27. Ex:SELECT * from class join classinfo ON class.id = classinfo.id; ID NAME 1 ABHI 2 ADAM 3 ALEX 4 ANU ID Address 1 DELHI 2 MUMBAI 3 CHENNAI ID NAME ID Address 1 ABHI 1 DELHI 2 ADAM 2 MUMBAI 3 ALEX 3 CHENNAI
  • 28. Theta Join •Theta Join allows you to merge two tables based on the condition other than equality. •Theta joins work for all comparison operators(<,>,<=,>=). •It is denoted by symbol θ. •The general case of JOIN operation is called a Theta join. •Ex: select employee.eid,employee.ename,depart.deptid,depart.dn ame from employee join depart on employee.eid<depart.deptid;
  • 29. Natural JOIN •Natural Join is a type of Inner join and is structured in such a way that, columns with same name of associate tables will appear only once. •Don’t use ON clause in a natural join. •Syntax SELECT * from table1 NATURAL JOIN table2;
  • 30. Ex:SELECT * from class NATURAL JOIN classinfo; class classinfo ID NAME 1 ABHI 2 ADAM 3 ALEX 4 ANU ID Address 1 DELHI 2 MUMBAI 3 CHENNAI ID NAME Address 1 ABHI DELHI 2 ADAM MUMBAI 3 ALEX CHENNAI
  • 31. Outer JOIN •Outer join is based on both matched and unmatched data. •An outer join will return all rows from one table and the matched rows from the other table. If there is no match, the result is NULL on the side where there is no match. Types of outer join: •Left Outer Join •Right Outer Join •Full Outer Join
  • 32. Left Outer Join •A left outer join returns all rows from the left table and the matched rows from the right table. •If there is no match, the result is NULL from the right table. •Syntax: •SELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
  • 33. Ex:SELECT * FROM class LEFT JOIN classinfo ON (class.id=classinfo.id); ID NAME 1 ABHI 2 ADAM 3 ALEX 4 ANU 5 ASHISH ID NAME ID ADDRESS 1 ABHI 1 DELHI 2 ADAM 2 MUMBAI 3 ALEX 3 CHENNAI 4 ANU NULL NULL 5 ASHISH NULL NULL ID Address 1 DELHI 2 MUMBAI 3 CHENNAI 7 NOIDA 8 PANIPAT
  • 34. Right Outer Join •A right outer join returns all rows from the right table and the matched rows from the left table. •If there is no match, the result is NULL from the left table. •Syntax: •SELECT * FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
  • 35. select * from class right outer join classinfo on (class.id=classinfo.id); ID NAME 1 ABHI 2 ADAM 3 ALEX 4 ANU 5 ASHISH ID ADDRESS 1 DELHI 2 MUMBAI 3 CHENNAI 7 NOIDA 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
  • 36. Full Outer Join •A full outer join combines rows when there is a match based on a specified condition and includes unmatched rows from both tables. •Syntax: •SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
  • 37. SELECT * FROM class FULL OUTER JOIN classinfo on (class.id=classinfo.id); ID NAME 1 ABHI 2 ADAM 3 ALEX 4 ANU 5 ASHISH ID ADDRESS 1 DELHI 2 MUMBAI 3 CHENNAI 7 NOIDA 8 PANIPAT ID NAME ID ADDRESS 1 ABHI 1 DELHI 2 ADAM 2 MUMBAI 3 ALEX 3 CHENNAI 4 ANU NULL NULL 5 ASHISH NULL NULL
  • 38. Q. Explain about Cross join with example?
  • 39. Cross JOIN or Cartesian Product •The SQL CROSS JOIN produces a result set which is the number of rows in the first table multiplied by the number of rows in the second table, if no WHERE clause is used along with CROSS JOIN. •This kind of result is called as Cartesian Product. •If, WHERE clause is used with CROSS JOIN, it functions like an INNER JOIN. Cross JOIN Syntax is, SELECT * from table1 CROSS JOIN table-name2;
  • 40. SELECT * from class cross JOIN classinfo; class classinfo ID NAME 1 ABHI 2 ADAM 4 ALEX ID Address 1 DELHI 2 MUMBAI 3 CHENNAI ID NAME ID Address 1 ABHI 1 DELHI 2 ADAM 1 DELHI 4 ALEX 1 DELHI 1 ABHI 2 MUMBAI 2 ADAM 2 MUMBAI 4 ALEX 2 MUMBAI 1 ABHI 3 CHENNAI 2 ADAM 3 CHENNAI 4 ALEX 3 CHENNAI
  • 41. Q. Explain about self join with example.
  • 42. Self Join • A self join is a type of inner join in which a table is joined with itself (which is also called unary relationship). • To join a table itself means that each row of the table is combined with itself and with every other row of the table. • Syntax: • Select column(s) from table1 t1, table1 t2 where condition; Ex: select x.student_name ,y.student_name from student x , student y where x.id=y.friend_id;
  • 44. Introduction to SQL •It is a structured query language , which is a computer language for storing, manipulating, and retrieving data stored in a relational data base. •It is a programming language that is used to work with data base. •It is an ANSI (AMERICAN NATIONAL STANDARD INSTITUTE) standard language.
  • 45. •It includes database creation, fetching rows, modifying rows etc.. •All the Relational Data Base Management Systems (RDBMS) like MY SQL, MS-ACCESS, Oracle, Sybase, Postgre sql and SQL Server use SQL as their standard data base language.
  • 46. History of SQL • SQL is initially developed in IBM by DONOLD D.CHAMBERLIN and RAYMOND F BOYCE in 1970. 1.1970:- •DR.E.F.CODD published the paper “ A relational model of data for large shared data banks” . •CODD’S model is now accepted as a definitive model for relational data base management system(RDBMS).
  • 47. 2.1978:- •IBM worked to developed codd’s ideas and released a product name SYSTEM/R. •Later the language structured English query language (SEQUEL) was developed by IBM corporation to use codd’s models. 3.1979:- •SEQUEL later it became SQL in 1979. •Today, sql is accepted as the standard RDBMS language 4.1986:- •The first relational database was first released by relational software which later came to be known as “ORACLE”.
  • 48. Q. Explain different types of datatypes available in sql.
  • 49. DATATYPES IN SQL • In SQL, data type specifies what type of data a column can contain. • SQL has different types of datatypes. They are • Exact numeric data types • Approximate numeric data types . • Date and time data type. • Character string data types • Other data types.
  • 51. DATA TYPES FROM TO Int -2,147,483,648 +2,147,483,647 Small int -32,768 +32,767 Big int 922,337,203,685,477,5808 922,337,203,685,477,5807 Tinyint 0 255 Bit 0 1 Decimal -10^38+1 +10^38+1 Numeric -10^38+1 10^38+1 Money 922,337,203,685,477,5808 +922,337,205,685,477,5807 Small money -214,748,3648 214,748,3647 Exact numeric
  • 52. • DECIMALS :- • It accepts numeric values, which may define precision &scale in the data type declaration. •SYNTAX:- decimal(p,s) •P-precision it represents the total no.of digits. •S-scale it represents the number of digits accepted after decimal point. •EX: AVG DECIMAL(4,2) 45.2 is correct 45.22 is correct 456.22 is wrong 456.2 is wrong
  • 53. Number datatype • The Oracle NUMBER data type is used to store numeric values that can be negative or positive. The following illustrates the syntax of the NUMBER data type: syntax: number(p,s) • The Oracle NUMBER data type has precision and scale. • The precision is the number of digits in a number. It ranges from 1 to 38. • The scale is the number of digits to the right of the decimal point in a number. • For example, the number 1234.56 has a precision of 6 and a scale of 2. So to store this number, you need NUMBER(6,2).
  • 54. Approximate numeric Datatypes from to Float -1.79E+308 1.79E+308 Real/double -3.40E+38 3.40E+38
  • 55. FLOAT :- •It accepts real values which may define a precision of upto a maximum of 64. •SYNTAX :- • float(p) / float • Ex :- avg float(10) REAL / DOUBLE :- •it accepts real values of upto a precision of 64. •no parameters are required when declaring a real type. •SYNTAX :- Real Ex :- avg real.
  • 56. DATE AND TIME DATATYPES Datatype from To Datetime Jan1,1753 Dec31,9999 Date Storesadatelikejun31,1991 Time Storestimeofdaylike12:00pm
  • 57. Character datatypes •It accepts character type data. The different types of character data types are •1.char •2.varchar-variable character •3.varchar2
  • 58. char •it accepts a fixed length non – Uni code character data . •it stores a maximum length upto 8000 characters. •Syntax :- char(n) • Here ‘n’ represents number of characters . •Ex :- sname char(10)
  • 59. varchar •it accepts a variable length , non –unicode character data. •It stores a maximum length upto 4000 characters . •Syntax :- varchar(n) • Ex :- sname varchar(10).
  • 61. varchar2 •It accepts a variable length non -Unicode character data. •It stores a maximum length up to 4000 characters . •Syntax :- varchar2(n) •Ex :- sname varchar2(10).
  • 62. Other Datatypes •The other data types are CLOB (CHARACTER LARGE OBJECT ) , BLOB (BINARY LARGE OBJECT ). •CLOB :- • It stores varaiable length character data that can be a single byte ( or ) multi – byte (supports more than 4 gb ) •BLOB :- • This type is used to store large amount of binary data such as images ( or ) other type of files .
  • 63. Q. Write about SQL commands?
  • 64. SQL COMMANDS • SQL is a software which is used to work with database. It is a fourth generation language. • It is a non-procedural language which contains set of commands. • All SQL commands are divided into four types. They are 1. Data definition language (DDL). 2. Data manipulation language (DML). 3. Data control language (DCL). 4. Transaction control language (TCL).
  • 67. Q. Explain about DDL commands with examples.
  • 68. DDL COMMANDS • DDL stands for DATA DEFINITION LANGUAGE . DDL commands are used to work with the structure of the data base . •There are six different commands in DDL. They are 1.create 2.Alter 3.drop 4.rename 5.truncate 6.comment
  • 69. CREATE • Create command is used to create data base object like tables , indexes, views, sequences on data base . Syntax :- Create table tablename (column1 datatype(size),column2 datatype(size),……); Ex :- command for creating customer table . SQL>create table customer (cno varchar(5),ename varchar(20), Addres varchar(20)); •
  • 70. ALTER •ALTER COMMAND TO ADD NEW COLUMN :- •SYNTAX :- Alter table tablename add (columnname datatype(size)); •Ex :- Alter table customer ADD (phnno char(10),email id varchar(20)); Alter add new column drop existing column modify existing column
  • 71. •ALTER COMMAND TO DROP A COLUMN:- SYNTAX :- Alter table tablename drop (course name ); Ex :- Alter table customer Drop (emailid); •ALTER COMMAND TO MODIFY:- SYNTAX :- Alter table tablename modify(column datatype(size),…..); •Ex :- SQL>Alter table book modify(ISBN varchar(12));
  • 72. DROP •Drop command is used to destroy (delete) an existing object from a database. Syntax :- Drop table tablename ; EX :- SQL>Drop table book ;
  • 73. RENAME •Rename command is used to rename a table . •Syntax :- Rename <old tablename> to <new tablename>; •Ex:- SQL>Rename employee to emp;
  • 74. TRUNCATE •This command is used to delete complete data in a table . The data deleted from tables cannot be rolled back. •Syntax :- truncate table <table name>; •Ex:- SQL>truncate table emp;
  • 75. COMMENT •This command is used to add comment to the existing table. •Syntax :- Comment on table <tablename> is “comment sentence”; •Ex :-comment on student is “to store student personal details”; •
  • 76. •To view the table comment :- •Syntax :- SQL >select comments from user _tab_comments where Table-name =’TABLE NAME’; •the table name must be given in capital letters only.
  • 77. Q. Explain about DML Commands. (or) Explain the form of a basic SQL query in detail with examples.
  • 78. DML • DML is used to insert, modify, delete and retrieve data in a data base. • There are four types of DML commands available in SQL. They are 1.INSERT 2.UPDATE 3.DELETE 4.SELECT
  • 79. INSERT •This command is used to add records to the existing table. •“&” is used to insert command to accept values at SQL prompt. •There are three ways to insert records in a table. •To insert values for one record :- Syntax:- insert into tablename values(value1,value2…..);
  • 80. • To insert data for a particular columns in a table :- • Syntax :- insert into tablename ((columname1,columname2….) values(exp1,exp2….); • To insert multiple records at a time :- • Syntax:- insert into tablename values (&columname1…….); • NOTE:-Put single quotes ( ’ ‘) for varchar data type column in insert command. • Ex :- SQL>insert into vijaya values(&sno,’&sname’,&marks); • Enter value for s.no: 1 • Enter value for sname : lucky • Enter value for marks : 98 • 1 row created • SQL>/ Here ‘/ ‘ is a character used to enter another record in a table.
  • 81. UPDATE •i) The update command is used to change ( or) modify data values in a table . •ii) it is used to update either all rows from a table.(or)set of selected rows from a table. •Syntax :- update < tablename > set colname = expression, colname=expression; •This command is used to update all rows in a table
  • 82. •Syntax :- Update tablename set colname=expression,colname = expression where <condition>; •To update selected row in a table •Ex :- Update student set tot =sub1+sub2+sub3; ( or ) •Update student set tot = sub1+sub2+sub3 where sno=2;
  • 83. DELETE •The delete command is used to delete the records from a table. •It is used to delete either all rows from a table (or)set of selected rows from a table. •Syntax :- to delete all rows from a table Delete from <tablename>; •To delete a particular row in a table . •Syntax :- delete from<tablename>[where < condition>]; •ex :- SQL>delete from student; • (or) • SQL> delete from student where sno =2;
  • 84. SELECT •Select command is used to retrieve the data from a table in data base according to user requirements . • The complete syntax for select statement is : •Syntax :- •Select [distinct][*][colnames] [aggregate operation] from <tablename> [where <search condition>] [Group by group –by-us] [Having<search condition>] [ order by orderlist [asc][desc]];
  • 85. SELECT •Ex :- select *from student; (or) •Select sub1,sub2,sub3 from student ; (or) •Select * from student where sno=3;
  • 86. •Distinct clause: • The SQL Distinct clause used along with the SELECT command. It is a keyword which retrieves only unique data entries depending on the column list. •Ex: select distinct student from emppayroll; • •(*): Star: • It retrieves all the records in a table. •Ex: select * from emp;
  • 87. •WHERE: •Where clause – The Where clause is used to filter records. •The WHERE clause is used to extract only those records that fulfills a specified condition. •Ex: select * from emp where eno=2; •Group by clause: •It is used to retrieve the records depending upon a particular column. •It divides the column data into different groups. •It is often used with aggregate functions to group the results with by one or more column. •Ex: select dno, sum(sal) from emp group by dno;
  • 88. •Having clause: •The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. •It is used with group by statement. •Ex: SQl>select dno, sum(sal) from emp group by dno having dno>10;
  • 89. •Order by: • The order by keyword is used to sort the data in ascending or descending order. •It sorts the records in ascending order by default. To sort the record in descending order, we use ‘Desc’ keyword. •Ex: SQL> select * from emp order by eno; • Or • SQL> select * from emp order by eno desc;
  • 90. Q. Explain about Aggregate functions /Operators in SQL.
  • 91. AGGREGATE FUNCTIONS •These are the functions in SQL which are applied in a group of records. •These are used to find aggregate values like sum, average etc…for a group of records in a database •We can apply this function on a database by using a special keyword known as ‘ GROUP BY’. •GROUP BY is a keyword which is used to group the records in a database on a particular column.
  • 93. • 1.COUNT:- The function is used to count a number of records in a database (table) • Ex-1:Select count(*) from emp; • 2.select dno,count(*)from emp group by dno; • 2.SUM:- This function is used to get the sum of values for the given attribute on the database . • Ex-1:select sum(sal) from emp; • 2: select dno,sum(sal)from emp group by dno having dno=1; • 3.AVG :- This function is used to get the average of values of given attribute from a database • Ex-1: select avg(sal) from emp; • select dno,avg(sal) from emp group by • dno;
  • 94. • 4.MAX :- This function is used to get maximum value for the given attribute form a database. •ex :- SQL>select dno,max(sal) from emp group by dno; •5.MIN :- The function is used to get minimum value for a given attribute from a datatype. •Ex :- SQL>select dno,min(sal) from emp group by dno;
  • 95. Q. Explain different types of operators available in SQL.
  • 97. AND,OR,NOT •The WHERE clause can be combined with AND, OR, and NOT operators. •The AND and OR operators are used to filter records based on more than one condition: •The AND operator displays a record if all the conditions separated by AND are TRUE. •The OR operator displays a record if any of the conditions separated by OR is TRUE. •The NOT operator displays a record if the condition(s) is NOT TRUE.
  • 98. •AND Syntax •SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND condition3 ...; •OR Syntax •SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR condition3 ...; •NOT Syntax •SELECT column1, column2, ... FROM table_name WHERE NOT condition;
  • 99. IN •The SQL IN Operator •The IN operator allows you to specify multiple values in a WHERE clause. •The IN operator is a shorthand for multiple OR conditions. •IN Syntax •SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...); •Ex: select * from emp where eid in(1,3,5);
  • 100. BETWEEN •The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. •The BETWEEN operator is inclusive: begin and end values are included. •BETWEEN Syntax •SELECT * FROM table_name WHERE column_name BETWEEN value1 AND value2; •Ex: select * from emp where salary between 10000 and 20000;
  • 101. LIKE •The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. •There are two wildcards often used in conjunction with the LIKE operator: • The percent sign (%) –It represents any number of characters,even zero characters • The underscore sign (_)-It can by any character or number, but each _ represents one, and only one, character. •Ex: select * from emp where ename like ‘s%’;
  • 102. LIKE Operator Description • WHERE CustomerName LIKE 'a%' Finds any values that starts with ‘a’ • WHERE CustomerName LIKE '%a' Finds any values that end with ‘a’ • WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position • WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position • WHERE CustomerName LIKE 'a_%' Finds any values that starts with "a" and are at least 2 characters in length • WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters in length • WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
  • 103. Q.What are the integrity constraints(Ics) over relations? Explain in details.
  • 104. Integrity constraints : •Constraints are used to limit the type of data that can go into a table. • This ensures the accuracy and reliability of the data in the table. •Constraints could be column level or table level. •Column level constraints are applied only to one column, whereas table level constraints are applied to the multiple columns.
  • 105. •Following are commonly used constraints available in SQL. 1. PRIMARY KEY 2. FOREIGN KEY 3. NOT NULL 4. UNIQUE 5. CHECK 6. DEFAULT
  • 106. Primary Key • The PRIMARY KEY constraint uniquely identifies each record in a database table. • Primary keys must contain UNIQUE values, and cannot contain NULL values. Primary Key at column level: • Example >CREATE TABLE Persons (ID NUMBER PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255)); Primary Key at table level: Example >CREATE TABLE Persons (ID NUMBER , LastName varchar(255) NOT NULL, FirstName varchar(255),primary key(ID));
  • 107. Foreign Key • A FOREIGN KEY is a key used to link two tables together. • A FOREIGN KEY is a field in one table(Child table) that refers to the PRIMARY KEY in another table(Parent table). • Example Creating parent table: • > CREATE TABLE DEPT(DEPTNO NUMBER PRIMARY KEY, DNAME VARCHAR2(10), LOC VARCHAR2(10); NUMBER PRIMARY • Creating child table at column level: • >CREATE TABLE EMP(EMPNO NUMBER PRIMARY KEY, ENAME VARCHAR2(10), DEPTNO NUMBER REFERENCES DEPT(DEPTNO)); • Creating child table at table level: • >CREATE TABLE EMP(EMPNO NUMBER PRIMARY KEY, ENAME VARCHAR2(10), DEPTNO NUMBER ,FOREIGN KEY(DEPTNO) REFERENCES DEPT(DEPTNO));
  • 108. NOT NULL • The NOT NULL constraint enforces a column to NOT accept NULL values. • It can be applied at column level only. • Example >CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255) NOT NULL);
  • 109. UNIQUE •The UNIQUE constraint ensures that all values in a column are different. • Example: • >CREATETABLE Persons ( ID NUMBER UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255));
  • 110. CHECK •The CHECK constraint is used to limit the value range that can be placed in a column. •EXAMPLES >CREATE TABLE TEST( EMPNO NUMBER, SAL NUMBER CHECK(SAL>5000)); >CREATE TABLE TEST(EMPNO NUMBER , AGE NUMBER CHECK(AGE>25)
  • 111. DEFAULT • 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. • EXAMPLE • >CREATE TABLE Persons ( ID NUMBER NOT NULL, City varchar(255) DEFAULT ‘MEXICO');
  • 112. Q. Explain different types of set operators?
  • 113. SQL Set Operation •The SQL Set operation is used to combine the two or more SQL SELECT statements. Types of Set Operation •1. Union •2. Union All •3. Intersect •4. Minus
  • 114. 1. Union • The SQL Union operation is used to combine the result of two or more SQL SELECT queries. • In the union operation, all the number of datatype and columns must be same in both the tables on which UNION operation is being applied. • The union operation eliminates the duplicate rows from its resultset. • Syntax : • SELECT column_name FROM table1 UNION SELECT column_name FROM table2;
  • 116. 2. Union All • Union All operation is equal to the Union operation. • It returns the set without removing duplication and sorting the data. • Syntax: SELECT column_name FROM table1 UNION ALL SELECT column_name FROM table2;
  • 117. 3. Intersect • It is used to combine two SELECT statements. The Intersect operation returns the common rows from both the SELECT statements. • Syntax SELECT column_name FROM table1 INTERSECT SELECT column_name FROM table2; • Ex:SELECT * FROM First INTERSECT SELECT * FROM Second;
  • 118. 4.Minus/Except • It combines the result of two SELECT statements. • Minus operator is used to display the rows which are present in the first query but absent in the second query. • It has no duplicates and data arranged in ascending order by default. • Syntax: • SELECT column_name FROM table1 MINUS SELECT column_name FROM table2;
  • 119. Q. Explain NESTED QUERIES with examples. (or) Explain any and all operators with examples.
  • 120. Nested Query •A nested query(also called a subquery) is a query embedded within another SQL Query. •A subquery is an SQL query nested inside another query. •The query that contains a subquery is known as an outer query. •It is often used in the WHERE, HAVING, or FROM clauses of a statement. Subqueries are commonly used with SELECT, UPDATE, INSERT, and DELETE statements to achieve complex filtering and data manipulation. •The result of the inner query is used by the outer query to perform further operations.
  • 121. Types of Nested Queries in SQL • Subqueries can be either correlated or non-correlated
  • 122. Independent Nested Query •In independent nested queries, the execution of the inner query is not dependent on the outer query. •The result of the inner query is used directly by the outer query. •The inner query is independent of the outer query. •Operators like IN, NOT IN, ANY, and ALL are commonly used with this type of nested query. ANY and ALL: •The ANY compares a value with any value returned by the subquery, while ALL ensures comparison with all values.
  • 123. Syntax of Nested Queries • SELECT column1, column2, ... FROM table1 WHERE column1 operator ( SELECT column1 FROM table2 WHERE condition ); Ex: A nested query has two SELECT STATEMENTS: one for the inner query and another for the outer query.
  • 124. Examples 1.SELECT first_name, salary FROM employees WHERE salary > ( SELECT AVG(salary) FROM employees ) ORDER BY salary; 2. SELECT first_name, salary FROM employees WHERE salary = ( SELECT MAX(salary) FROM employees ); 3. Find details of customers who have ordered. Query: SELECT * FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders); 4. SELECT ename from Employee where deptId=(SELECT deptId from Department where dname=‘CSM’); 5.Select * from employees where salary> any(select salary from depart where deptid=1); 5.Select * from employees where salary> all(select salary from depart where deptid=1);
  • 125. Correlated Nested Queries •Correlated subqueries are dependent on the outer query. •A correlated nested query is a subquery that uses values from the outer query. •The inner query depends on the outer query for its execution. For each row processed by the outer query, the inner query is executed. •The EXISTS keyword is often used with correlated queries. •EXISTS: The Exists operator checks for the existence of rows in a subquery. It returns true if the subquery produces any rows.
  • 126. • Syntax: SELECT column01 FROM table1 WHERE column02 operator ( SELECT column02 FROM table2 WHERE table1.column03 = table2.column04 ); • Find details of customers who have ordered. Query: SELECT * FROM Customers where EXISTS (SELECT OrderID FROM Orders WHERE Orders.OrderID=Customers.OrderID); Example 2: Select * from employee where exists(select * from depart where employee.deptid=depart.deptid;
  • 127. Difference b/w Nested & Correlated subquery NESTED SUBQUERY CORRELATED SUBQUERY A query is nested inside another query in a nested query, and the result of the inner query is used in the execution of the outer query. A query is nested inside another query in a Correlated query, and the inner query uses the values from the outer query. Inner query executes first, and only once, in a bottom-up method. The result of the Inner query is used to run the outer query. Top to Bottom Approach, in which the outer query executes first, followed by the inner query for each row of the outer query. The execution of an inner query is independent of the execution of an outer query. The inner query is influenced by the outer query. Performance is superior than Correlated Query, but slower than Join Operation. Performs slower than both Nested Query and Join operations since the inner query is executed for
  • 128. Define Null Values? 1. Understanding NULL • NULL represents the absence of a value in a column. • It is different from zero, an empty string, or any other default value. 2. Checking for NULL • To check for NULL values in SQL, use the IS NULL or IS NOT NULL operators. Ex: • SELECT * FROM employees WHERE department IS NULL; 3.Updating NULL Values • To update NULL values in a table, use the UPDATE statement with IS NULL. • Ex: • UPDATE employees SET department = 'General' WHERE department IS NULL;
  • 129. Q. Write about division operation with example.
  • 130. DIVISION operation • The DIVISION operation, denoted by ÷, is useful for a special kind of query that sometimes occurs in database applications. • The DIVISION operation is a binary relational operation that divides one set of rows into another set of rows based on specified conditions. • It is similar to a JOIN operation, but the resulting table contains only the rows that belong to the first set and satisfy the division condition.
  • 131. • R1 ÷ R2 = tuples of R1 associated with all tuples of R2. • Ex: Retrieve the name of the subject that is taught in all courses. ÷ Name Course C Btech DBMS Mtech DBMS Btech JAVA Btech Course Btech Mtech The result is as follows Name DBMS
  • 132. Adding & Dropping Constraints USING ALTER
  • 133. SQL PRIMARY KEY Constraint on ALTER TABLE • To create a PRIMARY KEY constraint on the "ID" column when the table is already created, Example • >ALTER TABLE Persons ADD PRIMARY KEY(ID); • Dropping: >ALTER TABLE persons drop PRIMARY KEY;
  • 134. SQL FOREIGN KEY Constraint on ALTER TABLE • To create a FOREIGN KEY constraint on the "ID" column which refers to the primary key in persons1 table, when the table is already created, Example • >ALTER TABLE Persons ADD FOREIGN KEY(ID) REFERENCES Persons1(ID); • Dropping: >ALTER TABLE persons drop FOREIGN KEY(ID);
  • 135. SQL UNIQUE Constraint on ALTER TABLE • To create a UNIQUE constraint on the "ID" column when the table is already created, Example • >ALTER TABLE Persons ADD UNIQUE(ID); • Dropping: >ALTER TABLE persons drop unique(ID);
  • 136. SQL CHECK Constraint on ALTER TABLE • To create a CHECK constraint on the "ID" column when the table is already created, Example • >ALTER TABLE Persons ADD CHECK(ID BETWEEN 1 AND 1000); • Dropping: >ALTER TABLE persons drop CHECK(ID);
  • 137. SQL NOT NULL Constraint on ALTER TABLE • To create a NOT NULL constraint on the "ID" column when the table is already created, Example • >ALTER TABLE Persons MODIFY ID int NOT NULL; • Dropping: >ALTER TABLE persons MODIFY ID int NULL;
  • 138. SQL default Constraint on ALTER TABLE • To create a DEFAULT constraint on the "ID" column when the table is already created, Example • >ALTER TABLE Persons MODIFY ID int default 1; • Dropping: >ALTER TABLE persons MODIFY ID int default NULL;