DBMS Unit - Ii
DBMS Unit - Ii
SYLLABUS
Introduction to the Relational Model: Structure of RDBMS, Integrity Constraints over Relations,
Querying Relational Data, Relational Algebra and Relational Calculus.
Introduction to SQL: Data Definition commands, Data Manipulation Commands, Basic Structure,
Set operations, Aggregate Operations, Join Operations, Sub queries and correlated queries, views,
Triggers, Cursors, Embedded SQL, Overview of NoSQL database.
1
A19PC1CS04 UNIT – III DBMS
Unique Constraint
• The unique specification no two tuples in the relation can be equal on all the listed attributes.
• Example: roll int unique
• However, attributes declared as unique are permitted to be null unless they have explicitly been
declared to be not null.
• Example: roll int not null unique
• Recall that a null value does not equal any other value.
Referential integrity constraint:
• Referential Integrity Constraint is used to specify interdependencies between relations.
• This constraint specifies a column or list of columns as a foreign key of the referencing table.
• A foreign key means the values in one table must also appear in another table.
• The foreign key in the child table will generally reference a primary key in the parent table.
• The referencing table is called the child table & referenced table is called the parent table.
• In order to provide Referential Integrity, the conditions must exist
1) The data types of TWO columns must be same
2) The referenced key must be Primary Key.
Key Constraints:
• Keys are the entity set that is used to identify an entity within its entity set uniquely.
• An entity set can have multiple keys, but out of which one key will be the primary key.
• A primary key can contain a unique and not null value in the relational table.
Assigning Names to Constraints:
• It is possible for us to assign a name to integrity constraints.
• Such names are useful if we want to drop a constraint that was defined previously.
• The constraint is a keyword to create constraint and the name we wish to assign it.
• Example: salary numeric (8,2),
constraint minsalary check (salary > 29000)
• Later, if we decide we no longer want this constraint, we can write:
• Example: alter table instructor drop constraint minsalary;
2
A19PC1CS04 UNIT – III DBMS
Relational Algebra:
• Relational algebra is a procedural query language, which takes instances of relations as input and
yields instances of relations as output.
• The relational algebra consists of a set of operations that take one or two relations as input a nd
produce a new relation as their result.
• The relational algebra is very important for several reasons.
1. It provides a formal foundation for relational model operations.
2. It is used as a basis for implementing and optimizing queries in the query processing and
optimization modules that are integral parts of relational database management systems
(RDBMSs).
3. Some of its concepts are incorporated into the SQL standard query language for RDBMSs.
• The relational algebra operations can be divided into two groups.
1. Unary Operations (select, project, and rename)
2. Binary Operations (union, Intersection, Cartesian product, and set difference)
Working Tables
emp
empno ename job mgr hiredate sal comm deptno
Unary Relational Operations: The unary operations are applied to a single relation (table).
SELECT Operation:
• The SELECT operation is used to retrieve a subset of the tuples from a relation that satisfies a
selection condition.
• The symbol σ (sigma) is used to denote the SELECT operator.
• Syntax: σ < selection condition> ( R )
• Where selection condition is a Boolean expression (condition) specified on the attributes of
relation R.
• For example, to select the EMPLOYEE tuples whose department is 4, SELECT operation as
follows:
σ Dno= 4 ( EMPLOYEE)
• The SELECT operation can also be visualized as a horizontal partition of the relation into two sets
of tuples:
➢ Tuples that satisfy the condition and are selected.
➢ Tuples that do not satisfy the condition and are discarded.
• The <selection condition> is applied independently to each individual tuple t in R.
• The Boolean expression specified in <selection condition> is made up of a number of clauses of
the form.
<attribute name> <comparison op> <constant value>
Or
<attribute name> <comparison op> <attribute name>
• Where <attribute name> is the name of an attribute of R
<comparison op> is normally one of the operators {=, <, ≤, >, ≥, ≠}
For ordered values (numeric or date), the comparison operators are {=, <, ≤, >, ≥, ≠}
For unordered values (names, colors), the comparison operators are {=, ≠}
• The number of tuples in the resulting relation is always less than or equal to the number of tuples
in R. That is, |σc ( R)| ≤ |R| for any condition C.
• The degree of the relation is the number of attributes in a relation.
• Notice that the SELECT operation is commutative; that is,
σ < cond1> ( σ < cond2> ( R )) = σ < cond2> ( σ < cond1> ( R ))
• we can always combine a cascade (or sequence) of SELECT operations into a single SELECT
operation with a conjunctive (AND) condition; that is,
σ < cond1> ( σ < cond2> ( ...( σ < condn> ( R )) ...)) = σ < cond1> AND< cond2> AND...AND < condn> ( R )
• In SQL, the SELECT condition is typically specified in the WHERE clause of a query.
• For example, the following operation:
σ Dno= 4 AND Salary> 25000 ( EMPLOYEE)
• would correspond to the following SQL query:
SELECT * FROM EMPLOYEE WHERE Dno=4 AND Salary>25000;
4
A19PC1CS04 UNIT – III DBMS
PROJECT Operation:
• The PROJECT operation is used to retrieve only certain attributes (columns) in a relation.
• The PROJECT operation is display the attributes in the same order as they appear in the list.
• π (pi) is the symbol used to represent the PROJECT operation.
• Syntax: π < attribute list> ( R )
• Where <attribute list> is the desired sub-list of attributes from the relation R.
• For example, to list each employee’s first and last name and salary, we can use the PROJECT
operation as follows:
π Lname, Fname, Salary( EMPLOYEE)
• The PROJECT operation can be visualized as a vertical partition of the relation into two
relations:
➢ One has the needed columns (attributes) and contains the result of the operation.
➢ The other contains the discarded columns.
• Degree is equal to the number of attributes in <attribute list>.
• If the attribute list includes only non-key attributes of R, duplicate tuples are likely to occur.
• The PROJECT operation removes any duplicate tuples from relation and retrieve a valid set of
distinct tuples is known as duplicate elimination.
• For example, consider the following PROJECT operation:
π Sex, Salary ( EMPLOYEE)
• Notice that the tuple <‘F’, 25000> appears only once in above Figure, even though this
combination of values appears twice in the EMPLOYEE relation.
• It is note that commutativity does not hold on PROJECT.
• In SQL, the PROJECT attribute list is specified in the SELECT clause of a query.
• For example, the following operation:
π Sex, Salary ( EMPLOYEE)
• Would correspond to the following SQL query:
SELECT DISTINCT Sex, Salary FROM EMPLOYEE
• Writing a relational algebra expression in single line known as an in-line expression.
• To rename the attributes in a relation, we simply list the new attribute names in parentheses.
• Rename operation is denoted with the symbol ρ (rho)
• If no renaming is applied, the names of the attributes in the resulting relation of a SELECT
operation are the same as those in the original relation and in the same order.
• We can rename either the relation name or the attribute names, or both—as a unary operator.
• The general RENAME operation when applied to a relation R of degree n is denoted by any of the
following three forms:
ρS ( R ) or ρ( B1, B2, ..., Bn)( R ) or ρ S ( B 1, B 2, ..., Bn)( R )
• Where the symbol ρ (rho) is used to denote the RENAME operator, S is the new relation name,
and B1, B2 , ..., Bn are the new attribute names.
5
A19PC1CS04 UNIT – III DBMS
• Suppose we have a relation named Students and we want to change it to FinalYrStudents the
rename operation works as follows:
ρFinalYrStudents(Students)
Suppose we have a relation named Students and we want to change its attributes
StudentID, StudentName to SID and SName, the rename operation works as follows:
ρ(SID,SName)(Students)
we'll change both the relation’s name and attributes of the Students class:
ρFinalYrStudents(SID,SName)(Students)
• The first expression renames the relation only, the second renames the attributes only, and the third
renames both the relation and its attributes.
• Renaming in SQL is accomplished by aliasing using AS, as in the following example:
SELECT E.Fname AS First_name, E.Lname AS Last_name, E.Salary AS Salary
FROM EMPLOYEE AS E WHERE E.Dno=5;
Binary Operations: The binary operations are applied to two relations (table).
UNION, INTERSECTION, and SET DIFFERENCE(MINUS) Operations
• Set theoretic operations are used to merge the elements of two sets in various ways, including
UNION, INTERSECTION, and SET DIFFERENCE (also called MINUS or EXCEPT).
• These are binary operations; that is, each is applied to two relations.
• The two relations on which any of these three operations are applied must follow two rules.
✓ Two relations must have the same number of attributes.
✓ Two relations must have union compatibility or type compatibility (i.e., same type of
tuples).
• Two relations R(A1 , A2 , ..., An ) and S(B1 , B2 , ..., Bn ) are said to be union compatible (or type
compatible) if they have the same degree n and if dom(Ai) = dom(Bi).
• We can define the three operations UNION, INTERSECTION, and SET DIFFERENCE on two
union-compatible relations R and S as follows:
❖ UNION: The result of this operation, denoted by R ∪ S, is a relation that includes all tuples
that are either in R or in S or in both R and S. Duplicate tuples are eliminated.
❖ INTERSECTION: The result of this operation, denoted by R ∩ S, is a relation that includes
all tuples that are in both R and S.
❖ SET DIFFERENCE (or MINUS): The result of this operation, denoted by R – S, is a
relation that includes all tuples that are in R but not in S.
6
A19PC1CS04 UNIT – III DBMS
Dept X Salgrade
Deptno Dname Loc Losal Hisal Grade
10 ACCOUNTING NEW YORK 700 1200 1
10 ACCOUNTING NEW YORK 1201 1400 2
Dept 10 ACCOUNTING NEW YORK 1401 2000 3
Deptno Dname Loc 10 ACCOUNTING NEW YORK 2001 3000 4
NEW 10 ACCOUNTING NEW YORK 3001 9999 5
10 ACCOUNTING 20 RESEARCH DALLAS 700 1200 1
YORK
20 RESEARCH DALLAS 20 RESEARCH DALLAS 1201 1400 2
30 SALES CHICAGO 20 RESEARCH DALLAS 1401 2000 3
40 OPERATIONS BOSTON 20 RESEARCH DALLAS 2001 3000 4
7
20 RESEARCH DALLAS 3001 9999 5
30 SALES CHICAGO 700 1200 1
A19PC1CS04 UNIT - II DBMS
THETA JOIN:
• A JOIN operation with general join condition is called a THETA JOIN.
• Syntax:
R <join condition>S or R ɵS
• Where R and S are two relations R (A1 , A2 , ..., An ) and S(B1 , B2 , ..., Bm ).
• where each <condition> is of the form A i θ Bj, Ai is an attribute of R, Bj is an attribute of S, Ai
and Bj have the same domain, and θ (theta) is one of the comparison operators {=, <, ≤, >, ≥, ≠}.
• Example: to retrieve the employee names and their grades
π Ename , Grade(Emp emp.sal>=salgrade.losal AND emp.sal>=salgrade.hisal Salgrade Salgrade)
• Tuples whose join attributes are NULL or for which the join condition is FALSE do not appear
in the result.
EQUI JOIN:
• A JOIN, where the only comparison operator used is =, is called an EQUIJOIN.
• EQUIJOIN we always have one or more pairs of attributes that have identical values in
every tuple.
• Example: π Ename , Deptno, Dname(Emp emp.deptno=dept.deptno Dept)
NATURAL JOIN:
• A NATURAL JOIN is the set of tuples of all combinations in R and S that are equal on their
common attribute names.
• NATURAL JOIN denoted by .
• A NATURAL JOIN requires that the two join attributes (or each pair of join attributes)
have the same name in both relations.
• NATURAL JOIN was created to get rid of the second (superfluous) attribute in an EQUIJOIN
condition.
• Example: π Ename , Deptno, Dname(Emp Dept)
• If this is not the case, a renaming operation is applied first.
Example: e1EMP e2EMP mgre2.Empno
π e1.Ename , e2.Ename (e1 e2)
• Join attribute: an attribute is used to join the both relations are called join attribute.
• In JOIN, only combinations of tuples satisfying the join condition appear in the result, whereas
in the CARTESIAN PRODUCT all combinations of tuples are included in the result.
• The expected size of the join result divided by the maximum size n R * nS leads to a ratio called
join selectivity, which is a property of each join condition.
8
A19PC1CS04 UNIT - II DBMS
• Outer joins were developed for the case where the user wants to keep all the tuples in R, or all
those in S, or all those in both relations in the result of the JOIN, regardless of whether or not
they have matching tuples in the other relation.
• This satisfies the need of queries in which tuples from two tables are to be combined by matching
corresponding rows, but without losing any tuples for lack of matching values.
• There are three type of outer joins are there
1. LEFT OUTER JOIN The LEFT OUTER JOIN operation keeps every tuple in the first, or left,
relation R and common with S is denoted by R S.
2. RIGHT OUTER JOIN The RIGHT OUTER JOIN operation keeps every tuple in the second,
or right, relation S and common with R is denoted by R S.
3. FULL OUTER JOIN The FULL OUTER JOIN operation keeps both tuple in the left and
right, relations in R S.
• If no matching tuple is found in relations, then filled or padded with NULL values.
• For example, list of all employee names as well as the name of the departments they manage.
• If employee manage a department, then department name will be result; if they do not manage
placed with NULL value. We can apply an operation LEFT OUTER JOIN
9
A19PC1CS04 UNIT - II DBMS
• Apply the DIVISION operation to the two relations, which gives the desired employees’ Social
Security numbers:
10
A19PC1CS04 UNIT - II DBMS
Generalized Projection
• The generalized projection operation extends the projection operation by allowing functions of
attributes to be included in the projection list.
• Syntax:
πF 1, F2, ..., Fn ( R)
• Where F1 , F2 , ..., Fn are functions over the attributes in relation R and may involve arithmet ic
operations and constant values.
• As an example, consider the relation
EMPLOYEE ( Ssn, Salary, Deduction, Years_service)
• A report may be required to show
Net Salary = Salary – Deduction,
Bonus = 2000 * Years_service, and
Tax = 0.25 * Salary.
• Then a generalized projection combined with renaming may be used as follows:
REPORT ← ρ( Ssn, Net_salary, Bonus, Tax) ( π Ssn, Salary – Deduction, 2000 * Years_service, 0.25 * Salary ( EMPLOYEE)).
• Where <grouping attributes> is a list of attributes of the relation specified in R, <function list>
is a list of (<function> <attribute>) pairs.
• Example: List Count of employees in each department and their average salary.
( Dno ℑ COUNT Ssn, AVERAGE Salary ( EMPLOYEE))
• If no renaming is applied, then the attribute names be the concatenation of the function name
with the attribute name in the form <function>_<attribute>.
• If rename is applied then corresponding rename attributes are displayed.
11
A19PC1CS04 UNIT - II DBMS
• If no grouping attributes are specified, the functions are applied to all the tuples in the relation,
so the resulting relation has a single tuple only.
• Example:
ℑ COUNT Ssn, AVERAGE Salary ( EMPLOYEE)
Query 2. For every project located in ‘Stafford’, list the project number, the controlling department
number, and the department manager’s last name, address, and birth date.
Ans: STAFFORD_PROJS ← σPlocation= ‘Stafford’( PROJECT)
CONTR_DEPTS ← ( STAFFORD_PROJS Dnum= DnumberDEPARTMENT)
Query 3. Find the names of employees who work on all the projects controlled by department number
5.
Ans: DEPT5_PROJS ← ρ( Pno) ( π Pnumber( σ Dnum= 5 ( PROJECT)))
EMP_PROJ ← ρ( Ssn, Pno) ( π Essn, Pno( WORKS_ON))
RESULT_EMP_SSNS ← EMP_PROJ ÷ DEPT5_PROJS
RESULT ← πLname, Fname( RESULT_EMP_SSNS * EMPLOYEE)
12
A19PC1CS04 UNIT - II DBMS
Query 4. Make a list of project numbers for projects that involve an employee whose last name is
‘Smith’, either as a worker or as a manager of the department that controls the project.
Ans: SMITHS( Essn) ← π Ssn ( σ Lname= ‘Smith’( EMPLOYEE))
SMITH_WORKER_PROJS ← πPno( WORKS_ON * SMITHS)
MGRS ← πLname, Dnumber( EMPLOYEE Ssn= Mgr_ssnDEPARTMENT)
Query 5. List the names of all employees with two or more dependents.
Ans: T1(Ssn, No_of_dependents) ← Essn ℑ COUNT Dependent_name( DEPENDENT)
T2 ← σNo_of_dependents> 2 ( T1)
RESULT ← πLname, Fname( T2 * EMPLOYEE)
Query 7. List the names of managers who have at least one dependent.
Ans: MGRS( Ssn) ← πMgr_ssn( DEPARTMENT)
EMPS_WITH_DEPS( Ssn) ← πEssn( DEPENDENT)
MGRS_WITH_DEPS ← ( MGRS ∩ EMPS_WITH_DEPS)
RESULT ← πLname, Fname( MGRS_WITH_DEPS * EMPLOYEE)
13
A19PC1CS04 UNIT - II DBMS
Relational Calculus:
• The relational calculus is a formal language, based on the branch of mathematical logic called
predicate calculus.
• The relational calculus provides a higher-level declarative language for specifying relational queries.
• In a relational calculus expression, there is no order of operations to specify how to retrieve the query
result—only what information the result should contain.
• This is the main distinguishing feature between relational algebra and relational calculus.
• There are two variations of relational calculus-tuple relational calculus and domain relational
calculus.
The Tuple Relational Calculus
• We can also retrieve only some of the attributes(say the first and last names) as
{t.Fname, t.Lname | EMPLOYEE( t) AND t .Salary>50000}
• we need to specify the following information in a tuple relational calculus expression:
➢ For each tuple variable t, the range relation R of t means R(t). If we do not specify a range
relation, then the variable t will range over all possible tuples “in the universe” as it is not
restricted to any one relation.
➢ A condition to select particular combinations of tuples from range relations, the condition is
evaluated for every possible combination of tuples to identify the selected combinations for
which the condition evaluates to TRUE.
➢ A set of attributes to be retrieved, the requested attributes. The values of these attributes are
retrieved for each selected combination of tuples.
14
A19PC1CS04 UNIT - II DBMS
{t1 . Aj, t2 . Ak , ..., tn .Am | COND( t1 , t2 , ..., tn , tn +1, tn +2, ..., tn+m)}
• where t1 , t2 , ..., tn , tn +1, ..., tn +m are tuple variables, each A i is an attribute of the relation on which
ti ranges, and COND is a condition or formula.
• A formula is made up of predicate calculus atoms, which can be one of the following:
1. An atom of the form R(ti), where R is a relation name and ti is a tuple variable.
2. An atom of the form t i. A op tj. B.
Where op is one of the comparison operators in the set {=, <, ≤, >, ≥, ≠},
ti and tj are tuple variables,
A is an attribute of the relation on which t i ranges, and
B is an attribute of the relation on which t j ranges.
3. An atom of the form ti. A op c or c op tj. B, where c is a constant value.
• A formula (Boolean condition) is made up of one or more atoms connected via the logical
operators AND, OR, and NOT and is defined recursively by Rules 1 and 2 as follows:
➢ Rule 1: Every atom is a formula.
➢ Rule 2: If F1 and F2 are formulas, then so are (F1 AND F 2 ), (F1 OR F 2 ), NOT ( F1 ).
a. ( F1 AND F 2 ) is TRUE if both F1 and F2 are TRUE; otherwise, it is FALSE.
b. ( F1 OR F 2 ) is FALSE if both F1 and F2 are FALSE; otherwise, it is TRUE.
c. NOT ( F1 ) is TRUE if F1 is FALSE; it is FALSE if F1 is TRUE.
d. NOT ( F2 ) is TRUE if F2 is FALSE; it is FALSE if F2 is TRUE.
• Quantifiers are two types, they are the universal quantifier (∀) and the existential quantifier
(∃).
• We need to define the concepts of free and bound tuple variables in a formula.
• Informally, a tuple variable t is bound if it is quantified, meaning that it appears in an (∃t) or (∀t)
clause; otherwise, it is free.
• we define a tuple variable in a formula as free or bound according to the following rules:
➢ An occurrence of a tuple variable in a formula F that is an atom is free in F.
➢ An occurrence of a tuple variable t is free or bound in a formula made up of logical connectives
—(F1 AND F 2 ), (F1 OR F 2 ), NOT( F1 ), and NOT( F2 ) -- depending on whether it is free
or bound in F1 or F2 (if it occurs in either).
• Truth values for formulas with quantifiers are described below-
➢ The formula (∃t)(F) is TRUE if the formula F evaluates to TRUE for some (at least one)
tuple assigned to free occurrences of t in F; otherwise, (∃t)(F) is FALSE.
➢ The formula (∀t)(F) is TRUE if the formula F evaluates to TRUE for every tuple (in the
universe) assigned to free occurrences of t in F; otherwise, (∀t)(F) is FALSE.
15
A19PC1CS04 UNIT - II DBMS
16
A19PC1CS04 UNIT - II DBMS
17
A19PC1CS04 UNIT - II DBMS
• An alternative shorthand notation, used in QBE (Query-By-Example), for writing this query is to
assign the constants ‘John’, ‘B’, and ‘Smith’ directly as shown in Q0A. Here, all variables not
appearing to the left of the bar are implicitly existentially quantified:
Q0A: { u , v | EMPLOYEE(‘John’,‘B’,‘Smith’,t,u,v,w,x,y,z) }
Query 1. Retrieve the name and address of all employees who work for the ‘Research’ department.
{ q, s, v | (∃z) (∃l) (∃m) (EMPLOYEE( qrstuvwxyz) AND DEPARTMENT( lmno) AND l
=‘Research’ AND m=z)}
Query 2. For every project located in ‘Stafford’, list the project number, the controlling department
number, and the department manager’s last name, birth date, and address.
{ i, k, s, u, v | (∃j)(∃m)(∃n)(∃t)(PROJECT( hijk) AND EMPLOYEE( qrstuvwxyz) AND
DEPARTMENT( lmno) AND k=m AND n=t AND j =‘Stafford’)}
18
A19PC1CS04 UNIT - II DBMS
Query 7. List the names of managers who have at least one dependent.
{ s, q | (∃t)(∃j)(∃l)(EMPLOYEE( qrstuvwxyz) AND DEPARTMENT( hijk) AND
DEPENDENT( lmnop) AND t=j AND l=t)}
19
A19PC1CS04 UNIT - II DBMS
Introduction to SQL
• SQL stands for Structured Query Language. It is used for storing and managing data in relational
database management system (RDMS).
• It is a standard language for Relational Database System. It enables a user to create, read, update and
delete relational databases and tables.
• All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as their standard
database language.
• SQL allows users to query the database in a number of ways, using English-like statements.
Database Languages/Commands
• DMBS provides set of languages/commands to manage database.
• The different types of DBMS commands are as follows
CREATE Command:
• It is used to create databases, tables, triggers and other database objects.
• Syntax to Create a Database:
CREATE Database Database_Name;
• Syntax to create a new table:
CREATE TABLE table_name (
column_Name1 data_type ( size of the column ) Constraint ,
column_Name2 data_type ( size of the column) Constraint ,
...
column_NameN data_type ( size of the column ) Constraint ) ;
• Example: create dept table
CREATE TABLE dept (
deptno NUMBER(2,0),
dname VARCHAR2(14),
location VARCHAR2(13) );
• Creating a Table from an Existing Table
• Instead of creating a new table every time, one can also copy an existing table and its contents
including its structure, into a new table.
• This can be done using a combination of the CREATE TABLE statement and the SELECT
statement.
• Since its is copied, the new table will have the same column definitions as the original table.
• Furthermore, the new table would be populated using the existing values from the old table.
• As it is a completely new table, any changes made in it would not be reflected in the original table.
20
A19PC1CS04 UNIT - II DBMS
• Syntax:
CREATE TABLE NEW_TABLE_NAME AS
SELECT [column1, column2,...columnN]
FROM EXISTING_TABLE_NAME
[WHERE CONDITION];
• Example: creating duplicate dept2 with existing columns from dept
CREATE TABLE dept2 AS select deptno,dname from dept;
INSERT Command:
• It is used to insert new record or tuple in a table.
• It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:
Syntax: INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example: INSERT INTO dept(deptno,dname,location) VALUES(10, 'ACCOUNTING', 'NEW YORK');
2. Insert values for all the columns of the table
Syntax: INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example: INSERT INTO dept VALUES(10, 'ACCOUNTING', 'NEW YORK');
3. Copy values from one table to another
• The INSERT INTO SELECT statement copies data from one table and inserts it into another table.
• The INSERT INTO SELECT statement requires that the data types in source and target tables match.
• Copy all columns from one table to another table:
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
• Copy only some columns from one table into another table:
INSERT INTO table2 (column1, column2, column3, ... columnn)
SELECT column1, column2, column3, ...columnn
FROM table1
WHERE condition;
• Example: insert into dept2 select * from dept;
21
A19PC1CS04 UNIT - II DBMS
UPDATE Command:
• UPDATE Query is used to modify the existing records in a table.
• This statement is a part of Data Manipulation Language, as it only modifies the data present in a table
without affecting the table's structure.
• Syntax: UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
• Example: change the location to Hyderabad for deptno 20.
SQL>UPDATE dept set location=”Hyderabad” where deptno=20;
DELETE Command:
• The DELETE statement is used to remove existing records in a table.
• The DELETE statement will not remove table.
• Syntax to delete specific record: DELETE FROM table_name WHERE condition;
• Example: remove the employee record 7521
SQL>DELETE FROM emp WHERE empno=7521;
• Syntax to delete all record: DELETE FROM table_name;
• Example: remove all employee records.
SQL>DELETE FROM emp;
TRUNCATE Command:
• The TRUNCATE TABLE command is used to delete all the records from an existing table by
reinitializing the table's structure.
• This command instructs the database to deallocate the space for all records in a table and change this
table's structure by resetting the table size.
• Syntax: TRUNCATE TABLE table_name;
• Example: remove all employee records.
SQL> TRUNCATE TABLE emp;
DROP Command:
• The DROP TABLE statement is a Data Definition Language (DDL) command that is used to remove a
table's definition, and its data, indexes, triggers, constraints and permission specifications (if any).
• You should be very careful while using this command because once a table is deleted then all the
information available in that table will also be lost forever.
• To drop a table in a database, one must require ALTER permission on the said table and CONTROL
permissions on the table schema.
• Syntax: DROP TABLE table_name;
• Example: remove the table emp.
SQL>DROP TABLE emp;
22
A19PC1CS04 UNIT - II DBMS
ALTER Command:
• The ALTER TABLE command is used to add, delete, or modify the structure of an existing table.
• The ALTER TABLE command is used to add and drop various constraints on an existing table.
• Syntax: ALTER TABLE table_name [alter_option];
• Where, the alter_option depends on the type of operation to be performed on a table.
• Adding a new column
➢ If you need to add a new column to a table you should use the ADD option to ALTER TABLE
statement.
➢ Syntax: ALTER TABLE table_name ADD column_name datatype;
➢ Example: add mgr column to dept.
SQL>ALTER TABLE dept ADD mgr int;
• Dropping a column
➢ You can drop an existing column by using the DROP COLUMN option to ALTER TABLE
statement.
➢ Syntax: ALTER TABLE table_name DROP COLUMN column_name;
➢ Example: remove mgr column from
SQL> dept.ALTER TABLE dept DROP COLUMN mgr;
• Modify size of column or datatype of column
➢ If you want change the column size or data type in table, the use MODIFY option to ALTER
TABLE statement.
➢ The size of column may be increase or decrease.
➢ Syntax: ALTER TABLE table_name MODIFY column_name data_type(new_size);
➢ Example: change location column size from 13 to 50 in dept table.
SQL>ALTER TABLE dept MODIFY location varchar2(50);
23
A19PC1CS04 UNIT - II DBMS
24
A19PC1CS04 UNIT - II DBMS
COMMIT Command:
• COMMIT in SQL is a transaction control language that is used to permanently save the changes done
in the transaction in tables/databases.
• The database cannot regain its previous state after its execution of commit.
• Syntax: commit;
ROLLBACK Command:
• The ROLLBACK command is the transactional command used to undo transactions that have not
already been saved to the database. This command can only be used to undo transactions since the last
COMMIT or ROLLBACK command was issued.
• It is used to restore the database to original since the last Commit.
• Syntax: ROLLBACK;
COMMENT Command:
• Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements.
• Single Line Comments syntax: --comment
• Multi Line Comments syntax: /* comment */
Basic Structure
• The fundamental structure of SQL queries includes three clauses that are select, from, and where
clause.
• Select clause specifies data to be retrieved from the table.
• From clause specifies list of tables where we can get the data.
• Where clause specifies how the relation must be operated to get the result.
• Syntax: SELECT Attribute list or expression
FROM Table List
WHERE Condition List;
• Example: List the employee names and their locations
SQL>select ename, location
from emp e,dept d
where e.deptno=d.deptno;
• Output: ENAME LOC
---------- -------------
KING NEW YORK
BLAKE CHICAGO
CLARK NEW YORK
JONES DALLAS
SCOTT DALLAS
FORD DALLAS
SMITH DALLAS
ALLEN CHICAGO
WARD CHICAGO
MARTIN CHICAGO
25
A19PC1CS04 UNIT - II DBMS
TURNER CHICAGO
ADAMS DALLAS
JAMES CHICAGO
MILLER NEW YORK
Clauses in SELECT statement:
1. FROM clause
2. WHERE clause
3. ORDER BY clause
4. GROUP BY clause
5. HAVING clause
1. FROM clause
• FROM clause specifies list of tables where we can get the data.
• It can also be used to retrieve records from multiple tables using JOIN condition.
• Syntax: select column1, column2,…,column from table1,…,tablen;
• Example: select ename, deptno from emp;
2. WHERE clause
• WHERE clause is used to filter records while retrieving data from a single table or multiple tables.
• This specifies a condition while fetching the data and if this condition is satisfied, then it returns
filtered data from the table.
• Syntax: SELECT column1, column2,... columnN
FROM table_name
WHERE [condition]
• Example: select ename, location
from emp e,dept d
where e.deptno=d.deptno;
3. ORDER BY clause
• The ORDER BY clause is used to sort the data in either ascending or descending order, based on
one or more columns.
• Sorting by multiple columns can be helpful when you need to sort data hierarchically, such as sorting
by state, city, and then by the person's name.
• ORDER BY is used with the SELECT statement and is usually specified after the WHERE,
HAVING, and GROUP BY clauses, if present in the query.
• Syntax: SELECT column-list
FROM table_name
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
• Example: SELECT * from emp order by ename;
• Example: SELECT * from emp order by ename DESC;
• Example: SELECT * from emp order by deptno, sal;
• Here, ASC means ascending order and DESC means descending order. If option not specify, the
SQL sort the data in ascending order.
26
A19PC1CS04 UNIT - II DBMS
4. GROUP BY clause:
• The GROUP BY clause is used in conjunction with the SELECT statement to arrange identical
data into groups.
• This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the
ORDER BY or HAVING clause (if they exist).
• It is often used with aggregate functions like SUM, COUNT, AVG, MAX, or MIN, which allows
us to perform calculations on the grouped data.
• Syntax: SELECT column_name(s)
FROM table_name
GROUP BY column_name(s);
• Group by single column:
select deptno, sum(sal) as TotalSal from emp group by deptno;
• Group by multiple column:
select deptno,job, sum(sal) as TotalSal from emp group by deptno,job;
5. HAVING clause
• HAVING clause is similar to the WHERE clause but the difference is GROUP BY filter grouped
rows instead of single rows.
• These rows are grouped together by the GROUP BY clause, so, the HAVING clause must always
be followed by the GROUP BY clause.
• It can be used with aggregate functions, whereas the WHERE clause cannot.
• Syntax: SELECT column1, column2, aggregate_function(column)
FROM table_name
GROUP BY column1, column2
HAVING condition;
• Example: select deptno, sum(sal) as TotalSal from emp group by deptno having sum(sal)>2000;
27
A19PC1CS04 UNIT - II DBMS
Set operations
• set operators are used to join the results of two (or more) SELECT statements.
• Set operators can be the part of sub queries.
• Set operators can't be used in SELECT statements containing TABLE collection expressions.
• The SET operators available in SQL are UNION, UNION ALL, INTERSECT, and EXCEPT.
• Rules to perform SET operations in SQL:
1. The number and order of columns must be the same.
2. Data types must be compatible /implicitly convertible.
UNION
• UNION will be used to combine the result of two select statements.
• Duplicate rows will be eliminated from the results obtained after performing the UNION operation.
• Syntax: SELECT column1, column2, …, column FROM table1
UNION
SELECT column1, column2, …, column FROM table2
UNION
SELECT column1, column2, …, column FROM tablen
• Example: combine the department number in emp and dept.
SQL> select deptno from emp UNION select deptno from dept;
Output: DEPTNO
----------
10
30
20
40
UNION ALL
• This operator combines all the records from both the queries.
• Duplicate rows will be not be eliminated from the results obtained after performing the UNION
ALL operation.
• Syntax: SELECT column1,column2,…,column FROM table1
UNION ALL
SELECT column1,column2,…,columnnFROM table2
• Example: select deptno from emp union all select deptno from dept;
DEPTNO 30
---------- 30
10 20
30 30
10 10
20 10
20 20
20 30
20 40
30
30 18 rows selected.
28
A19PC1CS04 UNIT - II DBMS
INTERSECT
• Using INTERSECT operator, Oracle displays the common rows from both the SELECT
statements, with no duplicates
• Syntax: SELECT column1,column2,…,column FROM table1
INTERSECT
SELECT column1,column2,…,columnnFROM table2
• Example: select deptno from emp intersect select deptno from dept;
• Output: DEPTNO
----------
10
30
20
EXCEPT OR MINUS
• It displays the rows which are present in the first query but absent in the second query with no
duplicates.
• Syntax: SELECT column1,column2,…,column FROM table1
EXCEPT
SELECT column1,column2,…,columnnFROM table2
• Example: select deptno from dept minus select deptno from emp;
• Output: DEPTNO
----------
40
29
A19PC1CS04 UNIT - II DBMS
Aggregate Operations/Functions:
• SQL aggregation function is used to perform the calculations on multiple rows of a single column of a
table and returns a single value.
• It is also used to summarize the data.
• Aggregate Functions are COUNT(), SUM(), AVG(), MIN(), and MAX().
1. COUNT ( )
• 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.
• Syntax: COUNT(*) or COUNT( [ALL|DISTINCT] expression )
• Here, Count(*): Returns total number of records in table.
Count(column): Return number of Non Null values over the column.
Count(Distinct column): Return number of distinct Non Null values over the column.
Example1: List the number of records in emp table
SQL> select count(*) from emp;
COUNT(*)
------------
14
Example2: List the number of records in mgr column
SQL> select count(mgr) from emp;
COUNT(MGR)
----------
13
Example3: List the number of records in mgr column without duplicates
SQL> select count(distinct mgr) from emp;
COUNT(DISTINCTMGR)
------------------
6
2. SUM ( )
• Sum function is used to calculate the sum of all selected columns.
• It works on numeric fields only.
• Syntax: SUM( ) or SUM( [ALL|DISTINCT] expression )
• Here, sum(column): Sum all Non Null values of Column.
sum(Distinct column): Sum of all distinct Non-Null values.
• Example1: display the total salary paid to employees.
SQL> select sum(distinct sal) from emp;
SUM(DISTINCTSAL)
----------------
24775
• Example2: display the total salary paid to employees without duplicates.
SQL> select sum(sal) from emp;
SUM(SAL)
----------
29025
30
A19PC1CS04 UNIT - II DBMS
3. AVG ( )
• The AVG function is used to calculate the average value of the numeric type.
• AVG function returns the average of all non-Null values.
• Syntax: AVG ( ) or AVG( [ALL|DISTINCT] expression )
• Example1: Find the average salary of employee.
SQL> select sum(sal),count(sal),avg(sal) from emp;
SUM(SAL) COUNT(SAL) AVG(SAL)
---------- ---------- ----------
29025 14 2073.21429
• Example2: Find the average salary of employee without duplicates.
SQL> select sum(distinct sal),count(distinct sal),avg(distinct sal) from emp;
SUM(DISTINCTSAL) COUNT(DISTINCTSAL) AVG(DISTINCTSAL)
---------------- ------------------ ----------------
24775 12 2064.58333
4. MAX ( )
31
A19PC1CS04 UNIT - II DBMS
Join Operations
• In a relational database, the data stored are all related but scattered throughout the database as multiple
tables.
• So, if there arises a need to retrieve cohesive data from multiple tables, a simple Join clause can be used.
• The Joins clause is used to combine records from two or more tables in a database.
• With a Join clause, fields from two tables can be combined by using values common to each.
• There are various types of Joins provided by SQL
1. CROSS JOIN
2. INNER JOIN
3. SELF JOIN
4. OUTER JOIN
1. CROSS JOIN:
• CROSS JOIN combines all of the possibilities of two or more tables and returns a result that
includes every row from all contributing tables.
• It's also known as CARTESIAN JOIN because it produces the Cartesian product of all linked
tables.
• The Cartesian product represents all rows present in the first table multiplied by all rows present
in the second table.
• The following visual representation of CROSS JOIN
2. INNER JOIN:
• INNER JOIN returns all records from multiple tables that satisfy the specified join condition.
• It compares each row of the first table with each row of the second table.
• If the pairs of these rows satisfy the join-predicate, they are joined together.
• An Inner Join retrieves works as intersection operation.
• This is a default join.
• The following visual representation of INNER JOIN
33
A19PC1CS04 UNIT - II DBMS
3. SELF JOIN:
• A table is joined to itself is called SELF JOIN.
• It means that each table row is combined with itself and with every other table row.
• We can do this with the help of table name aliases to assign a specific name to each table's
instance.
• The table aliases enable us to use the table's temporary name that we are going to use in the
query.
• It's a useful way to extract hierarchical data and comparing rows inside a single table.
• Syntax: SELECT T1.col_name, T2.col_name...
FROM table1 T1, table1 T2
WHERE join_condition;
ENAME MANAGER
---------- ----------
KING BLAKE
KING CLARK
KING JONES
JONES SCOTT
JONES FORD
FORD SMITH
BLAKE ALLEN
BLAKE WARD
BLAKE MARTIN
BLAKE TURNER
SCOTT ADAMS
BLAKE JAMES
CLARK MILLER
4. OUTER JOIN:
• An Outer Join retrieves all the records in two tables even if there is no counterpart row of one
table in another table, like Inner Join.
• Outer join is further divided into three subtypes: Left Outer Join, Right Outer Join and Full
Outer Join.
Left Outer Join:
• The LEFT OUTER JOIN retrieves all the records from the left table and matching rows
from the right table.
• It will return NULL when no matching record is found in the right side table.
• Since OUTER is an optional keyword, it is also known as LEFT JOIN.
• Syntax: SELECT column_lists FROM table1
LEFT [OUTER] JOIN table2 ON table1.column = table2.column;
• The below visual representation illustrates the LEFT OUTER JOIN:
34
A19PC1CS04 UNIT - II DBMS
35
A19PC1CS04 UNIT - II DBMS
Sub Queries:
• A query with in another query is called subquery/inner query/nested query.
• The result of inner query is used in execution of outer query.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
• In select statement, subquery can be used in where, from, and having clauses.
• In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to
perform the same function as ORDER BY command.
• A subquery is enclosed in parentheses.
• Syntax: SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE Condition);
• Example: Find all the employees who earn more than the average salary.
SQL> select ename,sal from emp where sal >(select avg(sal) from emp);
ENAME SAL
---------- ----------
KING 5000
BLAKE 2850
CLARK 2450
JONES 2975
SCOTT 3000
FORD 3000
Correlated Subqueries
• Correlated subqueries are used for row-by-row processing. Each subquery is executed once for every
row of the outer query.
• A correlated subquery is evaluated once for each row processed by the parent statement. The parent
statement can be a SELECT, UPDATE, or DELETE statement.
• Syntax:
SELECT column1, column2, ....
FROM table1 outer
WHERE column1 operator (SELECT column1, column2
FROM table2
WHERE expr1 = outer.expr2);
Note:
With a normal nested subquery, the inner SELECT query runs first and executes once, returning values to
be used by the main query. A correlated subquery, executes once for each candidate row considered by the
outer query. In other words, the inner query is driven by the outer query.
36
A19PC1CS04 UNIT - II DBMS
37
A19PC1CS04 UNIT - II DBMS
Views:
• Views in SQL are called of virtual tables. A view also has rows and columns as they are in a real table
in the database.
• We can create a view by selecting fields from one or more tables present in the database.
• A View can either have all the rows of a table or specific rows based on certain condition.
• We can perform creating, deleting and updating Views with some conditions.
• Sample table:
Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
STU_ID NAME MARKS AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
CREATING VIEWS
• We can create View using CREATE VIEW statement. A View can be created from a single table
or multiple tables.
• Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
• Creating View from a single table: In this example, we create a View named DetailsView from
the table Student_Detail.
Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;
• Creating View from multiple tables
In the given example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
38
A19PC1CS04 UNIT - II DBMS
DELETING VIEWS
• SQL allows us to delete an existing View.
• We can delete or drop a View using the DROP statement.
• Syntax: DROP VIEW view_name;
• For example, if we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;
UPDATING VIEWS
• There are certain conditions needed to be satisfied to update a view.
• If any one of these conditions is not met, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include GROUP BY clause
or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple tables,
then we will not be allowed to update the view.
• We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a
view. Syntax:
Uses of a View: A good database should contain views due to the given reasons:
1. Restricting data access – Views provide an additional level of table security by restricting access to a
predetermined set of rows and columns of a table.
2. Hiding data complexity – A view can hide the complexity that exists in multiple tables join.
3. Simplify commands for the user – Views allow the user to select information from multiple tables
without requiring the users to actually know how to perform a join.
4. Store complex queries – Views can be used to store complex queries.
5. Rename Columns – Views can also be used to rename the columns without affecting the base tables
provided the number of columns in view must match the number of columns specified in select
statement. Thus, renaming helps to hide the names of the columns of the base tables.
6. Multiple view facility – Different views can be created on the same table for different users.
39
A19PC1CS04 UNIT - II DBMS
PL/SQL
Pl/SQL stands for "Procedural Language extension of SQL" that is used in Oracle.
PL/SQL is a block structured language that can have multiple blocks in it.
PL/SQL includes procedural language elements like conditions and loops. It allows declaration of
constants and variables, procedures and functions, types and variable of those types and triggers. It can
support Array and handle exceptions (runtime errors).
PL/SQL is not case sensitive so you are free to use lower case letters or upper case letters except within
string and character literals.
structure of a PL/SQL block
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
S.No Sections & Description
Declarations
1 This section starts with the keyword DECLARE. It is an optional section and defines all variables,
cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It
2
consists of the executable PL/SQL statements of the program. It should have at least one executable line
of code, which may be just a NULL command to indicate that nothing should be executed.
Exception Handling
3 This section starts with the keyword EXCEPTION. This optional section contains exception(s) that
handle errors in the program.
40