0% found this document useful (0 votes)
5 views24 pages

DBMS Notes - UNIT 3

This document covers SQL basics, including querying, functions, and table creation with relationships. It details arithmetic, logical, and set operators, as well as scalar and aggregate functions, and constraints for data integrity. Additionally, it explains nested queries, grouping, ordering, and set operations in SQL.

Uploaded by

kdsiddu7
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)
5 views24 pages

DBMS Notes - UNIT 3

This document covers SQL basics, including querying, functions, and table creation with relationships. It details arithmetic, logical, and set operators, as well as scalar and aggregate functions, and constraints for data integrity. Additionally, it explains nested queries, grouping, ordering, and set operations in SQL.

Uploaded by

kdsiddu7
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/ 24

lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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

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 Operators(< , > , !=, = , >=, <=)
• SQL Logical Operators(AND, OR, NOT)
• SQL Set Operators(Union, Union all, Intersect, Minus)

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.

SQL functions are categorized into the following two categories:


• Scalar Functions
• Aggregate Functions

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

Database Management System B.Tech(CSE) II Year II Sem

Numberic Functions

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:
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

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
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

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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

Date and Time Functions

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:
select SYSDATE from dual;
select ADD_MONTHS(sysdate, 4) from dual ;
select MONTHS_BETWEEN('05-jan-99','05-jan-98') from dual;

Date Conversion Functions


Function Input Argument Value Returned
d = date value, fmt = The date d converted to a string in the
TO_CHAR ( d [, fmt ] )
format for string given format. It returns finally a string.
s = character string, fmt
TO_DATE ( s [, fmt ] ) String s converted to a date value
= format for date
d = date value, fmt = Date d rounded as specified by the
ROUND ( d [, fmt ] )
format for string format
d = date value, fmt = Date d truncated as specified by the
TRUNC ( d [, fmt ] )
format for string format

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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;

CREATING TABLES WITH RELATIONS:


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 dependant.
It should have a Primary key column.
The child table maintains a foreign key with this 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));

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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);

Implementation of Key and 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.

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

• 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

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’);

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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.

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.

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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);
Find details of customers who have ordered.
SELECT CustomerName
FROM Customers
WHERE EXISTS (SELECT CustomerID
FROM Orders
WHERE Orders.CustomerID= Customers.CustomerID);

SQL | ORDER BY, GROUP BY , HAVING CLAUSES

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

Database Management System B.Tech(CSE) II Year II Sem

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:

1.The following query counts deptno wise count of employees:


select deptno,count(*) from emp group by deptno;
2.The following query sums the salary on deptno wise of employees:
select deptno,sum(sal) from emp emp group by deptno;
3.The following query gives the jobwise maximum salary having maximum salary >= 500
select job,max(sal) from emp group by job having max(sal)>=500;

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

Database Management System B.Tech(CSE) II Year II Sem

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;

Note the ORDER BY clause applies to the combined result.

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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.

SELECT * FROM SAILOR S


WHERE EXISTS ( SELECT SID FROM RESERVES);

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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.

ALL Syntax With SELECT


SELECT ALL column_name(s)
FROM table_name
WHERE condition;
ALL Syntax With WHERE or HAVING
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name
FROM table_name
WHERE condition);

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

Database Management System B.Tech(CSE) II Year II Sem

IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
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

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

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

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;

ENAME SAL DNAME


SMITH 800 RESEARCH
ALLEN 1600 SALES
WARD 1250 SALES
JONES 2975 RESEARCH
MARTIN 1250 SALES
BLAKE 2850 SALES
CLARK 2450 ACCOUNTING
SCOTT 3000 RESEARCH
KING 5000 ACCOUNTING
TURNER 1000 SALES
ADEMS 1100 RESEARCH
JAMES 950 SALES
FORD 3000 RESEARCH
MILLER 1300 ACCOUNTING

Left Outer joins


Example: The query displays all employees with their working department name:

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

SELECT E.ENAME,E.SAL,D.DNAME FROM EMP E


LEFT OUTER JOIN DEPT D ON E.DEPTN D.DEPTNO;

ENAME SAL DNAME


SMITH 800 RESEARCH
ALLEN 1600 SALES
WARD 1250 SALES
JONES 2975 RESEARCH
MARTIN 1250 SALES
BLAKE 2850 SALES
CLARK 2450 ACCOUNTING
SCOTT 3000 RESEARCH
KING 5000 ACCOUNTING
TURNER 1000 SALES
ADEMS 1100 RESEARCH
JAMES 950 SALES
FORD 3000 RESEARCH
MILLER 1300 ACCOUNTING

Displays all employees because every employ has deptno.

Right Outer joins

Example: The query displays all employees with their working department name and
additionally Department nameOPERATIONS without any employee:

SELECT E.ENAME,E.SAL,D.DNAME FROM EMP E


RIGHT OUTER JOIN DEPT D ON E.DEPTN D.DEPTNO;

ENAME SAL DNAME


SMITH 800 RESEARCH
ALLEN 1600 SALES
WARD 1250 SALES
JONES 2975 RESEARCH
MARTIN 1250 SALES
BLAKE 2850 SALES
CLARK 2450 ACCOUNTING
SCOTT 3000 RESEARCH
KING 5000 ACCOUNTING
TURNER 1000 SALES

[email protected]
lOMoARcPSD|45012165

Database Management System B.Tech(CSE) II Year II Sem

ADEMS 1100 RESEARCH


JAMES 950 SALES
FORD 3000 RESEARCH
MILLER 1300 ACCOUNTING
OPERATIONS

Equi join
select e.ename,e.job,e.sal,d.dname from emp e,dept d where e.deptno=d.deptno;

ENAME SAL DNAME


SMITH 800 RESEARCH
ALLEN 1600 SALES
WARD 1250 SALES
JONES 2975 RESEARCH
MARTIN 1250 SALES
BLAKE 2850 SALES
CLARK 2450 ACCOUNTING
SCOTT 3000 RESEARCH
KING 5000 ACCOUNTING
TURNER 1000 SALES
ADEMS 1100 RESEARCH
JAMES 950 SALES
FORD 3000 RESEARCH
MILLER 1300 ACCOUNTING

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;

DNAME LOC DEPTNO


ACCOUNTING NEWYORK 20
ACCOUNTING NEWYORK 30
RESEARCH DALLAS 30
ACCOUNTING NEWYORK 40
RESEARCH DALLAS 40
SALES CHICAGO 40

[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:

Event: A change to the database that activates the trigger.

Condition: A query or test that is run when the trigger is activated.

Action: A procedure that is executed when the trigger is activated and its condition is true.

Syntax

create trigger Trigger_name

(before | after)

[insert | update | delete]

on [table_name]

[for each row]

[trigger_body]

1. CREATE TRIGGER: These two keywords specify that a triggered block is going to be
declared.

2. TRIGGER_NAME: It creates or replaces an existing trigger with the Trigger_name. The


trigger name should be unique.

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.

The SQL Trigger will be:

CREATE TRIGGER Add_marks

BEFORE

INSERT

ON Student

FOR EACH ROW

SET new.Marks = new.Marks + 100;

The new keyword refers to the row that is getting affected.

After creating the trigger, we will write the query for inserting a new student in the database.

INSERT INTO Student(Name, Address, Marks) VALUES('Alizeh', 'Maldives', 110);

The Student_id column is an auto-increment field and will be generated automatically when a new
record is inserted into the table.

To see the final output the query would be:

SELECT * FROM Student;

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

1. Triggers may be difficult to troubleshoot as they execute automatically in the database. If


there is some error then it is hard to find the logic of trigger because they are fired before or
after updates/inserts happen.

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.

Types of SQL Operations

• 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()).

2. SELECT Statement (Projection in SQL)


The SELECT statement is used to fetch data from a database table.

Basic Syntax:
SELECT column1, column2, ...
FROM table_name;

• column1, column2, ... → Specifies the columns to retrieve.


• table_name → Specifies the table from which data is fetched.

Example 1: Selecting All Columns


SELECT * FROM students;

• The * symbol means "all columns," so this retrieves all records and fields from the
students table.

Example 2: Selecting Specific Columns (Projection)


SELECT name, age FROM students;

• This retrieves only the name and age columns from the students table, ignoring other
fields.

3. The WHERE Clause (Selection in SQL)


The WHERE clause is used to filter records based on specific conditions.

Basic Syntax:

[email protected]
SELECT column1, column2, ...
FROM table_name
WHERE condition;

• condition → A logical expression that determines which rows will be retrieved.

Example 3: Filtering Records


SELECT name, age FROM students WHERE age > 20;

• This retrieves only those students whose age is greater than 20.

4. Operators Used in WHERE Clause


Comparison Operators

Operator Meaning Example


= Equal to age = 20
!= or <> Not equal to age != 20
> Greater than age > 18
< Less than age < 25
>= Greater than or equal to salary >= 50000
<= Less than or equal to marks <= 50

Logical Operators

Operator Meaning Example


AND Both conditions must be true age > 18 AND department = 'CSE'
OR At least one condition is true age < 18 OR department = 'IT'
NOT Negates a condition NOT (age = 20)

5. Advanced WHERE Clause Examples


Example 4: Combining Conditions using AND
SELECT name, age, department FROM students
WHERE age > 18 AND department = 'CSE';

• Retrieves students who are older than 18 and belong to the "CSE" department.

Example 5: Using OR Condition


SELECT name, department FROM students
WHERE department = 'CSE' OR department = 'IT';

[email protected]
• Retrieves students who are in either "CSE" or "IT" departments.

Example 6: Using NOT Operator


SELECT name FROM employees
WHERE NOT department = 'HR';

• Retrieves employees who are not in the "HR" department.

6. Special Operators in WHERE Clause


6.1 BETWEEN Operator

Used to filter values within a specific range (inclusive).

Syntax:

SELECT column1, column2


FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Example 7: Selecting Students Aged Between 18 and 25

SELECT name, age FROM students


WHERE age BETWEEN 18 AND 25;

• Retrieves students aged between 18 and 25 (inclusive).

6.2 IN Operator

Used to match values from a given list.

Syntax:

SELECT column1, column2


FROM table_name
WHERE column_name IN (value1, value2, value3, ...);

Example 8: Selecting Employees from Specific Departments

SELECT name, department FROM employees


WHERE department IN ('HR', 'IT', 'Finance');

• Retrieves employees working in "HR", "IT", or "Finance".

[email protected]
6.3 LIKE Operator (Pattern Matching)

Used for pattern-based searching with wildcards (% and _).

Wildcard Meaning
% Represents zero or more characters
_ Represents exactly one character

Syntax:

SELECT column1, column2


FROM table_name
WHERE column_name LIKE 'pattern';

Example 9: Finding Names That Start with "A"

SELECT name FROM students


WHERE name LIKE 'A%';

• Retrieves names that start with "A", like "Alex", "Alice", "Anand".

Example 10: Finding Names That End with "n"

SELECT name FROM students


WHERE name LIKE '%n';

• Retrieves names that end with "n", like "Karan", "Arun", "Ethan".

Example 11: Finding Names That Have "an" Anywhere

SELECT name FROM students


WHERE name LIKE '%an%';

• Retrieves names containing "an", like "Anand", "Karan", "Chandan".

7. Sorting Results using ORDER BY


The ORDER BY clause is used to sort query results in ascending (ASC) or descending (DESC)
order.

Syntax:

SELECT column1, column2


FROM table_name
WHERE condition
ORDER BY column_name ASC|DESC;

Example 12: Sorting Students by Age (Ascending)

[email protected]
SELECT name, age FROM students
ORDER BY age ASC;

• Displays students sorted by age in ascending order.

Example 13: Sorting Employees by Salary (Descending)


SELECT name, salary FROM employees
ORDER BY salary DESC;

• Displays employees sorted by salary in descending order.

8. Limiting Results using LIMIT


The LIMIT clause restricts the number of rows returned.

Syntax:

SELECT column1, column2


FROM table_name
LIMIT number_of_rows;

Example 14: Getting the Top 5 Highest Paid Employees


SELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 5;

• Retrieves the top 5 highest paid employees.

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.

[email protected]

You might also like