DBMS Notes - UNIT 3
DBMS Notes - UNIT 3
UNIT III
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
Examples:
Select sal+1000 from emp;
Ans: all salaries with addition of 1000
Select * from EMP where sal>=5000;
SQL Functions
Functions are methods used to perform data operations. SQL has many in-built functions used to
perform string concatenations, mathematical calculations etc.
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:
1)Numeric Functions
2)String Functions
3)Date & Time Functions
4)Conversion Functions
[email protected]
lOMoARcPSD|45012165
Numberic Functions
Examples:
select ABS(-65) from dual;
Ans:65
select CEIL(18.2) from dual;
Ans: 19
select FLOOR(18.2) from dual;
Ans:18
select POWER(10,2) from dual;
Ans:100
select SQRT(16) from dual;
Ans:4
STRING Functions
[email protected]
lOMoARcPSD|45012165
Examples:
select CHR(37) , CHR(100), CHR(101) from dual;
select CONCAT('Tamota','soup') "Dinner" from dual;
Ans: Tamotasoup
select RPAD(name,5,'$') from student;
select RTRIM(‘JNTUK ’), LTRIM(‘ UNIVERSITY’) FROM DUAL;
Ans: JNTUKUNIVERSITY
select REPLACE('This and That','Th','B')"First" from dual;
Ans: Bis and Bat
select TRANSLATE('abcdefghij','abcdef','123456') from dual;
Ans:123456ghij
[email protected]
lOMoARcPSD|45012165
Examples:
select SYSDATE, TO_CHAR(SYSDATE,'DAY') from dual;
Ans: Monday (if the sysdate is 09-05-2022)
Select TO_CHAR(sysdate, 'yyyy/mm/dd') from dual;
Ans: ‘2022/05/09’ if the sysdate is 09/05/2022
Select TO_CHAR(sysdate, 'Month DD, YYYY') from dual;
Ans: ‘May 05,2022 if the sysdate is 09/05/2022
SELECT TO_DATE('09-05-2022', 'DD-MM-YYYY') FROM DUAL;
Converts ‘09-05-2022’ i.e string into Date type
SELECT TO_DATE('1999-JAN-05', 'YYYY-MON-DD') FROM DUAL;
AGGREGATE FUNCTIONS
In database management an aggregate function is a function where the values of multiple rows
are grouped together as input on certain criteria to form a single value of more significant
meaning.
The following are the most commonly used SQL aggregate functions:
• 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.
• SUM – calculates the sum of values.
Exampes:
select sum(sal) from emp;
select max(sal) from emp where job='salesman';
select min(sal) from emp;
select avg(sal),count(*) from emp where deptno=20;
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));
[email protected]
lOMoARcPSD|45012165
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);
[email protected]
lOMoARcPSD|45012165
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.
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
[email protected]
lOMoARcPSD|45012165
1 row created.
SQL> select * from dept;
Deptno dname
10 Accounting
20 Research
• 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.
[email protected]
lOMoARcPSD|45012165
Example: Find the names of sailors who have reserved a red or green boat.
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);
Find details of customers who have ordered.
SELECT CustomerName
FROM Customers
WHERE EXISTS (SELECT CustomerID
FROM Orders
WHERE Orders.CustomerID= Customers.CustomerID);
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example:
1. The Following shows the employee table in ascending order on Ename column
Select * from Emp order by Ename;
2. The Following shows the employee table in descending order on Ename column
Select * from Emp order by Ename DESC;
[email protected]
lOMoARcPSD|45012165
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.
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;
Examples:
SET OPERATIONS:
Union, Intersect, and Except (SET operators)
The SQL Set operation is used to combine the two or more SQL SELECT statements.
[email protected]
lOMoARcPSD|45012165
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.
The other set operations are ANY, ALL, IN, NOT IN, EXISTS, NOT EXISTS.
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, Vendor, and Customer, and you want a combined list of
names, you can easily do so using:
SELECT ‘Vendor’, V.Name
FROM Vendor V
UNION
SELECT ‘Customer’, C.Name
FROM Customer C
ORDER BY Name;
[email protected]
lOMoARcPSD|45012165
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:
SELECT V.Name
FROM Vendor V
INTERSECT
SELECT C.Name
FROM Customer C
ORDER BY Name
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 vendors that are not customers you could write:
SELECT V.Name
FROM Vendor V
EXCEPT
SELECT C.Name
FROM Customer C
ORDER BY Name
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.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Example: The following query display the Sailors who reserves at least one boat.
[email protected]
lOMoARcPSD|45012165
ANY Operator
The ANY operator returns a boolean value as a result
returns TRUE if ANY of the subquery values meet the condition
ANY means that the condition will be true if the operation is true for any of the values in the
range.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Example: The following query display the employees whose salary is lessthan ‘SALESMAN’
SELECT * FROM EMP E
WHERE E.SAL > ANY ( SELECT E2.SAL FROM EMP E2
WHERE E1.SAL>E2.SAL AND E2.JOB=’SALESMAN’);
ALL Operator
The ALL operator
• returns a boolean value as a result
• returns TRUE if ALL of the subquery values meet the condition is used with SELECT,
WHERE and HAVING statements
ALL means that the condition will be true only if the operation is true for all values in the range.
Example: The following query display the employees whose salary is lessthan ‘SALESMAN’
SELECT * FROM EMP E
WHERE E.SAL > ALL ( SELECT E2.SAL FROM EMP E2
WHERE E1.SAL>E2.SAL AND E2.JOB=’SALESMAN’);
[email protected]
lOMoARcPSD|45012165
IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Example: The following query display the employees whose job is clerk or analyst
SELECT * FROM EMP WHERE JOB IN (‘CLERK’, ‘ANALYST’);
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
• (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
[email protected]
lOMoARcPSD|45012165
Examples:
Inner join
Example: The query displays all employees with their working department name:
SELECT E.ENAME,E.SAL,D.DNAME FROM EMP E
INNER JOIN DEPT D ON E.DEPTNO=D.DEPTNO;
[email protected]
lOMoARcPSD|45012165
Example: The query displays all employees with their working department name and
additionally Department nameOPERATIONS without any employee:
[email protected]
lOMoARcPSD|45012165
Equi join
select e.ename,e.job,e.sal,d.dname from emp e,dept d where e.deptno=d.deptno;
Self join
A table can join with the same table. We can join using the alias names
Example: The following query displays the department details whose deptNo is lessthan
other deptNos.
SELECT D1.DNAME,D1.LOC,D2.DEPTNO FROM DEPT D1, DEPT D2
WHERE D1.DEPTNO< D2.DEPTNO;
[email protected]
lOMoARcPSD|45012165
Triggers
Triggers are the SQL statements that are automatically executed when there is any change
in the database. The triggers are executed in response to certain events (INSERT, UPDATE
or DELETE) in a particular table. These triggers help in maintaining the integrity of the data
by changing the data of the database in a systematic fashion.
A database that has a set of associated triggers is called an active database. A trigger
description contains three parts:
Action: A procedure that is executed when the trigger is activated and its condition is true.
Syntax
(before | after)
on [table_name]
[trigger_body]
1. CREATE TRIGGER: These two keywords specify that a triggered block is going to be
declared.
3. BEFORE | AFTER: It specifies when the trigger will be initiated i.e. before the ongoing event
or after the ongoing event.
4. INSERT | UPDATE | DELETE : These are the DML operations and we can use either of
them in a given trigger.
5. ON[TABLE_NAME]: It specifies the name of the table on which the trigger is going to be
applied.
6. FOR EACH ROW: Row-level trigger gets executed when any row value of any column
changes.
7. TRIGGER BODY: It consists of queries that need to be executed when the trigger is called.
[email protected]
lOMoARcPSD|45012165
Example
Suppose we have a table named Student containing the attributes Student_id, Name, Address, and
Marks.
Now, we want to create a trigger that will add 100 marks to each new row of the Marks column
whenever a new student is inserted to the table.
BEFORE
INSERT
ON Student
After creating the trigger, we will write the query for inserting a new student in the database.
The Student_id column is an auto-increment field and will be generated automatically when a new
record is inserted into the table.
Advantages of Triggers
1. Triggers provide a way to check the integrity of the data. When there is a change in the
database the triggers can adjust the entire database.
[email protected]
lOMoARcPSD|45012165
2. Triggers help in keeping User Interface lightweight. Instead of putting the same function call
all over the application you can put a trigger and it will be executed.
Disadvantages of Triggers
2. The triggers may increase the overhead of the database as they are executed every time any
field is updated.
[email protected]
1. Introduction to SQL Querying
Structured Query Language (SQL) is used to interact with relational databases. The most
commonly used SQL query is the SELECT statement, which retrieves data from tables.
• Selection → Choosing specific rows (records) from a table (Using WHERE clause).
• Projection → Choosing specific columns (attributes) from a table (Using SELECT).
• Join → Combining records from multiple tables.
• Aggregation → Performing calculations on data (e.g., SUM(), AVG()).
Basic Syntax:
SELECT column1, column2, ...
FROM table_name;
• The * symbol means "all columns," so this retrieves all records and fields from the
students table.
• This retrieves only the name and age columns from the students table, ignoring other
fields.
Basic Syntax:
[email protected]
SELECT column1, column2, ...
FROM table_name
WHERE condition;
• This retrieves only those students whose age is greater than 20.
Logical Operators
• Retrieves students who are older than 18 and belong to the "CSE" department.
[email protected]
• Retrieves students who are in either "CSE" or "IT" departments.
Syntax:
6.2 IN Operator
Syntax:
[email protected]
6.3 LIKE Operator (Pattern Matching)
Wildcard Meaning
% Represents zero or more characters
_ Represents exactly one character
Syntax:
• Retrieves names that start with "A", like "Alex", "Alice", "Anand".
• Retrieves names that end with "n", like "Karan", "Arun", "Ethan".
Syntax:
[email protected]
SELECT name, age FROM students
ORDER BY age ASC;
Syntax:
9. Summary
• SELECT retrieves data (Projection).
• WHERE filters records (Selection).
• Comparison & Logical Operators refine query conditions.
• BETWEEN, IN, LIKE provide advanced filtering.
• ORDER BY sorts results.
• LIMIT restricts the number of records displayed.