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

DBMS UNIT 3

The document covers SQL functions and advanced SQL concepts including arithmetic and logical operations, various SQL functions (numeric, string, date and time), and creating tables with relationships. It explains key and integrity constraints, nested queries, subqueries, and the use of ORDER BY, GROUP BY, and HAVING clauses. Additionally, it discusses SQL aggregate functions and set operations like UNION and INTERSECT.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DBMS UNIT 3

The document covers SQL functions and advanced SQL concepts including arithmetic and logical operations, various SQL functions (numeric, string, date and time), and creating tables with relationships. It explains key and integrity constraints, nested queries, subqueries, and the use of ORDER BY, GROUP BY, and HAVING clauses. Additionally, it discusses SQL aggregate functions and set operations like UNION and INTERSECT.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Database Management System B.

Tech(CSE) II Year II Sem

UNIT III
SQL Functions: Arithmetic & logical operations, SQL functions (Numeric, String,
Date and Time, and String conversion).
Advanced SQL concepts: 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, Triggers, Indexes.

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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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.

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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.

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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;

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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.

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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.

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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:

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

Prepared by Ch Samsonu, Assoc.Professor, CSED,KHIT, Guntur


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

INTRODUCTION TO NOSQL

NoSQL is a type of database management system (DBMS) that is designed to handle and
store large volumes of unstructured and semi-structured data. Unlike traditional relational
databases that use tables with pre-defined schemas to store data, NoSQL databases use flexible
data models that can adapt to changes in data structures and are capable of scaling horizontally to
handle growing amounts of data.

The term NoSQL originally referred to “non-SQL” or “non-relational” databases, but the term has
since evolved to mean “not only SQL,” as NoSQL databases have expanded to include a wide range
of different database architectures and data models.

NoSQL databases are generally classified into four main categories:

1. Document databases: These databases store data as semi-structured documents, such as


JSON or XML, and can be queried using document-oriented query languages.

2. Key-value stores: These databases store data as key-value pairs, and are optimized for
simple and fast read/write operations.

3. Column-family stores: These databases store data as column families, which are sets of
columns that are treated as a single entity. They are optimized for fast and efficient querying
of large amounts of data.

4. Graph databases: These databases store data as nodes and edges, and are designed to
handle complex relationships between data.

5. NoSQL databases are often used in applications where there is a high volume of data that
needs to be processed and analyzed in real-time, such as social media analytics, e-commerce,
and gaming. They can also be used for other applications, such as content management
systems, document management, and customer relationship management.

However, NoSQL databases may not be suitable for all applications, as they may not provide the
same level of data consistency and transactional guarantees as traditional relational databases. It is
important to carefully evaluate the specific needs of an application when choosing a database
management system.
NoSQL originally referring to non SQL or non relational is a database that provides a mechanism
for storage and retrieval of data. This data is modeled in means other than the tabular relations
used in relational databases. Such databases came into existence in the late 1960s, but did not
obtain the NoSQL moniker until a surge of popularity in the early twenty-first century. NoSQL
databases are used in real-time web applications and big data and their use are increasing over
time.

 NoSQL systems are also sometimes called Not only SQL to emphasize the fact that they may
support SQL-like query languages. A NoSQL database includes simplicity of design, simpler
horizontal scaling to clusters of machines and finer control over availability. The data
structures used by NoSQL databases are different from those used by default in relational
databases which makes some operations faster in NoSQL. The suitability of a given NoSQL
database depends on the problem it should solve.

 NoSQL databases, also known as “not only SQL” databases, are a new type of database
management system that have gained popularity in recent years. Unlike traditional relational
databases, NoSQL databases are designed to handle large amounts of unstructured or semi-
structured data, and they can accommodate dynamic changes to the data model. This makes
NoSQL databases a good fit for modern web applications, real-time analytics, and big data
processing.

 Data structures used by NoSQL databases are sometimes also viewed as more flexible than
relational database tables. Many NoSQL stores compromise consistency in favor of
availability, speed and partition tolerance. Barriers to the greater adoption of NoSQL stores
include the use of low-level query languages, lack of standardized interfaces, and huge
previous investments in existing relational databases.

 Most NoSQL stores lack true ACID(Atomicity, Consistency, Isolation, Durability) transactions
but a few databases, such as MarkLogic, Aerospike, FairCom c-treeACE, Google Spanner
(though technically a NewSQL database), Symas LMDB, and OrientDB have made them
central to their designs.

 Most NoSQL databases offer a concept of eventual consistency in which database changes
are propagated to all nodes so queries for data might not return updated data immediately or
might result in reading data that is not accurate which is a problem known as stale reads.
Also some NoSQL systems may exhibit lost writes and other forms of data loss. Some NoSQL
systems provide concepts such as write-ahead logging to avoid data loss.

 One simple example of a NoSQL database is a document database. In a document database,


data is stored in documents rather than tables. Each document can contain a different set of
fields, making it easy to accommodate changing data requirements

 For example, “Take, for instance, a database that holds data regarding employees.”. In a
relational database, this information might be stored in tables, with one table for employee
information and another table for department information. In a document database, each
employee would be stored as a separate document, with all of their information contained
within the document.
 NoSQL databases are a relatively new type of database management system that have gained
popularity in recent years due to their scalability and flexibility. They are designed to handle
large amounts of unstructured or semi-structured data and can handle dynamic changes to
the data model. This makes NoSQL databases a good fit for modern web applications, real-
time analytics, and big data processing.

Key Features of NoSQL :

1. Dynamic schema: NoSQL databases do not have a fixed schema and can accommodate
changing data structures without the need for migrations or schema alterations.

2. Horizontal scalability: NoSQL databases are designed to scale out by adding more nodes to
a database cluster, making them well-suited for handling large amounts of data and high
levels of traffic.

3. Document-based: Some NoSQL databases, such as MongoDB, use a document-based data


model, where data is stored in semi-structured format, such as JSON or BSON.

4. Key-value-based: Other NoSQL databases, such as Redis, use a key-value data model,
where data is stored as a collection of key-value pairs.

5. Column-based: Some NoSQL databases, such as Cassandra, use a column-based data


model, where data is organized into columns instead of rows.

6. Distributed and high availability: NoSQL databases are often designed to be highly
available and to automatically handle node failures and data replication across multiple
nodes in a database cluster.

7. Flexibility: NoSQL databases allow developers to store and retrieve data in a flexible and
dynamic manner, with support for multiple data types and changing data structures.

8. Performance: NoSQL databases are optimized for high performance and can handle a high
volume of reads and writes, making them suitable for big data and real-time applications.

Advantages of NoSQL: There are many advantages of working with NoSQL databases such as
MongoDB and Cassandra. The main advantages are high scalability and high availability.

1. High scalability : NoSQL databases use sharding for horizontal scaling. Partitioning of data
and placing it on multiple machines in such a way that the order of the data is preserved is
sharding. Vertical scaling means adding more resources to the existing machine whereas
horizontal scaling means adding more machines to handle the data. Vertical scaling is not
that easy to implement but horizontal scaling is easy to implement. Examples of horizontal
scaling databases are MongoDB, Cassandra, etc. NoSQL can handle a huge amount of data
because of scalability, as the data grows NoSQL scale itself to handle that data in an efficient
manner.

2. Flexibility: NoSQL databases are designed to handle unstructured or semi-structured data,


which means that they can accommodate dynamic changes to the data model. This makes
NoSQL databases a good fit for applications that need to handle changing data requirements.
3. High availability : Auto replication feature in NoSQL databases makes it highly available
because in case of any failure data replicates itself to the previous consistent state.

4. Scalability: NoSQL databases are highly scalable, which means that they can handle large
amounts of data and traffic with ease. This makes them a good fit for applications that need
to handle large amounts of data or traffic

5. Performance: NoSQL databases are designed to handle large amounts of data and traffic,
which means that they can offer improved performance compared to traditional relational
databases.

6. Cost-effectiveness: NoSQL databases are often more cost-effective than traditional


relational databases, as they are typically less complex and do not require expensive
hardware or software.

Disadvantages of NoSQL: NoSQL has the following disadvantages.

1. Lack of standardization : There are many different types of NoSQL databases, each with its
own unique strengths and weaknesses. This lack of standardization can make it difficult to
choose the right database for a specific application

2. Lack of ACID compliance : NoSQL databases are not fully ACID-compliant, which means
that they do not guarantee the consistency, integrity, and durability of data. This can be a
drawback for applications that require strong data consistency guarantees.

3. Narrow focus : NoSQL databases have a very narrow focus as it is mainly designed for
storage but it provides very little functionality. Relational databases are a better choice in the
field of Transaction Management than NoSQL.

4. Open-source : NoSQL is open-source database. There is no reliable standard for NoSQL yet.
In other words, two database systems are likely to be unequal.

5. Lack of support for complex queries : NoSQL databases are not designed to handle
complex queries, which means that they are not a good fit for applications that require
complex data analysis or reporting.

6. Lack of maturity : NoSQL databases are relatively new and lack the maturity of traditional
relational databases. This can make them less reliable and less secure than traditional
databases.

7. Management challenge : The purpose of big data tools is to make the management of a
large amount of data as simple as possible. But it is not so easy. Data management in
NoSQL is much more complex than in a relational database. NoSQL, in particular, has a
reputation for being challenging to install and even more hectic to manage on a daily basis.

8. GUI is not available : GUI mode tools to access the database are not flexibly available in the
market.

9. Backup : Backup is a great weak point for some NoSQL databases like MongoDB. MongoDB
has no approach for the backup of data in a consistent manner.
10.Large document size : Some database systems like MongoDB and CouchDB store data in
JSON format. This means that documents are quite large (BigData, network bandwidth,
speed), and having descriptive key names actually hurts since they increase the document
size.

Types of NoSQL database: Types of NoSQL databases and the name of the databases system that
falls in that category are:

1. Graph Databases: Examples – Amazon Neptune, Neo4j

2. Key value store: Examples – Memcached, Redis, Coherence

3. Tabular: Examples – Hbase, Big Table, Accumulo

4. Document-based: Examples – MongoDB, CouchDB, Cloudant

When should NoSQL be used:

1. When a huge amount of data needs to be stored and retrieved.

2. The relationship between the data you store is not that important

3. The data changes over time and is not structured.

4. Support of Constraints and Joins is not required at the database level

5. The data is growing continuously and you need to scale the database regularly to handle the
data.

You might also like