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

Dbms

Uploaded by

vineethsoudri01
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)
29 views

Dbms

Uploaded by

vineethsoudri01
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/ 106

Database Management Systems

Module 2

Fundamentals of SQL and


Query Optimization

Presidency University, Bengaluru


Contents
• SQL Database Querying
• DDL , DML, DCL, TCL
• Constraints
• Operators
• Set Operators
• Aggregate Functions
• Joins
• Views
• Triggers
• Procedures
• Functions

Slide 1-2
What is SQL?
• Structured Query Language, is a powerful language used for managing and manipulating
relational databases.

• is a domain-specific language designed for managing and querying relational databases.

• It provides a standardized way to interact with databases, making it an essential tool for anyone
working with data.
• SQL commands are like instructions to a table.

• SQL can perform various tasks like creating a table, adding data to tables, dropping the table,
modifying the table, set permission for users.

Slide 1-3
• These SQL commands are mainly categorized into five categories:

1. DDL – Data Definition Language

2. DML – Data Manipulation Language

3. DCL – Data Control Language

4. TCL – Transaction Control Language


5. DQL – Data Query Language

4
Data Definition Language (DDL) Commands

• DDL, which stands for Data Definition Language, is a subset of SQL(Structured Query

Language) commands used to define and modify the database structure.

• These commands are used to create, alter, and delete database objects like tables, indexes, and

schemas.

• DDL commands play a crucial role in defining the database schema.

5
Data Definition Language (DDL) Commands

The primary DDL commands in SQL include:

CREATE: This command is used to create a new database object. For example, creating a new table, a view, or a

database.

• Syntax for creating a table:

• CREATE TABLE table_name (column1 datatype, column2 datatype, ...);

6
Data Definition Language (DDL) Commands

2. ALTER: This command is used to modify an existing database object, such as adding, deleting, or

modifying columns in an existing table.

• Syntax for adding a column in a table:

• ALTER TABLE table_name ADD column_name datatype;

• Syntax for modifying a column in a table:

• ALTER TABLE table_name MODIFY COLUMN column_name datatype;

7
Data Definition Language (DDL) Commands
3. DROP: This command is used to delete an existing database object like a table, a view, or other objects.

• Syntax for dropping a table: DROP TABLE table_name;

4. TRUNCATE: This command is used to delete all data from a table, but the structure of the table remains. It’s a fast

way to clear large data from a table.

• Syntax: TRUNCATE TABLE table_name;

5. RENAME: Used to rename an existing database object.

• Syntax: RENAME TABLE old_table_name TO new_table_name;

8
Data Manipulation Language (DML) Commands in SQL
• Data Manipulation Language (DML) is a subset of SQL commands used for adding
(inserting), deleting, and modifying (updating) data in a database.
• The primary DML commands in SQL include:
• INSERT: This command is used to add new rows (records) to a table.
• Syntax: INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1,
value2, value3, ...);
• UPDATE: This command is used to modify the existing records in a table.
• Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE
condition;
• The WHERE clause specifies which records should be updated. Without it, all records in the
table will be updated.
• DELETE: This command is used to remove one or more rows from a table.
• Syntax: DELETE FROM table_name WHERE condition;
• Like with UPDATE, the WHERE clause specifies which rows should be deleted. Omitting the
WHERE clause will result in all rows being deleted. Slide 1-9
Data Manipulation Language (DML) Commands in SQL

SELECT: It is used to retrieve data from the database.

• Syntax: SELECT column1, column2, ... FROM table_name WHERE condition;

• The SELECT statement is used to query and extract data from a table, which can

then be used for various purposes.

Slide 1-10
Data Control Language (DCL) Commands in SQL
Data Control Language (DCL) is a subset of SQL commands used to control access to data in a database.

The primary DCL commands in SQL include:

GRANT: This command is used to give users access privileges to the database. These privileges

can include the ability to select, insert, update, delete, and so on, over database objects like tables

and views.

• Syntax: GRANT privilege_name ON object_name TO user_name;

• For example, GRANT SELECT ON employees TO user123; gives user123 the permission to read data from

the employees table.


Slide 1-11
Data Control Language (DCL) Commands in SQL

REVOKE: This command is used to remove previously granted access privileges

from a user.

• Syntax: REVOKE privilege_name ON object_name FROM user_name;

• For example, REVOKE SELECT ON employees FROM user123; would remove user123‘s

permission to read data from the employees table.

Slide 1-12
Transaction Control Language (TCL) Commands in SQL

Transaction Control Language (TCL) is a subset of SQL commands used to manage transactions in a

database.

• Transactions are important for maintaining the integrity and consistency of data.

• The primary TCL commands in SQL include:

COMMIT: This command is used to permanently save all changes made in the current transaction.

• Syntax: COMMIT;

• When you issue a COMMIT command, the database system will ensure that all changes made during the current

transaction are saved to the database.

Slide 1-13
Transaction Control Language (TCL) Commands in SQL

ROLLBACK: This command is used to undo changes that have been made in the

current transaction.

• Syntax: ROLLBACK;

• If you issue a ROLLBACK command, all changes made in the current transaction are

discarded, and the state of the data reverts to what it was at the beginning of the transaction.

Slide 1-14
Data Query Language (DQL) Commands in SQL
Data Query Language (DQL) is a subset of SQL commands used primarily to query and retrieve data from existing
database tables.

• In SQL, DQL is mostly centered around the SELECT statement, which is used to fetch data according to specified
criteria.

• Here’s an overview of the SELECT statement and its common clauses:

• Basic Syntax:

SELECT column1, column2, ... FROM table_name;

• To select all columns from a table, you use

SELECT * FROM table_name;

• WHERE Clause:

Used with SELECT to filter records based on specific conditions.


Slide 1-15
Data Query Language (DQL) Commands in SQL

• Example:

SELECT * FROM employees WHERE department = 'Sales';

JOIN Clauses:
• Used to combine rows from two or more tables based on a related column between them.

• Types include INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN.

• Syntax:

SELECT columns FROM table1 [JOIN TYPE] JOIN table2 ON


table1.column_name = table2.column_name;

Slide 1-16
Data Query Language (DQL) Commands in SQL

Slide 1-17
Data Query Language (DQL) Commands in SQL
JOIN / INNER JOIN

SELECT s.roll_no, s.name, s.address, s.phone,s.age,sc.course_id


FROM Student s
JOIN StudentCourse sc ON s.roll_no = sc.roll_no;

Slide 1-18
Data Query Language (DQL) Commands in SQL
LEFT JOIN

Slide 1-19
Data Query Language (DQL) Commands in SQL
LEFT JOIN RIGHT JOIN

Slide 1-20
Data Query Language (DQL) Commands in SQL
FULL JOIN

Slide 1-21
Data Query Language (DQL) Commands in SQL

GROUP BY Clause: Used with aggregate functions (like COUNT, MAX, MIN, SUM, AVG) to
group the result set by one or more columns.

Syntax:

SELECT column1, aggregate_function(column2) FROM table_name GROUP BY column1;


• Display the Average Fees of students department-wise.
SELECT MAJOR, AVG(FEES)
FROM STUDENT
GROUP BY MAJOR;

Slide 1-22
Data Query Language (DQL) Commands in SQL

ORDER BY Clause: Used to sort the result set in ascending or descending order.

Syntax:

SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];

Example: SELECT name, city FROM student ORDER BY name;


The above query returns name and city columns of table student sorted by name in increasing order.

Example: SELECT * FROM student ORDER BY city DESC;


It displays all the records of table student ordered by city in descending order.

Slide 1-23
MySQL Data Types

• There are three main data types:

• String,

• Numeric, and

• Date and Time

Slide 1-24
String Data Types
• CHAR(size):
• A FIXED length string (can contain letters, numbers, and special characters).

• The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1

• VARCHAR(size):
• A VARIABLE length string (can contain letters, numbers, and special characters).

• The size parameter specifies the maximum string length in characters - can be from 0 to 65535.

Slide 1-25
Numeric Data Types
INT(size):
• A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is
from 0 to 4294967295.

FLOAT(size, d):
• A floating point number. The total number of digits is specified in size. The number of digits
after the decimal point is specified in the d parameter.

26
Date and Time Data Types
• DATE:
• Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31’.

• TIME(fsp):
• It is used to specify the time format. Its format is hh:mm:ss. Its supported range is
from '-838:59:59' to '838:59:59'

Slide 1-27
Constraints in SQL
• NOT NULL - Ensures that a column cannot have a NULL value

• UNIQUE - Ensures that all values in a column are different

• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table

• FOREIGN KEY - Uniquely identifies a row/record in another table

• CHECK - Ensures that all values in a column satisfies a specific condition

• DEFAULT - Sets a default value for a column when no value is specified

Slide 1-28
NOT NULL Constraint
• The NOT NULL constraint enforces a column to NOT accept NULL values.

• This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record
without adding a value to this field.

• Example:

• CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

Slide 1-29
PRIMARY KEY Constraint:
• The PRIMARY KEY constraint uniquely identifies each record in a table.

• Primary keys must contain UNIQUE values, and cannot contain NULL values.

• A table can have only ONE primary key;

• Example:
• CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, PRIMARY KEY (ID));

Slide 2-30
UNIQUE Constraint
• The UNIQUE constraint ensures that all values in a column are different.

• Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for
a column or set of columns.

• A PRIMARY KEY constraint automatically has a UNIQUE constraint.

• However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
• Example:
• CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age
int, UNIQUE (ID));

Slide 1-31
FOREIGN KEY Constraint
• The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.

• A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.

• The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.

• Example:
• CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY
KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));

Slide 2-32
CHECK Constraint
• The CHECK constraint is used to limit the value range that can be placed in a column.

• If you define a CHECK constraint on a column it will allow only certain values for this column.

• If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.

• Example:
• CREATE TABLE Person (ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int,
CHECK (Age>=18));

33
DEFAULT Constraint

• The DEFAULT constraint is used to set a default value for a column.

• The default value will be added to all new records, if no other value is specified.

• Example:
• CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int,
City varchar(255) DEFAULT ‘Bangalore’);

• The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():

• Example:
• CREATE TABLE Orders (ID int NOT NULL, OrderNumber int NOT NULL, OrderDate date DEFAULT GETDATE());

34
SQL Operators:
SQL operators are categorized in the following categories:
1. SQL Arithmetic Operators
2. SQL Comparison Operators
3. SQL Logical Operator
4. SQL Set Operators

Slide 2-35
SQL Arithmetic Operators
• The Arithmetic Operators perform the mathematical operation on the numerical data of the SQL tables.

• These operators perform addition, subtraction, multiplication, and division operations on the numerical operands.

• Following are the various arithmetic operators performed on the SQL data:
• SQL Addition Operator (+)

• SQL Subtraction Operator (-)

• SQL Multiplication Operator (*)

• SQL Division Operator (-)

• SQL Modulus Operator (%)

36
SQL Addition Operator (+)
• Syntax of SQL Addition Operator:
SELECT operand1 + operand2;
• Example:
SELECT Emp_Salary + 20000 as Emp_New_Salary FROM Employee_details;

SQL Subtraction Operator (-)


• Syntax of SQL Subtraction Operator:
SELECT operand1 - operand2;
• Example:
SELECT Emp_Salary - 5000 as Emp_New_Salary FROM Employee_details;

37
SQL Multiplication Operator (*)
• Syntax of SQL Multiplication Operator:

SELECT operand1 * operand2;

• Example:

SELECT Emp_Salary * 2 as Emp_New_Salary FROM Employee_details;

SQL Division Operator (/)


• Syntax of SQL Division Operator:

SELECT operand1 / operand2;

• Example:

SELECT Emp_Salary / 2 as Emp_New_Salary FROM Employee_details;

38
SQL Modulus Operator (%)
• Syntax of SQL Modulus Operator:

SELECT operand1 % operand2;

• Example:

SELECT First_operand % Second_operand as Remainder FROM Employee_details;

39
SQL Comparison Operators
1.SQL Equal Operator (=)

2.SQL Not Equal Operator (!=)

3.SQL Greater Than Operator (>)

4.SQL Greater Than Equals to Operator (>=)

5.SQL Less Than Operator (<)

6.SQL Less Than Equals to Operator (<=)

40
SQL Equal Operator (=)
• The Equal Operator in SQL shows only data that matches the specified value in the query.

• Example: SELECT * FROM Employee_details WHERE Emp_Salary = 30000;

SQL Equal Not Operator (!=)


• The Equal Not Operator in SQL shows only those data that do not match the query's specified value.

• Example: SELECT * FROM Employee_details WHERE Emp_Salary != 45000;

41
SQL Greater Than Operator (>)
• The Greater Than Operator in SQL shows only those data which are greater than the value of the right-hand
operand.

• Example: SELECT * FROM Employee_details WHERE Emp_Id > 202;

SQL Greater Than Equals to Operator (>=)


• The Greater Than Equals to Operator in SQL shows those data from the table which are greater than and equal
to the value of the right-hand operand.

• Example: SELECT * FROM Employee_details WHERE Emp_Id >= 202;

42
SQL Less Than Operator (<)
• The Less Than Operator in SQL shows only those data from the database tables which are less than the value of
the right-side operand.

• Example: SELECT * FROM Employee_details WHERE Emp_Id < 204;

SQL Less Than Equals to Operator (<=)


• The Less Than Equals to Operator in SQL shows those data from the table which are lesser and equal to the
value of the right-side operand

• Example: SELECT * FROM Employee_details WHERE Emp_Id <= 203;

43
SQL Logical Operators
1. SQL ALL operator

2. SQL AND operator

3. SQL OR operator

4. SQL BETWEEN operator

5. SQL IN operator

6. SQL NOT operator

7. SQL LIKE operator

44
SQL ALL Operator
• The ALL operator in SQL compares the specified value to all the values of a column from the
sub-query in the SQL database.

• This operator is always used with the following statement:

1.SELECT,

2.HAVING, and

3.WHERE.

45
SQL ALL Operator
• Syntax of ALL operator:
SELECT column_Name1, ...., column_NameN FROM table_Name WHERE column
Comparison_operator ALL (SELECT column FROM tablename2)
• Example:
SELECT Emp_Id, Emp_Name FROM Employee_details WHERE Emp_Salary > ALL ( SELECT Emp
_Salary FROM Employee_details WHERE Emp_City = Jaipur)

• The outer query selects Emp_Id and Emp_Name from the table Employee_details.
• The WHERE clause filters the results based on a condition.
• The condition Emp_Salary > ALL (...) compares the salary of each employee with the salaries of all employees from Jaipur.
• The inner query (SELECT Emp_Salary FROM Employee_details WHERE Emp_City = 'Jaipur') retrieves the salaries of
employees from Jaipur.
• The ALL keyword ensures that the salary of the outer query's employee is greater than all salaries retrieved by the inner query
for employees from Jaipur.
46
• So, the query will return the Emp_Id and Emp_Name of employees whose salary is greater than all employees from Jaipur.
SQL AND Operator
• The AND operator in SQL would show the record from the database table if all the conditions separated by the
AND operator evaluated to True.

• It is also known as the conjunctive operator and is used with the WHERE clause.

• Syntax of AND operator:


• SELECT column1, ...., columnN FROM table_Name WHERE condition1 AND condition2 AND condition3 AND ....... AND conditionN;

• Example:

SELECT * FROM Employee_details WHERE Emp_Salary = 25000 AND Emp_City = 'Delhi';

47
SQL OR Operator
• Syntax of OR operator:

SELECT column1, ...., columnN FROM

table_Name WHERE condition1 OR condition2

OR condition3 OR ....... OR conditionN;

Example:

SELECT * FROM Employee_details WHERE Emp_Salary = 25000 OR Emp_City = 'Delhi';

48
SQL BETWEEN Operator
• The BETWEEN operator in SQL shows the record within the range mentioned in the SQL query. This operator
operates on the numbers, characters, and date/time operands.

• If there is no value in the given range, then this operator shows NULL value.

• Syntax of BETWEEN operator:

SELECT column_Name1, column_Name2 ...., column_NameN FROM

table_Name WHERE column_name BETWEEN value1 and value2;

• Example:

SELECT * FROM Employee_details WHERE Emp_Salary BETWEEN 30000 AND 45000;

49
SQL IN Operator
• The IN operator in SQL allows database users to specify two or more values in a WHERE clause.
• This logical operator minimizes the requirement of multiple OR conditions.
• This operator makes the query easier to learn and understand.
• This operator returns those rows whose values match with any value of the given list.
IN operator:
SELECT column_Name1, column_Name2 ...., column_NameN FROM table_Name WHERE column_name IN (list_of_
values);
• Example:
SELECT * FROM Employee_details WHERE Emp_Id IN (202, 204, 205);
NOT IN:
Example:
SELECT * FROM Employee_details WHERE Emp_Id NOT IN (202,205);

50
SQL NOT Operator
• The NOT operator in SQL shows the record from the table if the condition evaluates to false. It
is always used with the WHERE clause.

• Syntax of NOT operator:

SELECT column1, column2 ...., columnN FROM

table_Name WHERE NOT condition;

• Example:

SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi’.

51
SQL LIKE Operator
• The LIKE operator in SQL shows those records from the table which match with the given pattern specified in the
sub-query.
• The percentage (%) sign is a wildcard which is used in conjunction with this logical operator.
• This operator is used in the WHERE clause with the following three statements:
1. SELECT statement
2. UPDATE statement
3. DELETE statement
• Syntax of LIKE operator:
SELECT column_Name1, column_Name2 ...., column_NameN FROM
table_Name WHERE column_name LIKE pattern;
• Example:
SELECT * FROM Employee_details WHERE Emp_Name LIKE 's%’ ; (starts with)
SELECT * FROM Employee_details WHERE Emp_Name LIKE '%y’ ; (Ends with)
SELECT * FROM Employee_details WHERE Emp_Name LIKE 'S%y’; (Both)

52
SQL Set Operators
• The Set Operators in SQL combine a similar type of data from two or more
SQL database tables.

• It mixes the result, which is extracted from two or more SQL queries, into a
single result.

• Set operators combine more than one select statement in a single query and
return a specific result set.

53
SQL Set Operators
1.SQL Union Operator

2.SQL Union ALL Operator

3.SQL Intersect Operator

4.SQL Minus Operator

54
SQL Union Operator
• The SQL Union Operator combines the result of two or more SELECT statements
and provides the single output.

• The data type and the number of columns must be the same for each SELECT
statement used with the UNION operator.

• This operator does not show the duplicate records in the output table.

55
SQL Union Operator
• Syntax of UNION Set operator:
SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]
UNION
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
• Example:
SELECT Emp_ID, Emp_Name FROM Employee_details1 UNION
SELECT Emp_ID, Emp_Name FROM Employee_details2 ;

56
SQL Set Operators
Table: T1_STUDENT Table: T2_STUDENT
Favourite_Subj Favourite_S
ID Name Hometown Percentage ID Name Hometown Percentage
ect ubject
1 Soniya Jain Udaipur 89 Java
1 Soniya Jain Udaipur 89 Java
2 Harshada Sharma Kanpur 92 C Programming 2 Ishwari Dixit Delhi 86 Python
3 Anuja Rajput Jaipur 78 C++
3 Anuja Rajput Jaipur 78 C++
Operating
Machine 4 Pakhi Arora Surat 70
4 Pranali Singh Nashik 88 System
Learning
5 Renuka Deshmukh Panipat 90 Data Science 5 Renuka Deshmukh Panipat 90 Data Science
Cloud
6 Swati Kumari Faridabad 93 Computer
Computing 6 Jayshree Patel Pune 91
Networks
7 Prachi Jaiswal Gurugram 96 DBMS
7 Prachi Jaiswal Gurugram 96 DBMS

SELECT *FROM T1_STUDENT UNION SELECT *FROM T2_STUDENT;


SELECT *FROM T1_STUDENT UNION ALL SELECT *FROM T2_STUDENT;

57
SQL Union ALL Operator
• The SQL Union Operator is the same as the UNION operator, but the only difference is that it also shows the
same record.
• Syntax of UNION ALL Set operator:
SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]
UNION ALL
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
• Example:
• If we want to see the employee name of each employee of both tables in a single output. For this, we have to
write the following query in SQL:
SELECT Emp_Name FROM Employee_details1 UNION ALL
SELECT Emp_Name FROM Employee_details2 ;

58
SQL Intersect Operator
• The SQL Intersect Operator shows the common record from two or more SELECT statements. The data type and the number of
columns must be the same for each SELECT statement used with the INTERSECT operator.
• Syntax of INTERSECT Set operator:
SELECT column1, column2 ...., columnN FROM table_Name1
[WHERE conditions]
INTERSECT
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
• Example:

SELECT Emp_Name FROM Employee_details1


INTERSECT
SELECT Emp_Name FROM Employee_details2 ;

59
SQL Minus Operator
• The SQL Minus Operator combines the result of two or more SELECT statements and shows only the results from the first data
set.
• Syntax of MINUS operator:
SELECT column1, column2 ...., columnN FROM First_tablename [WHERE conditions]
MINUS
SELECT column1, column2 ...., columnN FROM Second_tablename [WHERE conditions];
• Suppose, we want to see the name of employees from the first result set after the combination of both tables
SELECT Emp_Name FROM Employee_details1
MINUS
SELECT Emp_Name FROM Employee_details2 ;

60
Types of SQL Aggregation Function

61
SQL Aggregate Functions

• SQL aggregation function is used to perform the calculations on multiple rows of

a single column of a table.

• It returns a single value.

• It is also used to summarize the data.

62
COUNT FUNCTION
• COUNT function is used to Count the number of rows in a database table.

• It can work on both numeric and non-numeric data types.

• COUNT function uses the COUNT(*) that returns the count of all the rows in a

specified table. COUNT(*) considers duplicate and Null.

63
COUNT FUNCTION
• Syntax
COUNT(*)
or COUNT( [ALL|DISTINCT] expression )
• Example:
SELECT COUNT(*) FROM PRODUCT_MAST;
• COUNT with WHERE
SELECT COUNT(*) FROM PRODUCT_MAST WHERE RATE>=20;
• COUNT() with DISTINCT
SELECT COUNT(DISTINCT COMPANY) FROM PRODUCT_MAST;

64
COUNT FUNCTION
• COUNT() with GROUP BY
Example:
SELECT COMPANY, COUNT(*) FROM
PRODUCT_MAST GROUP BY COMPANY;
COUNT() with HAVING
SELECT COMPANY, COUNT(*) FROM
PRODUCT_MAST GROUP BY COMPANY
HAVING COUNT(*)>2;

65
SUM Function
• Sum function is used to calculate the sum of all selected columns.
• It works on numeric fields only.
• Syntax
SUM() or
SUM( [ALL|DISTINCT] expression )
• Example: SUM()
SELECT SUM(COST) FROM PRODUCT_MAST;

66
AVG function
• The AVG function is used to calculate the average value of the numeric type.
AVG function returns the average of all non-Null values.

• Syntax

AVG() or AVG( [ALL|DISTINCT] expression )

• Example:

SELECT AVG(COST) FROM PRODUCT_MAST;

67
MAX Function
• MAX function is used to find the maximum value of a certain column.

• This function determines the largest value of all selected values of a column.

• Syntax

MAX() or

MAX( [ALL|DISTINCT] expression )

• Example:

SELECT MAX(RATE) FROM PRODUCT_MAST;

68
MIN Function
• MIN function is used to find the minimum value of a certain column.

• This function determines the smallest value of all selected values of a column.

• Syntax

MIN() or MIN( [ALL|DISTINCT] expression )

• Example:

SELECT MIN(RATE) FROM PRODUCT_MAST;

69
Views in SQL
• Views in SQL are considered as a virtual table. A view also contains
rows and columns.

• To create the view, we can select the fields from one or more tables
present in the database.

• A view can either have specific rows based on certain condition or all
the rows of a table.

70
Advantages of View:
1. Complexity

2. Security

3. Consistency

4. Data Integrity

5. Storage Capacity

6. Logical Data Independence

71
Disadvantages of View:
• The DML statements which can be performed on a view created using single base table have certain
restrictions are:

1.You cannot INSERT if the base table has any not null column that do not appear in view.

2.You cannot INSERT or UPDATE if any of the column referenced in the INSERT or UPDATE contains
group functions or columns defined by expression.

3.You can't execute INSERT, UPDATE, DELETE statements on a view, if with read only option is enabled.

4.You can't be created view on temporary tables.

72
Sample table:
Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram

Student_Marks
STU_ID NAME MARKS AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18

73
Creating view
• A view can be created using the CREATE VIEW statement.
• We can create a view from a single table or multiple tables.
• Syntax: STU_ID NAME ADDRESS
CREATE VIEW view_name AS 1 Stephan Delhi
SELECT column1, column2..... 2 Kathrin Noida
FROM table_name 3 David Ghaziabad

WHERE condition; 4 Alina Gurugram

• Creating View from a single table


• In this example, we create a View named DetailsView from the table Student_Detail.

• Query:

CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM Student_Details WHERE


STU_ID < 4; 74
View
• Just like table query, we can query the view to view the data.
SELECT * FROM DetailsView;
• Output:

NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad

75
• In the given example, a view is created named MarksView from two tables Student_Detail and Student_Marks.
• Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Marks
WHERE Student_Detail.NAME = Student_Marks.NAME;
• SELECT * FROM MarksView;

NAME ADDRESS MARKS


Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90

76
View
• Deleting View
• A view can be deleted using the Drop View statement.
• Syntax
DROP VIEW view_name;

77
Types of Views:

• There are two types of views.

78
Types of Views
1.Join View: A join view is a view that has more than one table or view in its from
clause and it does not use any Group by Clause, Distinct and set operation.

2.Inline View: An inline view is a view which is created by replacing a subquery in


the from clause which defines the data source that can be referenced in the
main query. The sub query must be given an alias for efficient working.

79
Types of Views
• Example
• Assume there are two tables: The first table is User_Address, which maps each user to a ZIP code; the second
table is User_Score, which records all the scores of each user. The question is, how to write a SQL query to find
the number of users who scored higher than 200 for each ZIP code?
• Without using an inline view, we can accomplish this in two steps:

80
Trigger in SQL
• A Trigger in Structured Query Language is a set of procedural statements which
are executed automatically when there is any response to certain events on the
particular table in the database.

• Triggers are used to protect the data integrity in the database.

• In SQL, this concept is the same as the trigger in real life. For example, when we
pull the gun trigger, the bullet is fired.

81
Triggers
• In Structured Query Language, triggers are called only either before or after
the below events:

1.INSERT Event: This event is called when the new row is entered in the table.

2.UPDATE Event: This event is called when the existing record is changed or
modified in the table.

3.DELETE Event: This event is called when the existing record is removed from the
table.
82
Types of Triggers in SQL
• Following are the six types of triggers in SQL:
1.AFTER INSERT Trigger
This trigger is invoked after the insertion of data in the table.
2.AFTER UPDATE Trigger
This trigger is invoked in SQL after the modification of the data in the table.
3.AFTER DELETE Trigger
This trigger is invoked after deleting the data from the table.
4.BEFORE INSERT Trigger
This trigger is invoked before the inserting the record in the table.
5.BEFORE UPDATE Trigger
This trigger is invoked before the updating the record in the table.
6.BEFORE DELETE Trigger
This trigger is invoked before deleting the record from the table.

83
Syntax of Trigger in SQL
CREATE TRIGGER Trigger_Name

[ BEFORE | AFTER ]

[ Insert | Update | Delete]

ON [Table_Name]

[ FOR EACH ROW | FOR EACH COLUMN ]

AS

Set of SQL Statement


84
Example of Trigger in SQL
CREATE TABLE Student_Trigger (
Student_RollNo INT PRIMARY KEY,
Student_FirstName VARCHAR(100),
Student_EnglishMarks INT,
Student_PhysicsMarks INT,
Student_ChemistryMarks INT,
Student_MathsMarks INT,
Student_TotalMarks INT,
Student_Percentage DECIMAL(5, 2)
);

85
The following query shows the structure of theStudent_Trigger table:
DESC Student_Trigger;

Field Type NULL Key Default Extra


Student_RollNo INT NO PRI NULL
Student_FirstName Varchar(100) YES NULL
Student_EnglishMarks INT YES NULL
Student_PhysicsMarks INT YES NULL
Student_ChemistryMarks INT YES NULL
Student_MathsMarks INT YES NULL
Student_TotalMarks INT YES NULL
Student_Percentage INT YES NULL

86
• The following query fires a trigger before the insertion of the student record in the
table:

CREATE TRIGGER Student_Table_Marks


BEFORE INSERT
ON
Student_Trigger
FOR EACH ROW
SET new.Student_TotalMarks = new.Student_EnglishMarks + new.Student_PhysicsMarks + new.Student
_ChemistryMarks + new.Student_MathsMarks,
new.Student_Percentage = ( new.Student_TotalMarks / 400) * 100;

87
• The following query inserts the record into Student_Trigger table:
INSERT INTO Student_Trigger (Student_RollNo,
Student_FirstName, Student_EnglishMarks,
Student_PhysicsMarks, Student_ChemistryMarks,
Student_MathsMarks, Student_TotalMarks,
Student_Percentage) VALUES
( 201, Sorya, 88, 75, 69, 92, 0, 0);
• To check the output of the above INSERT statement,
SELECT * FROM Student_Trigger;

88
OUTPUT
Student_RollNo Student_FirstNa Student_English Student_Physics Student_chemistr Student_MathsM Student_TotalMar Student_Percenta
me Marks Marks yMarks arks ks ge

201 Sorya 88 75 69 92 324 81

89
Advantages of Triggers in SQL
• Following are the three main advantages of triggers in Structured Query
Language:
1.SQL provides an alternate way for maintaining the data and referential integrity
in the tables.
2.Triggers helps in executing the scheduled tasks because they are called
automatically.
3.They allow the database users to validate values before inserting and updating.

90
Disadvantages of Triggers in SQL

• Following are the main disadvantages of triggers in Structured Query Language:


1.They are not compiled.
2.It is not possible to find and debug the errors in triggers.
3.If we use the complex code in the trigger, it makes the application run slower.

91
PL/SQL Procedure
• The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks.

• It is just like procedures in other programming languages.

• The procedure contains a header and a body.

• Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.

• Body: The body contains a declaration section, execution section and exception section.

92
How to pass parameters in procedure
• When you want to create a procedure or function, you have to define parameters.
There are three ways to pass parameters in procedure:

1.IN parameters: The IN parameter can be referenced by the procedure or function.


The value of the parameter cannot be overwritten by the procedure or the function.

2.OUT parameters: The OUT parameter cannot be referenced by the procedure or


function, but the value of the parameter can be overwritten by the procedure or
function.

3.INOUT parameters: The INOUT parameter can be referenced by the procedure or


function and the value of the parameter can be overwritten by the procedure or
function. 93
PL/SQL Create Procedure
• Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION exception_section]
END
[procedure_name];

94
Create procedure example
• In this example, we are going to insert record in user table. So you need to create user
table first.
Table creation:
create table user (id int(10) primary key, name varchar(100));
Now write the procedure code to insert record in user table.
• Procedure Code:
create or replace procedure "INSERTUSER"
(id IN NUMBER, name IN VARCHAR2) is
begin insert into user values(id,name);
end;

95
PL/SQL program to call procedure
• Let's see the code to call above created procedure.
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully’);
END;
• Now, see the "USER" table, you will see one record is inserted.
ID NAME
101 Rahul

96
PL/SQL Drop Procedure
• Syntax for drop procedure

DROP PROCEDURE procedure_name;

• Example of drop procedure

DROP PROCEDURE pro1;

97
Advantages
• Using Procedures result in performance improvement of the application.
• Reduce the traffic between the database and the application.
• Code reusability

Disadvantages
• Stored procedures can cause a lot of memory usage.
• MySQL does not provide the functionality of debugging the stored procedures.

98
PL/SQL Function
• The PL/SQL Function is very similar to PL/SQL Procedure.

• The main difference is, a function must always return a value, and on the
other hand a procedure may or may not return a value.

• Except this, all the other things of PL/SQL procedure are true for PL/SQL
function too.

99
Syntax to create a function:
CREATE [OR REPLACE] FUNCTION function_name [parameters]

[(parameter_name [IN | OUT | IN OUT] type [, ...])]


RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

100
PL/SQL Function
• Function_name: specifies the name of the function.
• [OR REPLACE] option allows modifying an existing function.
• The optional parameter list contains name, mode and types of the parameters.
• IN represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
• The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the function.
• Function_body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone function.

101
PL/SQL Function Example
create or replace function adder(n1 in number, n2 in number)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;

102
PL/SQL Function Example
• Now write another program to call the function.
DECLARE
n3 number(2);
BEGIN
n3 := adder(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;

103
PL/SQL
DECLARE
Function Example
a number; Consider an example to demonstrate Declaring, Defining and Invoking a simple
b number; PL/SQL function which will compute and return the maximum of two values.
c number;
FUNCTION findMax(x IN number, y IN number)

RETURN number BEGIN


IS a:= 23;
z number; b:= 45;
BEGIN
IF x > y THEN c := findMax(a, b);
z:= x; dbms_output.put_line(' Maximum of (23,45): ' || c);
ELSE
z:= y; END;
END IF;
RETURN z;
END;

104
PL/SQL Drop Function
Syntax for removing your created function:

DROP FUNCTION function_name;

105
106

You might also like