0% found this document useful (0 votes)
39 views

samson dbms (R23) FULL NOTES-1_removed

The document provides an overview of SQL commands used in database management, including examples of UPDATE, DELETE, and SELECT commands. It explains the use of Data Control Language (DCL) for managing user permissions and Transaction Control Language (TCL) for handling transactions. Additionally, it covers SQL querying techniques, arithmetic and logical operations, and various SQL functions for data manipulation.

Uploaded by

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

samson dbms (R23) FULL NOTES-1_removed

The document provides an overview of SQL commands used in database management, including examples of UPDATE, DELETE, and SELECT commands. It explains the use of Data Control Language (DCL) for managing user permissions and Transaction Control Language (TCL) for handling transactions. Additionally, it covers SQL querying techniques, arithmetic and logical operations, and various SQL functions for data manipulation.

Uploaded by

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

Database Management System (R23) B.

Tech (CSE) II Year II Semester

Example:Change the age of teacher to 45 whose id=3;


SQL> UPDATE teacher SET age=45 where id=3;

Example: C hange the name of teacher to ‘ARJUN RAO’ whose name is ‘A.RAO’
SQL> UPDATE teacher SET name=’ARJUN RAO’ where name=’A.RAO’;

DELETE COMMAND:

DELETE command is used to delete a specific single record or group of records or all records
based on the given condition in WHERE clause. It is DML command.
It delete the records temporarily from the table. We can rollback the deleted records before
COMMIT command.

Syntax:
DELETE from tablename where condition;
Example: Delete a teacher record whose id=3;
SQL> DELETE from teacher where id=3;
Example: Delete a teacher record whose name is ‘B.RAO’
SQL>DELETE from teacher where name=’B.RAO’;

Example:Delete a teacher record whose age is 60


SQL>DELETE from teacher where age=60;

DQL (Data Query Language)


DQL command is SELECT that is used to display records of the table.
Syntax for simple SELECT:
SELECT Column_Name1, Column_Name2, ....., Column_NameN FROM Table_Name;
In this SELECT syntax, Column_Name1, Column_Name2, ….., Column_NameN are the name
of those columns in the table whose data we want to read.

If you want to access all rows from all fields of the table, use the following SELECT syntax with
* asterisk sign:

SELECT * FROM Table_Name;


Example: Query to display all records of a table ‘STUDENT’
SQL> SELECT * FROM STUDENT;
Example: Query to display only ROLLNO & STNAME columns of a table ‘STUDENT’
SQL> SELECT ROLLNO, NAME FROM STUDENT;

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 54


Database Management System (R23) B.Tech (CSE) II Year II Semester

DCL(Data Control Language)


DCL includes commands deal with the rights, permissions and other controls of the database
system. These are GRANT and REVOKE commands.

GRANT-gives user’s access privileges to the database.


Example: Query to grant delete permission to manager on Bank table.
SQL>GRANT DELETE ON BANK TO MANAGER;

REVOKE-withdraw user’s access privileges given by using the GRANT command.


SQL>REVOKE DELETE ON BANK FROM MANAGER;

TCL(Transaction Control Language)


TCL commands deal with the transaction within the database.

COMMIT– commits a Transaction.


Example: SQL> COMMIT;

ROLLBACK– rollbacks a transaction in case of any error occurs.


Example: SQL> ROLLBACK;

SAVEPOINT–sets a savepoint within a transaction.


Example: SQL> SAVEPOINT A;
The above set a label ‘A’ for transaction at particular point.

Suppose if we want rollback till savepoint A:


SQL> ROLLBACK TO SAVE POINT A;
Where A is savepoint label.

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 55


Database Management System (R23) B.Tech (CSE) II Year II Semester

UNIT 3
SQL:Basic SQL querying (select and project) using where clause, arithmetic & logical
operations, SQL functions(Date and Time, Numeric, String conversion).Creating tables with
relationship, implementation of key and integrity constraints, nested queries, sub queries,
grouping, aggregation, ordering, implementation of different types of joins, view(updatable and
non-updatable), relational set operations.

3.1. SQL querying (select and project) using where clause


SQL Querying:
The SELECT command is the DQL (Data Query Language) command, that is used to
select/project records of the table.
SELECT can be used for
a) selection
b) projection

a. Selection:
Selection is used to filter rows based on specific conditions.
Selection of rows by using SELECT and WHERE clauses.
Syntax:
SELECT * FROM table_name WHERE condition;
The * operator indicates all columns in a row.
Consider the following table “TEACHER”
Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20
Example1: Query to display teachers whose age is greaterthan or equal to 40 years
SQL>SELECT * from teacher where age>=40;
Output:
Id Name Age
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 56


Database Management System (R23) B.Tech (CSE) II Year II Semester

Example2: Query to display teachers whose age is below 40 years


SQL>SELECT * from teacher where age<40;
Output:
Id Name Age
1 ANAND RAO 30
5 ANAND KRISHNA 20

b. Projection:
Projection is used to select specific columns for display.
Projection of particular columns by using SELECT and WHERE clauses.
Syntax:
SELECT c1,c2,c3.. FROM table_name WHERE condition;
The c1,c2,c3.. are the columns names to display.
Consider the following table “TEACHER”
Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20
Example1: Query to display names of the teachers whose age is greater than or equal to 40 years
SQL> SELECT name from teacher where age>=40;
Output:
Name
RAMA RAO
CHANDRA RAO
DURGA RAO

Example2: Query to display Name and ages of teachers whose age is below 40 years
SQL> SELECT name, age from teacher where age<40;
Output:
Name Age
ANAND RAO 30
ANAND KRISHNA 20

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 57


Database Management System (R23) B.Tech (CSE) II Year II Semester

3.2. Arithmetic & logical operations


Operators are useful to perform the operation. These are unary or Binary operator.
Types of Operator
SQL operators are categorized in the following categories:
• SQL Arithmetic Operators(+, - ,* ,/ )
• SQL Comparison or Relational Operators(< , > , !=, = , >=, <=)
• SQL Logical Operators(AND, OR, NOT)
• SQL Set Operators(Union, Union all, Intersect, Minus)

Examples:
SQL>Select sal+1000 from emp;
Ans: all salaries with addition of 1000

Examples:
Select * from EMP where sal>=5000;
Ans: all salaries greater than or equal to 5000

3.3. SQL | WHERE Clause


WHERE keyword is used for fetching filtered data in a result set. It is used to fetch data
according to particular criteria.
WHERE keyword can also be used to filter data by matching patterns.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name operator value;

Operator can be any relational operator (< , > , !=, = , >=, <=,<>)

Consider the following table “TEACHER”


Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 58


Database Management System (R23) B.Tech (CSE) II Year II Semester

Example1: Query to display teachers whose age is greaterthan or equal to 40 years


SQL>SELECT * from teacher where age>=40;
Output:
Id Name Age
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60

Example2: Query to display teachers whose age is greater than 40 and less than 60 years
SQL>SELECT * from teacher where age>40 AND age<60;
Output:
Id Name Age
3 CHANDRA RAO 50

Additional operators with Where Clause


 BETWEEN In an inclusive Range
 LIKE Search for a pattern
 IN To specify multiple possible values for a column
BETWEEN:
WHERE clause with BETWEEN Operator
It is used to fetch filtered data in a given range inclusive of two values.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name BETWEEN value1
AND value2;
Consider the following table “TEACHER”
Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20
Example1: Query to display teachers whose age is between 30 and 50 years
SQL>SELECT * from teacher where age BETWEEN 30 AND 50;
Output:
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 59


Database Management System (R23) B.Tech (CSE) II Year II Semester

LIKE:
Where Clause with LIKE Operator
It is used to fetch filtered data by searching for a particular pattern in the where clause.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern;

Pattern is exact value extracted from the pattern to get related data in the result set.
Note: The character(s) in the pattern is case-insensitive.
To fetch records of Teachers where Name starts with the letter S. Query:

Consider the following table “TEACHER”


Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20

Example1: Query to display Teachers where Name starts with the letter A.
SQL>SELECT * from teacher where Name LIKE 'A%';
The ‘%'(wildcard) signifies the later characters here which can be of any length.

Output:
Id Name Age
1 ANAND RAO 30
5 ANAND KRISHNA 20

Example2: Query to display Teachers where Name contains the pattern ‘N’.
SQL> SELECT * from teacher where Name LIKE '%N%';
Output:
Id Name Age
1 ANAND RAO 30
3 CHANDRA RAO 50
5 ANAND KRISHNA 20

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 60


Database Management System (R23) B.Tech (CSE) II Year II Semester

IN:
Where Clause with IN Operator, it is used to fetch the filtered data same as fetched by ‘=’
operator just the difference is that here we can specify multiple values for which we can get the
result set.
Syntax:
SELECT column1, column2 FROM table_name WHERE column_name IN (value1, value2,..);
value1, value2,..: exact value matching the values given and get related data in the result set.

Consider the following table “TEACHER”


Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20
Example1: Query to To fetch the Names of Teachers where Age is 20 or 50.
SQL>SELECT name,age from teacher where age in(20,50);
Output:
Id Name Age
3 CHANDRA RAO 50
5 ANAND KRISHNA 20

3.4. SQL Functions


Functions are methods used to perform data operations. SQL has many in-built functions used to
perform string concatenations, mathematical calculations etc.
SQL functions are categorized into the following two categories:
1. Scalar Functions
2. Aggregate Functions

1. Scalar Functions:
The Scalar Functions in SQL are used to return a single value from the given input value. Each
record is operated independently by the function.
Types of Functions:
a. Numeric Functions
b. String Functions
c. Date & Time Functions
d. Conversion Functions

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 61


Database Management System (R23) B.Tech (CSE) II Year II Semester

Numeric Functions:
These functions take number type values or columns parameters
Function Value Returned
ABS ( m ) Absolute value of m
MOD ( m, n ) Remainder of m divided by n
POWER ( m, n ) m raised to the nth power
ROUND ( m , n ) m rounded to the nth decimal place
TRUNC ( m, n ) m truncated to the nth decimal place
SQRT ( n ) positive square root of n
EXP ( n ) e raised to the power n
LN ( n ) natural logarithm of n
LOG ( n2, n1 ) logarithm of n1, base n2
CEIL ( n ) smallest integer greater than or equal to n
FLOOR ( n ) greatest integer smaller than or equal to n

Examples:
SQL> select ABS(-65) from dual;
Ans:65
SQL>select CEIL(18.2) from dual;
Ans: 19
SQL>select FLOOR(18.2) from dual;
Ans:18
SQL>select POWER(10,2) from dual;
Ans:100
SQL>select SQRT(16) from dual;
Ans:4

STRING Functions
These functions take string type values or columns parameters

Function Value Returned


INITCAP ( s ) First letter of each word is changed to uppercase and all other
letters are in lower case.
LOWER ( s ) All letters are changed to lowercase.
UPPER ( s ) All letters are changed to uppercase.
CONCAT ( s1, s2 ) Concatenation of s1 and s2.
LTRIM ( s , set] ) Returns s with characters removed up to the first character not in
set; defaults to space
RTRIM ( s , set ) Returns s with final characters removed after the last character
not in set; defaults to space

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 62


Database Management System (R23) B.Tech (CSE) II Year II Semester

REPLACE ( s, s1,s2 ) Returns s with every occurrence of s1 in s replaced by s2 ;


default removes s1
SUBSTR ( s, m , n ) Returns a substring from s, beginning in position m and n
characters long; default returns to end of s.
LENGTH ( s ) Returns the number of characters in s.
CHR(n) Returns the character which is equal to ASCII n value

Examples:
SQL> select CONCAT('Tamota','soup') "Dinner" from dual;
Ans: Tamotasoup

SQL> select RTRIM(‘JNTUK ’), LTRIM(‘ UNIVERSITY’) FROM DUAL;


Ans: JNTUKUNIVERSITY

SQL> select REPLACE('This and That','Th','B') from dual;


Ans: Bis and Bat

SQL> select TRANSLATE('abcdefghij','abcdef','123456') from dual;


Ans:123456ghij

Using String Functions on Database Tables:


Consider the following table “TEACHER”
Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20

Example1: Query to display names of Teachers in InitCap letter


SQL> select initcap(name) from teacher;
Ouput:
Id Name Age
1 Anand Rao 30
2 Rama Rao 40
3 Chandra Rao 50
4 Durga Rao 60
5 Anand Krishna 20

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 63


Database Management System (R23) B.Tech (CSE) II Year II Semester

Example2: Query to display all names of Teachers in lower case letters


SQL> select lower(name) from teacher;
Ouput:
Id Name Age
1 anand rao 30
2 rama rao 40
3 chandra rao 50
4 durga rao 60
5 anand krishna 20

Example3: Query to display all names and length of the names of Teachers
SQL> select name, length(name) from teacher;
Ouput:
Id Name Length(name)
1 ANAND RAO 9
2 RAMA RAO 8
3 CHANDRA RAO 11
4 DURGA RAO 9
5 ANAND KRISHNA 13

Date and Time Functions


These functions take date or time type values or columns parameters

Function Value Returned


ADD_MONTHS ( d, n ) Date d plus n months
LAST_DAY ( d ) Date of the last day of the month containing date d.
MONTHS_BETWEEN ( d, e ) Number of months by which e precedes date d
NEXT_DAY ( d, day ) Date of the first day of the week after date d
SYSDATE Current date and time
GREATEST ( d1, d2, ..., dn ) Latest of the given dates
LEAST ( d1, d2, ..., dn ) Earliest of the given dates
Examples:
SQL>select SYSDATE from dual;
Ans: 26-02-2025
SQL>select ADD_MONTHS(sysdate, 4) from dual ;
Ans: 26-06-2025
SQL>select MONTHS_BETWEEN('05-jan-99','05-jan-98') from dual;
Ans: 12

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 64


Database Management System (R23) B.Tech (CSE) II Year II Semester

Conversion Functions
Function Input Argument Value Returned
TO_CHAR ( m [, fmt ] ) m = numeric value, fmt = Number m converted to
format character string as specified by
the format
TO_NUMBER ( s [, fmt ] ) s = character string, fmt = Character string s converted to
format a number as specified by the
format
TO_DATE ( s [, fmt ] ) s = character string, fmt = String s converted to a date
format for date value

Examples:
SQL> select SYSDATE, TO_CHAR(SYSDATE,'DAY') from dual;
Ans: Monday (if the sysdate is 09-05-2022)
SQL> Select TO_CHAR(sysdate, 'yyyy/mm/dd') from dual;
Ans: ‘2022/05/09’ if the sysdate is 09/05/2022
SQL> Select TO_CHAR(sysdate, 'Month DD, YYYY') from dual;
Ans: ‘May 05,2022 if the sysdate is 09/05/2022
SQL> SELECT TO_DATE('09-05-2022', 'DD-MM-YYYY') FROM DUAL;
Converts ‘09-05-2022’ i.e string into Date type

2. Aggregate Functions

Aggregate Functions are all about

Performing calculations on multiple rows of a single column of a table and returning a single
value.The commonly used aggregated functions are

 SUM – calculates the sum of values


 AVG – calculates the average of a set of values.
 COUNT – counts rows in a specified table or view.
 MIN – gets the minimum value in a set of values.
 MAX – gets the maximum value in a set of values.

Consider the following table: EMP TABLE


EMPNO ENAME JOB SAL DEPTNO
7369 SMITH CLERK 800 20
7499 ALLEN SALESMAN 1600 30
7521 WARD SALESMAN 1250 30

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 65


Database Management System (R23) B.Tech (CSE) II Year II Semester

7566 JONES MANAGER 2975 20


7654 MARTIN SALESMAN 1250 30
7698 BLAKE MANAGER 2850 30
7782 CLARK MANAGER 2450 10
7788 SCOTT ANALYST 3000 20
7839 KING PRESIDENT 5000 10
7844 TURNER SALESMAN 10000 30
7876 ADEMS CLERK 1100 20
7900 JAMES CLERK 950 30
7902 FORD ANALYST 3000 20
7934 MILLER CLERK 1300 10
Example1: Write a query to display count of Enames in the table ‘EMP’:
SQL> SELECT COUNT(ENAME) FROM EMP;
Ans: 14
Example2: Write a query to display TOTAL salary of all employees in the table ‘EMP’:
SQL> SELECT SUM(SAL) FROM EMP;
Ans: 37525
Example3: Write a query to display maximum of salary in the table ‘EMP’:
SQL> SELECT MAX(SAL) FROM EMP;
Ans: 10000
Example4: Write a query to display average salary from DEPTNO is 20 in the table ‘EMP’
SQL> SELECT AVG(SAL) FROM EMP WHERE DEPTNO=20;
Ans: 2175

3.5. GROUP BY , HAVING and ORDER BY clauses


GROUP BY
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of
some functions. i.e if a particular column has same values in different rows then it will arrange
these rows in a group.
Important Points:
• GROUP BY clause is used with the SELECT statement.
• In the query, GROUP BY clause is placed after the WHERE clause.
• In the query, GROUP BY clause is placed before ORDER BY clause if used any.
Syntax: SELECT column1, function_name(column2) FROM table_name WHERE condition
GROUP BY column1, column2 ORDER BY column1, column2;

Function_name: Name of the function used for example, SUM() , AVG().


table_name: Name of the table.
condition: Condition used.

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 66


Database Management System (R23) B.Tech (CSE) II Year II Semester

HAVING Clause
We can use HAVING clause to place conditions to decide which group will be the part of final
result-set. Also we can not use the aggregate functions like SUM(), COUNT() etc. with
WHERE clause. So we have to use HAVING clause if we want to use any of these functions in
the conditions
Syntax:
SELECT column1, function_name(column2)
FROM table_name WHERE condition
GROUP BY column1, column2 HAVING condition ORDER BY column1, column2;

Example5: Write a query to display department wise total salary of employees in the table
‘EMP’
SQL> SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO;
Output:

DEPTNO SUM(SAL)
10 8750
20 10875
30 17900

Example6: Write a query to display department wise total salary of employees which department
wise sum is >10000 in the table ‘EMP’
SQL> SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO HAVING
SUM(SAL)>10000;
Output:

DEPTNO SUM(SAL)
20 10875
30 17900

ORDER BY:
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or
descending according to one or more columns.
• By default ORDER BY sorts the data in ascending order.
• We can use the keyword DESC to sort the data in descending order and the keyword
ASC to sort in ascending order.
Syntax of all ways of using ORDER BY is shown below:
• Sort according to one column: To sort in ascending or descending order we can use the
keywords ASC or DESC respectively.

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 67


Database Management System (R23) B.Tech (CSE) II Year II Semester

Syntax:
SELECT * FROM table_name ORDER BY column_name ASC|DESC

Sort according to multiple columns: To sort in ascending or descending order we can use the
keywords ASC or DESC respectively. To sort according to multiple columns, separate the names
of columns by (,) operator.
Syntax:
SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2 ASC|DESC

Consider the following table:


Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20
Example1: Query to sort teachers in Ascending order of Names
SQL> select * from Teacher order by Name;
Id Name Age
5 ANAND KRISHNA 20
1 ANAND RAO 30
3 CHANDRA RAO 50
4 DURGA RAO 60
2 RAMA RAO 40

Example2: Query to sort teachers in descending order of Ages


SQL> select * from Teacher order by Age Desc;
Id Name Age
4 DURGA RAO 60
3 CHANDRA RAO 50
2 RAMA RAO 40
1 ANAND RAO 30
ANAND
5 20
KRISHNA

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 68


Database Management System (R23) B.Tech (CSE) II Year II Semester

3.6. Creating tables with relationship


The user has to do the following to set relationship between two tables (one is Parent table and
second is Child table)
Parent table: Parent table is the table on which the child data is dependent. It should have a
Primary key column.
Example: Create dept table as parent table, in this deptno is the primary key attribute.
create table dept
( deptno number(2) primary key,
dname varchar2(10) not null,
loc varchar2(8));

Child Table: Child table is the table, the data of this table should references to the column in
parent table..
It should have same column name of the parent table.
The child table maintains a foreign key on the same column of the parent table.

Example: Create emp table as child table, in this deptno is the foreign key attribute.
create table emp
( empno number(5) primary key,
ename varchar2(10) not null,
sal number(7,2),
deptno number(2),
foreign key(deptno) references dept);

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 69


Database Management System (R23) B.Tech (CSE) II Year II Semester

3.7. Implementation of Integrity Constraints:

Constraints: You can place constraints to limit the type of data that can go into a table.
Common types of constraints include the following:
 UNIQUE Constraint : Ensures that all values in a column are distinct.
 NOT NULL Constraint : Ensures that a column cannot have NULL value.
 CHECK Constraint : Makes sure that all values in a column satisfy certain criteria.
 PRIMARY KEY Constraint : Ensures that all values in a column are distinct and a
Column can’t have NULL value.
 FOREIGN KEY Constraint : Used to ensure referential integrity of the data.

UNIQUE Constraint:-
SQL> CREATE TABLE Customer
(SID integer Unique,
First_Name varchar2(30),
Last_Name varchar2(30));
SID FIRST_NAME LAST_NAME
1212 RAJENDRA PRASAD
1201 PURNA CHANDRARAO
1215 LITHEN KUMAR
1242 DIVYA SREE
1243 BHAVYA SREE
1238 SUDHEER BABU

Executing the following SQL statement,


SQL> INSERT INTO Customer values ('1242','Reshma','Lee');

It will result in an error because '1242' already exists in the SID column, thus trying to insert
another row with that value violates the UNIQUE constraint.

NOT NULL Constraint:-


SQL>CREATE TABLE Customer2
(SID integer NOT NULL,
Last_Name varchar (30) NOT NULL,
First_Name varchar (30));

Executing the following SQL statement,


SQL> INSERT INTO Customer2(Last_name,First_name) values (‘Rama’ , ‘Rao’);
It will result in an error

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 70


Database Management System (R23) B.Tech (CSE) II Year II Semester

Check Constraint:-
SQL> create table emp (empno number(5) ,ename varchar2(10) sal number(7,2) check(sal>=500
and sal<=10000));
Executing the following SQL statement,
SQL> INSERT INTO emp values (100, ‘Rama’ , 20000);
It will result in an error

Primary key and Foreign key Constraint: -


SQL> create table dept (deptno number(4) primary key,
dname varchar2(10) );
SQL> insert into dept values(10,'accounting’);
1 row created.
SQL> insert into dept values(20,'research’);
1 row created.
SQL> select * from dept;
Deptno dname
10 Accounting
20 Research

SQL> create table emp (empno number(5) primary key,


ename varchar2(10),sal number(7,2) ,
deptno number(2),
foreign key(deptno) references dept);
SQL> insert into emp values(7369,'smith‘,800,20);
1 row created.
SQL> insert into emp values (7499,'allen‘,300,30);
Deptno 30 violates the constraint and give an error.

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 71


Database Management System (R23) B.Tech (CSE) II Year II Semester

3.8. Nested Query(Sub Query):


A query in other query is called as Nested query. In other words we can say that a Sub query is a
query that is embedded in WHERE clause of another SQL query.

 A subquery is a query within another query. The outer query is called as main query and
inner query is called as subquery.
 The subquery generally executes first, and its output is used to complete the query
condition for the main or outer query.
 Subquery must be enclosed in parentheses.
 A sub query is typically appears within the where clause of a query.

Syntax:
SELECT column_name FROM table_name WHERE column_name
expression_operator ( SELECT COLUMN_NAME from TABLE_NAME
WHERE ……... );

Example: Find the names of sailors who have reserved at least one boat.

NESTED SUB QUERY:


A subquery can be nested inside other subqueries. SQL has an ability to nest queries within one
another. A subquery is a SELECT statement that is nested within another SELECT statement and
which return intermediate results. SQL executes innermost subquery first, then next level.

Example: Find the names of sailors who have reserved a red or green boat.

Select s.sid, s.sname from sailors s where s.sid in


(select r.sid from reserves r where r.bid in
(select b.bid from Boats b where b.color=’green’ or b.color=’red’));

CORRELATED QUERY –
In Correlated Query, Outer query executes first and for every Outer query row Inner query is
executed. Hence, Inner query uses values from Outer query.
Example –
Orders (OrderID, CustomerID, OrderDate);
Customers (CustomerID, CustomerName, ContactName, Country);

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 72


Database Management System (R23) B.Tech (CSE) II Year II Semester

Find details of customers who have ordered.


SELECT CustomerName
FROM Customers
WHERE EXISTS (SELECT CustomerID
FROM Orders
WHERE Orders.CustomerID= Customers.CustomerID);

3.9. implementation of different types of joins

A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records
from the right table
 RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
 FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 73


Database Management System (R23) B.Tech (CSE) II Year II Semester

Examples:
Consider the following two student tables:
OFFICE EXAM-SECTION
ROLLNO TUTIONFEE_DUE ROLLNO EXAMFEE_DUE
501 50000 501 500
502 80000 502 800
503 30000 504 300
505 20000 506 200

Inner join

Example: The query displays all students who have both Tution and Exam Fees due
employees with their working department name:
SELECT O.ROLLNO, O.TUTIONFEE_DUE, E.EXMFEE_DUE FROM OFFICE O
INNER JOIN EXAM-SECTION E ON O.ROLLNO=E,ROLLNO;

ROLLNO TUTIONFEE_DUE EXAMFEE_DUE


501 50000 500
502 80000 800

Left Outer joins


Example: The query displays all students from OFFICE table having TUTIONFEE_DUE
and students having both TUTIONFEE_DUE & EXAMFEE_DUE :

SELECT O.ROLLNO, O.TUTIONFEE_DUE, E.EXMFEE_DUE FROM OFFICE O


LEFT OUTER JOIN EXAM-SECTION E ON O.ROLLNO E.ROLLNO;
ROLLNO TUTIONFEE_DUE EXAMFEE_DUE
501 50000 500
502 80000 800
503 30000
505 20000

Rollnos 503 & 505 only have TutionFee_due but not ExamFee_due.

Right Outer joins


Example: The query displays all students from EXAM_SECTION table having
EXAMFEE_DUE and students having both TUTIONFEE_DUE & EXAMFEE_DUE :

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 74


Database Management System (R23) B.Tech (CSE) II Year II Semester

SELECT O.ROLLNO, O.TUTIONFEE_DUE, E.EXMFEE_DUE FROM OFFICE O


RIGHT OUTER JOIN EXAM-SECTION E ON O.ROLLNO E.ROLLNO;
ROLLNO TUTIONFEE_DUE EXAMFEE_DUE
501 50000 500
502 80000 800
504 300
506 200

Full Outer joins


Example: The query displays all students from EXAM_SECTION table having
EXAMFEE_DUE and all students from OFFICE table and students having both
TUTIONFEE_DUE & EXAMFEE_DUE :

SELECT O.ROLLNO, O.TUTIONFEE_DUE, E.EXMFEE_DUE FROM OFFICE O


FULL OUTER JOIN EXAM-SECTION E ON O.ROLLNO E.ROLLNO;
ROLLNO TUTIONFEE_DUE EXAMFEE_DUE
501 50000 500
502 80000 800
503 30000
504 300
505 20000
506 200

Self join
A table can join with the same table. One table can be assumed as two tables by using the
alias names and then perform the join operations on rows.

Example: The following query displays the students details whose DUE is lessthan other

SELECT S1.ROLNO, S1.TUTIONFEE_DUE , S2.ROLNO, S2.TUTIONFEE_DUE


E.EXMFEE_DUE FROM OFFICE S1, OFFICE S2 WHERE S1.TUTIONFEE_DUE<
S2.TUTIONFEE_DUE;
ROLLNO TUTIONFEE_DUE ROLLNO TUTIONFEE_DUE
501 50000 502 80000
503 30000 501 50000
503 30000 502 80000
505 20000 503 30000
505 20000 501 50000
505 20000 502 80000

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 75


Database Management System (R23) B.Tech (CSE) II Year II Semester

3.10. View (updatable and non-updatable)

Views in SQL are a type of virtual table that simplifies how users interact with data across one
or more tables. Unlike traditional tables, a view in SQL does not store data on disk; instead, it
dynamically retrieves data based on a pre-defined query each time it’s accessed.
We can create a 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;
Updatable views
Updatable views can be modified using INSERT, UPDATE, or DELETE statements, while
non-updatable views cannot.
Updatable views
Can contain both updatable and non-updatable columns
Have a one-to-one relationship between the rows in the view and the rows in the underlying
table
Can be used in statements such as UPDATE, DELETE, or INSERT to update the contents of
the underlying table
Non-updatable views
Cannot be modified using INSERT, UPDATE, or DELETE statements
Contain constructs such as aggregate functions, window functions, DISTINCT, GROUP BY,
HAVING, UNION or UNION ALL, or a subquery in the select list
Consider the following table “TEACHER”
Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20

Teachers whose age >= 50;


Example: Query to create view on TEACHER table which is used to view the teachers who
have more than 50 years:

SQL> create view TEACHERVIEW on TACHER where AGE >=50;


To See View:
SQL> select * from TEACHERVIEW;

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 76


Database Management System (R23) B.Tech (CSE) II Year II Semester

OUTPUT:
Id Name Age
3 CHANDRA RAO 50
4 DURGA RAO 60

3.11. Set Operations:


Union, Intersect, and Except (SET operators)
The SQL Set operation is used to combine the two or more SQL SELECT statements.
They are useful when you need to combine the results from separate queries into one single
result.
They differ from a join in that entire rows are matched and, as a result, included or excluded
from the combined result.
The UNION, INTERSECT, and EXCEPT are the set operations.

Table: TEACHER1 Table: TEACHER2


Id Name Age Name Age
1 ANAND RAO 30 4 DURGA RAO 60
2 RAMA RAO 40 5 ANAND KRISHNA 20
3 CHANDRA RAO 50 6. RAMA RAO 40

UNION Operator
The Union operator returns rows from both tables. If used by itself, UNION returns a distinct
list of rows.
Using UNION ALL, returns all rows from both tables.
A UNION is useful when you want to sort results from two separate queries as one combined
result.
For instance if you have two tables, Teacher1 & Teacher2
Example: query to display name of teachers from both tables
SQL> select name from Teacher1 UNION select name from Teacher2;

Name
ANAND RAO
RAMA RAO
CHANDRA RAO
DURGA RAO
ANAND KRISHNA
DURGA RAO
ANAND KRISHNA

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 77


Database Management System (R23) B.Tech (CSE) II Year II Semester

INTERSECT Operator
Use an intersect operator to returns rows that are in common between two tables; it returns
unique rows from both the left and right query.
This query is useful when you want to find results that are in common between two queries.
Continuing with Vendors, and Customers, suppose you want to find vendors that are also
customers. You can do so easily using:

SQL> select name from Teacher1 INTERSECT select name from Teacher2;
Name
RAMA RAO

EXCEPT Operator
Use the EXCEPT Operator to return only rows found in the left query.
It returns unique rows from the left query that aren’t in the right query’s results.
This is similar to MINUS command in other sql softwares. This query is useful when you’re
looking to find rows that are in one set but not another.
For example, to create a list of all Teachers that are in Teacher1 table but not in Teachers table:

SQL> select name from Teacher1 EXCEPT select name from Teacher2;
Table: TEACHER1
Id Name Age
1 ANAND RAO 30
3 CHANDRA RAO 50

EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a subquery.

The EXISTS operator returns TRUE if the subquery returns one or more records.

Example: The following query display the Sailors who reserves at least one boat.

SELECT * FROM SAILOR S


WHERE EXISTS ( SELECT SID FROM RESERVES);

Prepared by Ch Samsonu, Associate Professor, CSE Dept,, KHIT, Guntur 78

You might also like