DBMS UNIT 3
DBMS UNIT 3
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.
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
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
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
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));
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);
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
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.
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;
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.
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;
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.
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’);
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
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;
Example: The query displays all employees with their working department name and
additionally Department nameOPERATIONS without any employee:
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;
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
2. The relationship between the data you store is not that important
5. The data is growing continuously and you need to scale the database regularly to handle the
data.