Oracle 9i introduces several new features for SQL queries including support for full outer joins, the USING clause for joins, and flashback queries to view past states of data. It also adds new functions, enhances administration tools, and allows online redefinition of objects without downtime. Undo management is improved with automatic undo management and undo retention settings.
1) SQL is a standard language for accessing and manipulating databases. It allows users to define, manipulate, and control access to data in a database.
2) SQL was first introduced in a 1970 research paper and later developed into a language. It became a standard and is now supported by most major databases.
3) SQL allows users to define tables, perform data manipulation like inserts and updates, run queries to retrieve data, and control transactions in the database. It provides powerful and easy to use commands to work with relational databases.
1) SQL is a standard language for accessing and manipulating databases. It allows users to define, manipulate, and control access to data in a database.
2) SQL was first introduced in a 1970 research paper and later developed into a language. It became a standard and is now supported by most major databases.
3) SQL allows users to define tables, perform data manipulation like inserts and updates, run queries to retrieve data, and control transactions in the database. It provides powerful and easy to use commands to work with relational databases.
This document discusses various SQL concepts including data types, data definition language (DDL), data manipulation language (DML), constraints, and transactions. It provides examples of creating tables with different data types, inserting, updating, and deleting data, setting constraints, and using transactions like commit and rollback. Key points covered include creating a table with a timestamp column, using case expressions, cursor for loops, and nested procedures and exception handling.
1. The document describes experiments related to SQL DDL, DML commands and SELECT statements.
2. It discusses commands like CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, SELECT, UPDATE, DELETE and provides syntax and examples for each.
3. Queries are provided at the end of each experiment to create tables, insert data, modify structure, retrieve and manipulate data using the studied commands.
in this presentation the commands let you help to understand the basic of the database system software. how to retrieve data, how to feed data and manipulate it very efficiently by using this commands.
This document outlines the contents of a manual for a database management systems laboratory course. It covers 5 chapters on different lab programs involving creating database tables, inserting data, and writing queries. Chapter 1 provides an introduction to basic SQL commands including DDL, DML, TCL, and DCL commands. It describes commands like CREATE TABLE, ALTER TABLE, DROP TABLE, SELECT, INSERT, UPDATE, DELETE. Subsequent chapters provide the problem statements, ER diagrams, schema diagrams, code for creating tables and inserting sample data, and solutions to queries for 5 different database domains - library, orders, movies, college, and company.
2. DBMS Experiment - Lab 2 Made in SQL UsedTheVerse1
The document describes a database management system lab covering integrity constraints and data manipulation language (DML). It defines various integrity constraints like primary key, unique key, foreign key, check, default and NOT NULL constraints. It also explains how to create tables, alter tables, insert, update and delete data using DML commands. Experiments are described to design tables for different systems using appropriate integrity constraints and populate them with sample data using DML statements.
Oracle 9i introduces several new features for SQL queries including support for full outer joins, the USING clause for joins, and flashback queries to view past states of data. It also adds new functions, enhances administration tools, and allows online redefinition of objects without downtime. Undo management is improved with automatic undo management and undo retention settings.
1) SQL is a standard language for accessing and manipulating databases. It allows users to define, manipulate, and control access to data in a database.
2) SQL was first introduced in a 1970 research paper and later developed into a language. It became a standard and is now supported by most major databases.
3) SQL allows users to define tables, perform data manipulation like inserts and updates, run queries to retrieve data, and control transactions in the database. It provides powerful and easy to use commands to work with relational databases.
1) SQL is a standard language for accessing and manipulating databases. It allows users to define, manipulate, and control access to data in a database.
2) SQL was first introduced in a 1970 research paper and later developed into a language. It became a standard and is now supported by most major databases.
3) SQL allows users to define tables, perform data manipulation like inserts and updates, run queries to retrieve data, and control transactions in the database. It provides powerful and easy to use commands to work with relational databases.
This document discusses various SQL concepts including data types, data definition language (DDL), data manipulation language (DML), constraints, and transactions. It provides examples of creating tables with different data types, inserting, updating, and deleting data, setting constraints, and using transactions like commit and rollback. Key points covered include creating a table with a timestamp column, using case expressions, cursor for loops, and nested procedures and exception handling.
1. The document describes experiments related to SQL DDL, DML commands and SELECT statements.
2. It discusses commands like CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, SELECT, UPDATE, DELETE and provides syntax and examples for each.
3. Queries are provided at the end of each experiment to create tables, insert data, modify structure, retrieve and manipulate data using the studied commands.
in this presentation the commands let you help to understand the basic of the database system software. how to retrieve data, how to feed data and manipulate it very efficiently by using this commands.
This document outlines the contents of a manual for a database management systems laboratory course. It covers 5 chapters on different lab programs involving creating database tables, inserting data, and writing queries. Chapter 1 provides an introduction to basic SQL commands including DDL, DML, TCL, and DCL commands. It describes commands like CREATE TABLE, ALTER TABLE, DROP TABLE, SELECT, INSERT, UPDATE, DELETE. Subsequent chapters provide the problem statements, ER diagrams, schema diagrams, code for creating tables and inserting sample data, and solutions to queries for 5 different database domains - library, orders, movies, college, and company.
2. DBMS Experiment - Lab 2 Made in SQL UsedTheVerse1
The document describes a database management system lab covering integrity constraints and data manipulation language (DML). It defines various integrity constraints like primary key, unique key, foreign key, check, default and NOT NULL constraints. It also explains how to create tables, alter tables, insert, update and delete data using DML commands. Experiments are described to design tables for different systems using appropriate integrity constraints and populate them with sample data using DML statements.
SQL is a standard language for accessing and manipulating databases. It allows users to query, insert, update, and delete data. The document discusses SQL statements like SELECT, INSERT, UPDATE, DELETE and functions like JOIN, aggregate functions, and scalar functions. It provides examples of creating tables and manipulating data using DDL, DML, and DCL statements. Joins allow combining data from multiple tables based on common fields.
SQL is a standard language used to manage data in relational database management systems. It can be used to create and modify database objects like tables and stored procedures, query and manipulate data, and set permissions. Common SQL statements include SELECT to query data, INSERT and UPDATE to modify data, CREATE and ALTER to define database structure, and DELETE to remove data. Transactions are managed using commands like COMMIT, ROLLBACK, and SAVEPOINT. Security is enforced using GRANT and REVOKE commands to manage user permissions on database objects.
- A table is a logical representation of data stored in a database. It holds data in rows and columns.
- Data Definition Language (DDL) commands like CREATE, ALTER, TRUNCATE, DROP are used to create, modify and delete database objects like tables.
- Data Manipulation Language (DML) commands like INSERT, SELECT, UPDATE, DELETE are used to query and manipulate data in existing tables.
- A table is a logical representation of data stored in a database. It contains data organized into rows and columns.
- Data Definition Language (DDL) commands like CREATE, ALTER, DROP are used to define and manage database objects like tables. These commands implicitly commit transactions.
- Data Manipulation Language (DML) commands like INSERT, SELECT, UPDATE, DELETE are used to query and manipulate data within existing database tables.
The document discusses various SQL commands used for data manipulation:
1. The INSERT command is used to add rows to a table by specifying column values.
2. The SELECT command is used to retrieve data from one or more tables.
3. The UPDATE command modifies existing records in a table by changing column values.
4. The DELETE command removes rows from a table.
Data Definition Language (DDL), Data Definition Language (DDL), Data Manipulation Language (DML) , Transaction Control Language (TCL) , Data Control Language (DCL) - , SQL Constraints
This document contains information about a database management systems practical file submitted by Sachin for their fourth semester computer science course. It includes an index of experiments completed and sections covering database languages like DDL, DML, and DCL. It also discusses topics like data types in SQL, set operations, joins, query processing, and constraints.
1. The document describes the laboratory manual for the subject "Fundamentals of Database Management Systems" for the III B. Tech - II Semester at Malla Reddy Engineering College.
2. It provides the sample database for the Railway Reservation System and lists 13 experiments involving SQL commands for creating tables, inserting data, querying, joining, aggregation and more.
3. The goals of the course are to practice concepts learned in DBMS by developing and querying a database using SQL and PL/SQL statements.
This document provides an overview of SQL statements, functions, and joins. It discusses the main SQL statements including CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, GRANT, and REVOKE. It also covers aggregate functions such as SUM, AVG, MIN, MAX, and COUNT, as well as scalar functions like LCASE, UCASE, and ROUND. Finally, it summarizes the different types of joins in SQL, including inner joins, left outer joins, and right outer joins.
This document provides instructions for experiments in a Database Management System laboratory course. It includes a list of 12 experiments covering topics like Data Definition Language commands, Data Manipulation Language commands, database design using ER modeling and normalization, and implementation of various database applications. It also provides details on the hardware and software requirements for the course, as well as the internal assessment structure including marks distribution.
This document summarizes SQL statements, functions, and joins. It defines SQL as a programming language for managing relational databases and describes common SQL statements like DDL, DML, and DCL. It also outlines functions like aggregate functions to return single calculated values and scalar functions to modify values. Finally, it explains join operations to combine data from multiple tables based on common fields.
The document provides examples of SQL commands for:
1. Selecting data from tables including top rows, random rows, joins, outer joins, and grouping.
2. Creating views and stored procedures.
3. Differences between functions and stored procedures.
4. Using triggers, cursors, and retrieving the second highest/lowest value from a column.
5. Common DDL commands like creating, copying, deleting, and altering tables.
So in summary, it covers the basics of SQL including queries, views, stored procedures, functions, triggers and DDL commands.
The document discusses SQL database commands including DDL commands like CREATE, ALTER, DROP and TRUNCATE used to build and modify database structures. It describes using CREATE TABLE to generate tables with data types like VARCHAR2, CHAR, NUMBER, DATE and LOB types. ALTER TABLE adds, deletes or modifies columns and constraints. DROP TABLE deletes tables. DML commands like INSERT INTO, UPDATE and DELETE are used to add, modify and remove data from tables.
This document provides an introduction to SQL (Structured Query Language). It defines SQL as a standard language for accessing and manipulating databases. The key points covered include:
- SQL lets you perform queries against a database to retrieve, insert, update, and delete data. It can also be used to create and modify database structures.
- Common SQL commands covered are SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, ALTER TABLE, DROP TABLE.
- Additional SQL concepts explained are data types, WHERE clauses, ORDER BY clauses, GROUP BY clauses, and JOIN operations.
- RDBMS systems like MySQL, SQL Server, Oracle, etc. use SQL to communicate with the databases they manage.
SQL commands are used to communicate with databases and perform tasks like creating tables, adding data, modifying tables, and querying data. There are five main types of SQL commands: DDL for defining data structures, DML for manipulating data, DCL for controlling access, TCL for transactions, and DQL for querying data. DDL commands like CREATE, ALTER, and DROP are used to create, modify, and delete tables while DML commands like INSERT, UPDATE, DELETE add, modify, and remove data in tables. [END SUMMARY]
SQL offers many powerful techniques for analyzing your data out of the box, but being also extendable if you are still missing something. Now much more easier in 18c with polymorphic table functions (PTF). As an evolution of table functions, PTF is invoked in the FROM clause and is capable to encapsulate the custom processing of the input data, whereas the input row type does not have to be known at design time and the output row type may first be determined by the actual PTF invocation parameters. This session will give you an introduction based on simple examples. Discover how you can develop your own flexible and self-describing extensions while focusing on business logic and leaving complex things like parallel execution to the database.
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELijaia
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Determination of Equivalent Circuit parameters and performance characteristic...pvpriya2
Includes the testing of induction motor to draw the circle diagram of induction motor with step wise procedure and calculation for the same. Also explains the working and application of Induction generator
More Related Content
Similar to unit 3.pptx notes very important prepare
SQL is a standard language for accessing and manipulating databases. It allows users to query, insert, update, and delete data. The document discusses SQL statements like SELECT, INSERT, UPDATE, DELETE and functions like JOIN, aggregate functions, and scalar functions. It provides examples of creating tables and manipulating data using DDL, DML, and DCL statements. Joins allow combining data from multiple tables based on common fields.
SQL is a standard language used to manage data in relational database management systems. It can be used to create and modify database objects like tables and stored procedures, query and manipulate data, and set permissions. Common SQL statements include SELECT to query data, INSERT and UPDATE to modify data, CREATE and ALTER to define database structure, and DELETE to remove data. Transactions are managed using commands like COMMIT, ROLLBACK, and SAVEPOINT. Security is enforced using GRANT and REVOKE commands to manage user permissions on database objects.
- A table is a logical representation of data stored in a database. It holds data in rows and columns.
- Data Definition Language (DDL) commands like CREATE, ALTER, TRUNCATE, DROP are used to create, modify and delete database objects like tables.
- Data Manipulation Language (DML) commands like INSERT, SELECT, UPDATE, DELETE are used to query and manipulate data in existing tables.
- A table is a logical representation of data stored in a database. It contains data organized into rows and columns.
- Data Definition Language (DDL) commands like CREATE, ALTER, DROP are used to define and manage database objects like tables. These commands implicitly commit transactions.
- Data Manipulation Language (DML) commands like INSERT, SELECT, UPDATE, DELETE are used to query and manipulate data within existing database tables.
The document discusses various SQL commands used for data manipulation:
1. The INSERT command is used to add rows to a table by specifying column values.
2. The SELECT command is used to retrieve data from one or more tables.
3. The UPDATE command modifies existing records in a table by changing column values.
4. The DELETE command removes rows from a table.
Data Definition Language (DDL), Data Definition Language (DDL), Data Manipulation Language (DML) , Transaction Control Language (TCL) , Data Control Language (DCL) - , SQL Constraints
This document contains information about a database management systems practical file submitted by Sachin for their fourth semester computer science course. It includes an index of experiments completed and sections covering database languages like DDL, DML, and DCL. It also discusses topics like data types in SQL, set operations, joins, query processing, and constraints.
1. The document describes the laboratory manual for the subject "Fundamentals of Database Management Systems" for the III B. Tech - II Semester at Malla Reddy Engineering College.
2. It provides the sample database for the Railway Reservation System and lists 13 experiments involving SQL commands for creating tables, inserting data, querying, joining, aggregation and more.
3. The goals of the course are to practice concepts learned in DBMS by developing and querying a database using SQL and PL/SQL statements.
This document provides an overview of SQL statements, functions, and joins. It discusses the main SQL statements including CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, GRANT, and REVOKE. It also covers aggregate functions such as SUM, AVG, MIN, MAX, and COUNT, as well as scalar functions like LCASE, UCASE, and ROUND. Finally, it summarizes the different types of joins in SQL, including inner joins, left outer joins, and right outer joins.
This document provides instructions for experiments in a Database Management System laboratory course. It includes a list of 12 experiments covering topics like Data Definition Language commands, Data Manipulation Language commands, database design using ER modeling and normalization, and implementation of various database applications. It also provides details on the hardware and software requirements for the course, as well as the internal assessment structure including marks distribution.
This document summarizes SQL statements, functions, and joins. It defines SQL as a programming language for managing relational databases and describes common SQL statements like DDL, DML, and DCL. It also outlines functions like aggregate functions to return single calculated values and scalar functions to modify values. Finally, it explains join operations to combine data from multiple tables based on common fields.
The document provides examples of SQL commands for:
1. Selecting data from tables including top rows, random rows, joins, outer joins, and grouping.
2. Creating views and stored procedures.
3. Differences between functions and stored procedures.
4. Using triggers, cursors, and retrieving the second highest/lowest value from a column.
5. Common DDL commands like creating, copying, deleting, and altering tables.
So in summary, it covers the basics of SQL including queries, views, stored procedures, functions, triggers and DDL commands.
The document discusses SQL database commands including DDL commands like CREATE, ALTER, DROP and TRUNCATE used to build and modify database structures. It describes using CREATE TABLE to generate tables with data types like VARCHAR2, CHAR, NUMBER, DATE and LOB types. ALTER TABLE adds, deletes or modifies columns and constraints. DROP TABLE deletes tables. DML commands like INSERT INTO, UPDATE and DELETE are used to add, modify and remove data from tables.
This document provides an introduction to SQL (Structured Query Language). It defines SQL as a standard language for accessing and manipulating databases. The key points covered include:
- SQL lets you perform queries against a database to retrieve, insert, update, and delete data. It can also be used to create and modify database structures.
- Common SQL commands covered are SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, ALTER TABLE, DROP TABLE.
- Additional SQL concepts explained are data types, WHERE clauses, ORDER BY clauses, GROUP BY clauses, and JOIN operations.
- RDBMS systems like MySQL, SQL Server, Oracle, etc. use SQL to communicate with the databases they manage.
SQL commands are used to communicate with databases and perform tasks like creating tables, adding data, modifying tables, and querying data. There are five main types of SQL commands: DDL for defining data structures, DML for manipulating data, DCL for controlling access, TCL for transactions, and DQL for querying data. DDL commands like CREATE, ALTER, and DROP are used to create, modify, and delete tables while DML commands like INSERT, UPDATE, DELETE add, modify, and remove data in tables. [END SUMMARY]
SQL offers many powerful techniques for analyzing your data out of the box, but being also extendable if you are still missing something. Now much more easier in 18c with polymorphic table functions (PTF). As an evolution of table functions, PTF is invoked in the FROM clause and is capable to encapsulate the custom processing of the input data, whereas the input row type does not have to be known at design time and the output row type may first be determined by the actual PTF invocation parameters. This session will give you an introduction based on simple examples. Discover how you can develop your own flexible and self-describing extensions while focusing on business logic and leaving complex things like parallel execution to the database.
Similar to unit 3.pptx notes very important prepare (20)
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELijaia
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Determination of Equivalent Circuit parameters and performance characteristic...pvpriya2
Includes the testing of induction motor to draw the circle diagram of induction motor with step wise procedure and calculation for the same. Also explains the working and application of Induction generator
Digital Twins Computer Networking Paper Presentation.pptxaryanpankaj78
A Digital Twin in computer networking is a virtual representation of a physical network, used to simulate, analyze, and optimize network performance and reliability. It leverages real-time data to enhance network management, predict issues, and improve decision-making processes.
Build the Next Generation of Apps with the Einstein 1 Platform.
Rejoignez Philippe Ozil pour une session de workshops qui vous guidera à travers les détails de la plateforme Einstein 1, l'importance des données pour la création d'applications d'intelligence artificielle et les différents outils et technologies que Salesforce propose pour vous apporter tous les bénéfices de l'IA.
Open Channel Flow: fluid flow with a free surfaceIndrajeet sahu
Open Channel Flow: This topic focuses on fluid flow with a free surface, such as in rivers, canals, and drainage ditches. Key concepts include the classification of flow types (steady vs. unsteady, uniform vs. non-uniform), hydraulic radius, flow resistance, Manning's equation, critical flow conditions, and energy and momentum principles. It also covers flow measurement techniques, gradually varied flow analysis, and the design of open channels. Understanding these principles is vital for effective water resource management and engineering applications.
A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...DharmaBanothu
The Network on Chip (NoC) has emerged as an effective
solution for intercommunication infrastructure within System on
Chip (SoC) designs, overcoming the limitations of traditional
methods that face significant bottlenecks. However, the complexity
of NoC design presents numerous challenges related to
performance metrics such as scalability, latency, power
consumption, and signal integrity. This project addresses the
issues within the router's memory unit and proposes an enhanced
memory structure. To achieve efficient data transfer, FIFO buffers
are implemented in distributed RAM and virtual channels for
FPGA-based NoC. The project introduces advanced FIFO-based
memory units within the NoC router, assessing their performance
in a Bi-directional NoC (Bi-NoC) configuration. The primary
objective is to reduce the router's workload while enhancing the
FIFO internal structure. To further improve data transfer speed,
a Bi-NoC with a self-configurable intercommunication channel is
suggested. Simulation and synthesis results demonstrate
guaranteed throughput, predictable latency, and equitable
network access, showing significant improvement over previous
designs
Generative AI Use cases applications solutions and implementation.pdfmahaffeycheryld
Generative AI solutions encompass a range of capabilities from content creation to complex problem-solving across industries. Implementing generative AI involves identifying specific business needs, developing tailored AI models using techniques like GANs and VAEs, and integrating these models into existing workflows. Data quality and continuous model refinement are crucial for effective implementation. Businesses must also consider ethical implications and ensure transparency in AI decision-making. Generative AI's implementation aims to enhance efficiency, creativity, and innovation by leveraging autonomous generation and sophisticated learning algorithms to meet diverse business challenges.
https://www.leewayhertz.com/generative-ai-use-cases-and-applications/
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Transcat
Join us for this solutions-based webinar on the tools and techniques for commissioning and maintaining PV Systems. In this session, we'll review the process of building and maintaining a solar array, starting with installation and commissioning, then reviewing operations and maintenance of the system. This course will review insulation resistance testing, I-V curve testing, earth-bond continuity, ground resistance testing, performance tests, visual inspections, ground and arc fault testing procedures, and power quality analysis.
Fluke Solar Application Specialist Will White is presenting on this engaging topic:
Will has worked in the renewable energy industry since 2005, first as an installer for a small east coast solar integrator before adding sales, design, and project management to his skillset. In 2022, Will joined Fluke as a solar application specialist, where he supports their renewable energy testing equipment like IV-curve tracers, electrical meters, and thermal imaging cameras. Experienced in wind power, solar thermal, energy storage, and all scales of PV, Will has primarily focused on residential and small commercial systems. He is passionate about implementing high-quality, code-compliant installation techniques.
Supermarket Management System Project Report.pdfKamal Acharya
Supermarket management is a stand-alone J2EE using Eclipse Juno program.
This project contains all the necessary required information about maintaining
the supermarket billing system.
The core idea of this project to minimize the paper work and centralize the
data. Here all the communication is taken in secure manner. That is, in this
application the information will be stored in client itself. For further security the
data base is stored in the back-end oracle and so no intruders can access it.
Levelised Cost of Hydrogen (LCOH) Calculator ManualMassimo Talia
The aim of this manual is to explain the
methodology behind the Levelized Cost of
Hydrogen (LCOH) calculator. Moreover, this
manual also demonstrates how the calculator
can be used for estimating the expenses associated with hydrogen production in Europe
using low-temperature electrolysis considering different sources of electricity
2. S-1 SLO-1 : Basics of SQL-DDL,DML,DCL,TCL
SLO-2 : Structure Creation, alternation
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign Key, Unique,
not null, check, IN operator
S-3 SLO-1 : Functions-aggregation functions
SLO-2 : Built-in Functions- Numeric, Date, String functions, Set operations
S 4-5 SLO-1 & SLO-2 : Lab 7 : Join Queries on sample exercise.
S-6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
S-8 SLO-1 : Transaction Control Commands
SLO-2 : Commit, Rollback, Savepoint
S-9-10 SLO-1 & SLO-2 : Lab 8: Set Operators & Views.
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions Triggers and Exceptional Handling
S-13 SLO-1 & SLO-2 : Query Processing
S-14-15SLO-1 & SLO-2 : Lab9: PL/SQL Conditional and Iterative Statements
Outline of the Presentation
5/9/2024 2
Dr.B.Muruganantham
Associate Professor / CTech
3. Structured Query Language ( SQL)
SQL became a standard of the American National Standards Institute (ANSI)
in 1986, and of the International Organization for Standardization (ISO) in
1987
Common language for all Databases
Fourth generation Language
Non procedural Language
Commands like an normal English statements
SQL is not a case sensitive language
All SQL statements should ended with terminator , the default terminator is
semi-colon (;)
Based on the operation SQL divided into three categories
– DDL ( Data Definition Language)
– DML ( Data Manipulation Language)
– DCL ( Data Control Language)
5/9/2024
Dr.B.Muruganantham
Associate Professor / CTech
3
S-1 SLO-1 : Basics of SQL-DDL,DML,DCL,TCL
4. Data Definition Language (DDL)
DDL is the subset of SQL and part of DBMS
DDL relates only with base tables structure and it is no where relates with the
information stored in the table.
Note : All the DDL command statements are AUTO COMMIT Statements
DDL consists of the following commands
– CREATE
– ALTER
– DROP
– TRUNCATE
5/9/2024
Dr.B.Muruganantham
Associate Professor / CTech
4
S-1 SLO-2 : Structure Creation, alternation
5. 5/9/2024
Dr.B.Muruganantham
Associate Professor / CTech
5
Data Definition Language (DDL)
CREATE COMMAND
Used to create a new object / schema with a defined structure
Syntax :
Example :
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
CREATE TABLE EMP
(EMPNO NUMBER(4) NOT NULL, ENAME VARCHAR2(10), JOB VARCHAR2(9),
MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7, 2), COMM NUMBER(7, 2),
DEPTNO NUMBER(2));
S-1 SLO-2 : Structure Creation, alternation
6. Data Definition Language (DDL)
ALTER COMMAND
Alter command used to modify the base table structure
Using this command
– a new column can be added with restrictions
– column data width can be increased / decreased with
restrictions
– a column can be dropped
Two key words are using in this command
– ADD
– MODIFY
5/9/2024
Dr.B.Muruganantham
Associate Professor / CTech
6
S-1 SLO-2 : Structure Creation, alternation
7. Data Definition Language (DDL)
ALTER COMMAND
5/9/2024
Dr.B.Muruganantham
Associate Professor / CTech
7
SYNTAX
ALTER TABLE table_name ADD / MODIFY column_name datatype;
EXAMPLE 1: To add a new column in a table
ALTER TABLE emp ADD phone_no number(10);
EXAMPLE 2 : TO modify the existing column data width
ALTER TABLE emp MODIFY phone_no number(13);
S-1 SLO-2 : Structure Creation, alternation
8. Data Definition Language (DDL)
ALTER COMMAND
5/9/2024
Dr.B.Muruganantham
Associate Professor / CTech
8
Syntax to DROP a column
ALTER TABLE table_name DROP column column_name;
Example :
ALTER TABLE emp DROP column phone_no;
S-1 SLO-2 : Structure Creation, alternation
9. 5/9/2024
Dr.B.Muruganantham
Associate Professor / CTech
9
Data Definition Language (DDL)
DROP COMMAND
It is used to remove the base table with records (information) from
database permanently.
Syntax:
DROP TABLE table_name ;
Example:
DROP TABLE emp;
S-1 SLO-2 : Structure Creation, alternation
10. 5/9/2024
Dr.B.Muruganantham
Associate Professor / CTech
10
TRUNCATE COMMAND
Truncate command used to delete the records (information) from the
base table permanently and keeps the structure of the base table alone
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE emp;
S-1 SLO-2 : Structure Creation, alternation
11. DML Commands are relates only with base table information ( value in an attribute)
There are four commands in DML:
1. INSERT
2. UPDATE
3. DELETE
4. SELECT
Where clause ( Conditional retrieval )
Order by clause ( Retrieval in Ascending or Descending Order )
Group by clause ( Retrieval of distinct values by considering
groups )
Having clause ( Followed by Group by clause with COUNT
function )
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
11
S-1 SLO-2 : Structure Creation, alternation
12. INSERT COMMAND
It relates only with new records.
Only one row can be inserted at a time
Multiple rows can be inserted using “&” symbol one by one
Can insert in selected columns with some restrictions
Must follow the order of the column specified in the query statement
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
12
S-1 SLO-2 : Structure Creation, alternation
13. INSERT COMMAND
Syntax:
INSERT INTO <table_name> (column_name1
<datatype>,
column_name2 <datatype>,
. . . ,
column_name_n <datatype>)
VALUES
(value1,
value2,
. . . ,
value n);
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
13
S-1 SLO-2 : Structure Creation, alternation
Note :
Number values can be
inserted as integer or
float
Char and Date values
must be in single quote
14. INSERT COMMAND
Example 1: To insert a record using all fields in EMP table
INSERT INTO EMP VALUES (7369, 'SMITH', 'CLERK', 7902, '17-12-1980‘, 800, NULL, 20);
(OR)
INSERT INTO EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)
VALUES (7369, 'SMITH', 'CLERK', 7902, '17-12-1980', 800, NULL, 20);
Example 2: To insert a record using selected fields in EMP table
INSERT INTO EMP (EMPNO, ENAME) VALUES (7499, 'ALLEN);
Note : When a record is inserted using selected fields, it must include
NOT NULL and Primary key fields.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
14
S-1 SLO-2 : Structure Creation, alternation
15. Example 3: To insert multiple records using all fields in EMP table
INSERT INTO EMP values
(&EMPNO,’&ENAME’,’&JOB’,&MGR,’&HIREDATE’,&SAL,&COMM,&DEPTNO) ;
NOTE : ‘&’ (Ampersand) symbol used to ask
Enter value for followed by the string during runtime.
The input value will be store in the appropriate field using bind
variable ( :OLD and :NEW)
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
15
S-1 SLO-2 : Structure Creation, alternation
16. Update command
It works with only existing records
It works only column wise
It is used to modify the column values ( increase / decrease / change)
Syntax
UPDATE <table_name> set <field_name> = value [ where <condition>];
Note : Update command without where condition will update all the records.
Update command with where condition will update the records which are satisfy
the condition
Example 1:
UPDATE emp set comm = 2000 ; ( Update all the records in EMP table )
Example 2 :
Update emp set comm = 1000 where empno = 7369;
(Update the records having the empno as 7369)
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
16
S-1 SLO-2 : Structure Creation, alternation
17. Delete command
It works only with existing records
It works only with row wise
It not possible to delete a single column in a row
Syntax
DELETE from <table_name> [ where <condition>];
Note : Delete command with out where condition will delete all the records in the table.
Delete command with where condition will delete the selected records which are
satisfy the condition.
Example 1: DELETE from emp; ( All records will be deleted from emp )
Example 2: DELETE from emp where empno = 7369;
( Those records holding the value in the field empno as 7369 will be deleted )
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
17
S-1 SLO-2 : Structure Creation, alternation
18. SELECT COMMAND
Works with existing records
Works with row wise and column wise
Works with multiple tables
Never affect / change / update / modification in the
data base
Using this command , we can select a column , multiple
columns, all columns, single row, multiple row, all rows
Specially called as “QUERY STATEMENT”
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
18
S-1 SLO-2 : Structure Creation, alternation
19. SELECT COMMAND
Syntax
SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
NOTE : To retrieve all the column from the table ‘ * ’ symbol can be
used instead of specifying the column_list.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
19
S-1 SLO-2 : Structure Creation, alternation
20. SELECT COMMAND
Example 1: To retrieve all the columns and rows from emp table
SELECT * from emp; ( ‘*’ stands from all columns and rows )
Example 2: To select retrieve the specific columns from all rows
SELECT empno,ename from emp;
Select command with where clause
Example 3: To retrieve the records from emp table which record holds the salary value
greater than 1000;
SELECT * from emp WHERE sal> 1000;
Example 4: To retrieve the columns empno and ename from emp table which records holds
the value as CLERK in job column.
SELECT empno, ename from emp WHERE job = ‘CLERK’
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
20
S-1 SLO-2 : Structure Creation, alternation
21. SELECT COMMAND
Select command with order by clause
Example 5 : To retrieve the records from emp table in
ascending order using empno
SELECT * from emp order by empno asc;
(OR)
SELECT * from emp order by empno;
Example 6: To retrieve the records from emp table in
ascending order using job and empno
SELECT * from emp order by job,empno asc;
(OR)
SELECT * from emp order by job,empno;
NOTE : Ascending order is default condition, no need to specify
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
21
S-1 SLO-2 : Structure Creation, alternation
22. SELECT COMMAND
Select command with order by clause
Example 7 : To retrieve the records from emp table in descending order using
empno.
SELECT * from emp order by empno desc;
Example 8: To retrieve the records from emp table in descending order using job
and empno
SELECT * from emp order by job desc,empno desc;
Example 8: To retrieve the records from emp table in ascending order using job
and descending order empno
SELECT * from emp order by job asc,empno desc;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
22
S-1 SLO-2 : Structure Creation, alternation
23. SELECT COMMAND
Select command with group by clause
Example 9: To retrieve the different jobs from emp table
SELECT job from emp group by job;
Example 10: To retrieve the different jobs and its average salary from emp
table
SELECT job, avg(sal) from emp group by job;
Select command with group by and having clause
Example 11: To retrieve the different jobs from emp table where the total
numbers in a group is greater than 2;
SELECT job from emp group by job having count(job) >2;
NOTE : Count is built-in group function
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
23
S-1 SLO-2 : Structure Creation, alternation
24. Data Control Languages
Used to give / get back / control the privileges of an object by the owner
GRANT : To give access privileges of an object to other user by the owner
Syntax : GRANT [ ALL / INSERT /UPDATE /DELETE /SELECT ]
on <OBJECT_NAME> to <USER_NAME>;
Example: GRANT all on emp to scott;
REVOKE : To get back all the privileges from the user who has been granted
Syntax : REVOKE [ ALL / INSERT /UPDATE /DELETE /SELECT ]
on <OBJECT_NAME> from <USER_NAME>;
Example: REVOKE all on emp from scott;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
24
S-1 SLO-2 : Structure Creation, alternation
25. Constraint
Purpose
Use a constraint to define an integrity constraint--a rule that restricts
the values in a database.
Oracle Database lets you create five types of constraints and lets you
declare them in two ways.
There five types of integrity constraint
• NOT NULL constraint
• Unique constraint
• Primary key constraint
• Foreign key constraint
• Check constraint
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
25
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
26. General Syntax for Constraints:
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
26
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
27. Not Null Constraint
NOT NULL constraint prohibits a database value from being null.
Permits duplicate values
To satisfy a NOT NULL constraint, every row in the table must contain a value for
the column.
Restrictions on NOT NULL Constraints
NOT NULL constraints are subject to the following restrictions:
You cannot specify NULL or NOT NULL in a view constraint.
You cannot specify NULL or NOT NULL for an attribute of an object. Instead, use
a CHECK constraint with the IS [NOT] NULL condition.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
27
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
28. Syntax for Not Null constraint
Create table <table_name> ( column_1 datatype Constraint <constraint_name>
<constraint_type>,
column_2 datatype,
………..
……….
column_n datatype);
Example
Create table emp ( empno number constraint my_cons_NN not null,
ename varchar2(10), sal number(10), dept varchar2(10));
Note : Constraints may specified without name also, in that case system automatically
assign some random name.
Create table emp ( empno number(10) not null, ename varchar2(10),
sal number(10), dept varchar2(10));
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
28
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
29. Unique Constraint
A unique constraint designates a column as a unique key.
A composite unique key designates a combination of columns as the
unique key.
To satisfy a unique constraint, no two rows in the table can have the
same value for the unique key.
Unique constraint allows null values and it allows more number of null
values (Two null values are always not equal ).
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
29
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
30. Restrictions on Unique Constraint
None of the columns in the unique key can be of
LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, OBJECT, REF, o
r user-defined type.
A composite unique key cannot have more than 32 columns.
You cannot designate the same column or combination of columns as
both a primary key and a unique key.
You cannot specify a unique key when creating a subview in an
inheritance hierarchy. The unique key can be specified only for the
top-level (root) view.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
30
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
31. Syntax for unique constraint
Create table <table_name> ( column_1 datatype Constraint <constraint_name>
<constraint_type>, column_2 datatype,
………..
……….
column_n datatype);
Example
Create table emp ( empno number(10) constraint my_cons_UK unique,
ename varchar2(10), sal number(10), dept varchar2(10));
Example for Composite Unique Key
Create table emp ( empno number(10), ename varchar2(10), sal
number(10), dept varchar2(10), Constraint my_unique_key unique (empno,ename));
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
31
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
32. Primary Key
A primary key constraint designates a column as the primary key of a
table or view.
A composite primary key designates a combination of columns as the
primary key.
A primary key constraint combines a NOT NULL and unique
constraint in one declaration
Therefore, to satisfy a primary key constraint:
• No primary key value can appear in more than one row in the table.
• No column that is part of the primary key can contain a null.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
32
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
33. Restrictions on Primary Key Constraints
A table or view can have only one primary key.
None of the columns in the primary key can be LOB , LONG , LONG RAW , VARRAY,
NESTED TABLE , BFILE, REF, TIMESTAMP WITH TIME ZONE, or user-defined type.
The size of the primary key cannot exceed approximately one database block.
A composite primary key cannot have more than 32 columns.
You cannot designate the same column or combination of columns as both a primary
key and a unique key.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
33
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
34. Syntax for Primary key constraint
Create table <table_name> ( column_1 datatype Constraint
<constraint_name> <constraint_type>, column_2 datatype,
………..
……….
column_n datatype);
Example
Create table emp ( empno number(10) constraint my_cons_PK primary key,
ename varchar2(10), sal number(10), dept varchar2(10));
Example for composite primary key
Create table emp ( empno number(10, ename varchar2(10),
sal number(10), dept varchar2(10),
constraint my_cons_CPK primary key (empno,dept));
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
34
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
35. Foreign key constraint
A foreign key constraint (also called a referential integrity constraint) designates
a column as the foreign key and establishes a relationship between that foreign
key and a specified primary or unique key, called the referenced key.
A composite foreign key designates a combination of columns as the foreign key.
The table or view containing the foreign key is called the child object, and the
table or view containing the referenced key is called the parent object.
The foreign key and the referenced key can be in the same table or view.
To satisfy a composite foreign key constraint, the composite foreign key must
refer to a composite unique key or a composite primary key in the parent table
or view, or the value of at least one of the columns of the foreign key must be
null.
You can define multiple foreign keys in a table or view
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
35
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
36. Restrictions on Foreign Key Constraints
None of the columns in the foreign key can be of
LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, BFILE, REF,
TIMESTAMP WITH TIME ZONE, or user-defined type.
The referenced unique or primary key constraint on the parent table or
view must already be defined.
A composite foreign key cannot have more than 32 columns.
The child and parent tables must be on the same database.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
36
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
37. Syntax for Foreign Key
CREATE TABLE <child_table_name> ( column_1 datatype,
column_1 datatype ,
-------
Dept_id references <parent_table_name>
(Parent_table_Primary key));
Example
CREATE TABLE emp ( empno number (10) Primary key,
ename varchar2(25),
salary number(10,2),
dept_id references DEPT (DEPT_ID));
An entity emp created with foreign key constraint referencing dept entity
primary key attribute dept_id.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
37
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
38. Check Constraint
A check constraint lets you specify a condition that each row in the table must satisfy.
To satisfy the constraint, each row in the table must make the condition either TRUE or
NULL
Restrictions on Check Constraints
You cannot specify a check constraint for a view.
The condition of a check constraint can refer to any column in the table, but it cannot
refer to columns of other tables.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
38
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign
Key, Unique, Not null, Check, IN operator
40. Aggregation Functions
MAX – To find the number of the maximum values in the SQL table.
MIN – Number of the minimum values in the table.
COUNT – Get the number of count values in the SQL table.
AVG – Find average values in the SQL table.
SUM – Return the summation of all non-null values in the SQL table.
DISTINCT – Return the distinct values of a column.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
40
S3 SLO-1 : Functions - aggregation functions
41. Note : For all the examples , consider the “EMP” Table
Max Function
Syntax: Max( Column_name)
Example : Select max(sal) from emp;
Min Function
Syntax : Min(Column_name)
Example : Select min(sal) from emp;
Avg Function
Syntax : Avg( Column_name)
Example : Select avg(sal) from emp;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
41
S3 SLO-1 : Functions - aggregation functions
42. Sum Function
Syntax : Sum(Column_name)
Example : Select sum(sal) from emp;
Count Function
Syntax : Count(Column_name)
Example : Select count(sal) from emp;
Note : (1) When Count (*) is used , it will count the number of
rows using rowid value ( Rowid is the unique id and it is
a 16bit hexa decimal number for all the rows assigned at
the time of creation)
(2) When Count (Column_name) is used, it will count the
number of values in a specified column except null values
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
42
S3 SLO-1 : Functions - aggregation functions
43. Distinct Function
Syntax : Distinct ( Column_name)
Example : Select distinct (job) from emp;
STDDEV Function
Syntax : Stddev ( Column_name)
Example : Select stddev(sal) from emp;
Variance Function
Syntax : Variance (Coulmn_name)
Example : Select variance (sal) from emp;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
43
S3 SLO-1 : Functions - aggregation functions
44. Some more examples using EMP table
Select sum(sal), avg(sal), min(sal), max(sal) from emp;
Select Job, sum(sal) from emp group by job;
Select Job, count(job) from emp group by job;
Select job, avg(sal), max(sal),min(sal) from emp group by job;
Select distinct (job) from emp;
Select count(*) from emp;
Select count(comm) from emp;
Select count(sal) from emp;
Select stddev(sal) from emp;
select variance(sal) from emp;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
44
S3 SLO-1 : Functions - aggregation functions
45. Numeric Functions
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
45
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Functions Value Returned Example
Abs(n) Absolute value of n Select abs(-15) from dual;
Ceil(n) Smallest int >= n Select ceil(33.645) from dual;
Cos(n) Cosine of n Select cos(180) from dual;
Cosh(n) Hyperbolic cosine of n Select cosh(0) from dual;
Exp(n) en Select exp(2) from dual;
Floor(n) Largest int <= n Select floor(100.2) from dual;
Ln(n) Natural log of n (base e) Select ln(5) from dual;
Log(b,n) Log n base b Select log(2,64) from dual;
Mod(m,n) Remainder of m divided by n Select mod(17,3) from dual;
46. Numeric Functions
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
46
Functions Value Returned Example
Power(m,n) m power n Select power(5,3) from dual;
Round(m,n) m rounded to n decimal places Select round(125.67854,2) from dual;
Sign(n) If n<0, -1 if n=0, 0 otherwise 1. Select sin(-19) from dual;
Sin(n) Sin of n Select sin(90) from dual;
Sinh(n) Hyperbolic sin of n Select sinh(45) from dual;
Sqrt(n) Square root of n Select sqrt(7) from dual;
Tan(n) Tangent of n Select tan(45) from dual;
Tanh(n) Hyperbolic tangent of n Select tanh(60) from dual;
Trunc(m,n) m truncated to n decimal places Select trunc(125.5764,2) from dual;
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
47. Date Functions
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
47
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Functions Value Returned Example
add_months(d,n) ‘n’ months added to date ‘d’. Select add_months(sysdate,2) from dual;
last_day(d) Date corresponding to the last day
of the month
Select last_day(sysdate) from dual;
to_date(str,’format’) Converts the string ina given
format into Oracle date.
Select to_date(’10-02-09’,’dd-mm-yy’)
from dual;
to_char(date,’format’) Reformats date according to
format
Select to_char(sysdate,’dy dd mon yyyy’)
from dual;
months_between(d1,d2) No. of months between two dates
Select months_between(sysdate,
to_date(’10-10-07’,’dd-mm-yy’) )
from dual;
next_day(d,day) Date of the ‘day’ that immediately
follows the date ‘d’
Select next_day(sysdate,’wednesday’)
from dual;
48. 09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
48
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Date Functions
Functions Value Returned Input
round(d,’format’)
Date will be the rounded to nearest
day.
Select round(sysdate,’year’) from dual;
Select round(sysdate,’month’) from dual;
Select round(sysdate,’day’) from dual;
Select round(sysdate) from dual;
trunc(d,’format’)
Date will be the truncated to
nearest day.
Select trunc(sysdate,’year’) from dual;
Select trunc(sysdate,’month’) from dual;
Select trunc(sysdate,’day’) from dual;
Select trunc(sysdate) from dual;
greatest(d1,d2,…) Picks latest of list of dates
Select greatest(sysdate, to_date(‘02-10- 06’,’dd-mm-yy’),to-
date(’12-07- 12’,’dd-mm-yy’)) from dual;
Date Arithmetic
Add /Subtract no. of days to a date
Select sysdate+25 from dual;
Select sysdate-25 from dual;
Subtract one date from another,
producing a no. of days
Select sysdate - to_date(‘02-10-06’,’dd- mm-yy’) from dual;
49. String Functions
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
49
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Functions Value Returned Input
initcap(char) First letter of each word
capitalized
Select initcap(‘database management’) from dual;
lower(char) Lower case Select lower(‘WELCOME’) from dual;
upper(char) Upper case Select upper(‘srmist’) from dual;
ltrim(char, set) Initial characters removed up
to the character not in set.
Select ltrim(‘muruganantham’,’murug’) from
dual;
rtrim(char, set) Final characters removed after
the last character not in set.
Select rtrim(‘muruganantham’,’antham’)
from dual;
translate(char,
from, to) Translate ‘from’ by ‘to’ in char. Select translate(‘jack’,’j’,’b’) from dual;
replace(char,
search, repl)
Replace ‘search’ string by ‘repl’
string in ‘char’.
Select replace(‘jack and jue’,’j’,’bl’) from dual;
substr(char, m, n) Substring of ‘char’ at ‘m’ of size
‘n’ char long.
Select substr(‘muruganantham’,7,6) from dual;
50. 09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
50
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Set Operators
Set operators are used to join the results of two (or more) SELECT
statement.
The following set operators are available in SQL
• Union
• Union All
• Intersect
• Minus
51. Set Operators
Union operator retrieves the records from both queries without
duplicate.
Coulmn heading will be selected from the prior query statement.
Union All retrieves all the records from both queries (with duplicate).
Intersect operator retrieve the common records from both query
statements.
Minus operator retrieve the records from first query , the records are
not available in second query.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
51
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
52. Set Operators
Point to be followed while using SET operators
The number of columns must be same in all participating query
Column heading will be selected from the first query for displaying the output.
Data types of the column list must be match with all the query.
Positional ordering must be used to sort the result set.
UNION and INTERSECT operators are commutative, i.e. the order of queries is
not important; it doesn't change the final result.
Set operators can be the part of sub queries.
Set operators can't be used in SELECT statements containing TABLE collection
expressions.
The LONG, BLOB, CLOB, BFILE, VARRAY,or nested table are not permitted for
use in Set operators.
For update clause is not allowed with the set operators.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
52
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
53. Examples: Set Operators
Create two tables named a and b with the columns f1,f2 and id,name
respectively
Sql> create table a (f1 number, f2 varchar2(5))
Table created.
Sql> create table b (id number, name varchar2(5))
Table created.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
53
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
54. Examples: Set Operators
Insert three rows as given below in tables a and b
Sql>insert into a values( 10,'A')
1 row(s) inserted.
Sql>insert into a values( 20,'B')
row(s) inserted.
Sql>insert into a values( 30,'C')
1 row(s) inserted.
Sql>insert into b values(30,'C')
1 row(s) inserted.
Sql>insert into b values(40,'D')
1 row(s) inserted.
Sql>insert into b values(50,'E')
1 row(s) inserted.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
54
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
55. Records in table a
Sql > Select * from a
F1 F2
30 C
10 A
20 B
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
55
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Records in table b
Sql > Select * from b;
ID NAME
30 C
40 D
50 E
Examples: Set Operators
56. Example 1 : Union
Sql> select f1 from a
union
select id from b;
F1
10
20
30
40
50
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
56
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
Example 2 : Union
Sql> select id from b
union
select f1 from a;
ID
10
20
30
40
50
Column
Heading
from first
query for
display
purpose
57. Example : Union All
Sql>select f1 from a union all select id from b
F1
30
10
20
30
40
50
Note : Output with duplication, 30 is common in both tables
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
57
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
58. Example 1: Intersect
Sql>select f1 from a
intersect
select id from b;
F1
30
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
58
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
Example 2: Intersect
Sql>select id from b
intersect
select f1 from a;
ID
30
59. Example 1: Intersect
Sql> select f1 from a
minus
select id from b
F1
10
20
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
59
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
Example 2 : Intersect
Sql> select id from b
minus
select f1 from a
ID
40
50
60. Joins
SQL Joins are used to fetch records from two are more tables using a
common field.
To implement join condition minimum two tables are required
Join conditions used in where clause as given below
Note : Column name used in where condition need not to same , but data
type should be same.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
60
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
<Table_Name1> . <Column_name> = <Table_Name1> . <Column_name>
61. The Join conditions are classified as follows
• Simple Join - Equi Join
- Non Equi Join
• Self Join
• Outer Join - Left Outer Join
- Right Outer Join
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
61
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
62. Note : Consider EMP and Dept Tables
Simple Join
For the below query the output is cartesian prodcut
Sql> select * from emp,dept;
For all the records in the first table (emp) , Each and every
record in the second table (dept) will be executed.
That is , 14 x 4 Records will be in output.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
62
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
63. Simple Join
Syntax : where <table_name1>.<column_name> =
<table_name2>.<column_name>
Example 1:
Sql> select * from emp,dept where emp.deptno= dept.deptno;
Example 2:
Sql> select ename,dname from emp,dept where emp.deptno=
dept.deptno;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
63
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
64. Simple Join
Example 3: ( Simple join and Equi Join)
Sql> select ename,dname from emp,dept
where emp.deptno= dept.deptno and ename like '%S‘
Example 4: ( Common column should be specified with tablename as shown in
example below)
Sql> select ename,dname,dept.deptno from emp,dept where
emp.deptno= dept.deptno and ename like '%S'
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
64
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
65. Simple Join
Example :
Sql> select a.ename,b.ename,a.empno,b.empno from emp a,
emp b where b.mgr=a.empno;
Outer Join
Example: (Right Outer Join)
Sql> select * from emp ,dept where emp.deptno = dept.deptno(+);
Example: (Left Outer Join)
Sql> select * from emp ,dept where emp.deptno (+) = dept.deptno;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
65
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
66. A Query statement contains another query is called sub query or nested query
A subquery is used to return value(s) that will be used in the main query as a condition
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
The followings to be considered while using sub query
• Subqueries must be enclosed within parentheses.
• An ORDER BY command cannot be used in a subquery
• Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
• The BETWEEN operator cannot be used with a subquery, but the BETWEEN operator can
be used within the subquery.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
66
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
67. Basic Syntax of Subquery
SELECT column_name [, column_name ] FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ] FROM table1 [, table2 ]
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
67
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
68. Note : Consider emp table
Example : Subqueries with the SELECT Statement
SQL> SELECT * FROM emp WHERE deptno IN (SELECT deptno FROM dept WHERE
dname = ‘SALES’ or dname = ‘RESEARCH’) ;
Example: Subqueries with the INSERT Statement
SQL> INSERT INTO emp_backup SELECT * FROM emp WHERE deptno IN (SELECT
deptno FROM dept) ;
Example: Subqueries with the delete Statement
SQL> DELETE FROM emp WHERE deptno IN (SELECT deptno FROM dept WHERE
deptno=10 );
Example: Subqueries with the update Statement
SQL> UPDATE emp SET comm = SAL * 0.25 WHERE deptno IN (SELECT deptno
FROM dept WHERE deptno >30);
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
68
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
69. Sample Sub queries
SELECT ename FROM EMP WHERE sal > ( SELECT sal FROM emp WHERE empno=7566);
SELECT ename, sal, deptno, job FROM EMP WHERE job = SELECT job FROM emp WHERE empno=7369);
SELECT ename, sal, deptno FROM EMP WHERE sal IN ( SELECT MIN(sal) FROM emp GROUP BY deptno );
SELECT empno, ename, job FROM emp WHERE sal < ANY ( SELECT sal FROM emp WHERE job = 'CLERK' );
SELECT empno, ename, job FROM emp WHERE sal > ALL ( SELECT AVG(sal) FROM emp GROUP BY
deptno) ;
SELECT ename, sal, deptno FROM EMP WHERE sal IN ( SELECT MIN(sal) FROM emp GROUP BY deptno ) ;
SELECT job, AVG(sal) FROM emp GROUP BY job HAVING AVG(sal) = ( SELECT MIN(AVG(sal)) FROM emp
GROUP BY job );
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
69
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
70. correlated sub queries
SQL correlated subquery is a query which is executed one time for each record
returned by the outer query.
It is called correlated as it is a correlation between the number of times the sub
query is executed with the number of records returned by the outer query
Examples for Correlated Sub query
List the employees who have never received a comm.
SELECT ename,comm FROM emp e1 WHERE NOT EXISTS (SELECT ename
FROM emp e2 WHERE e2.empno = e1.empno AND e2,comm = null)
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
70
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
71. Using EXISTS the following query display the empno, mgr, ename of those
employees who manage other employees.
select empno, mgr, ename from emp a where exists
(select empno from emp b where b.mgr = a.empno)
Find the nth maximum salry in emp table
select * from( select ename, sal, dense_rank() over(order by sal desc) r from Emp)
where r=&n;
Note : Dense_rank () function
Example : select ename,sal, dense_rank() over ( order by sal desc) Sal_rank from emp
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
71
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
72. 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.
Eaxmple :
SQL> SELECT job,AVG(sal),Min(sal),Max(sal) FROM emp GROUP BY job HAVING
2 AVG(sal) < (SELECT MAX(AVG(sal)) FROM emp WHERE job IN
3 (SELECT job FROM emp WHERE deptno BETWEEN 10 AND 40) GROUP BY job);
JOB AVG(SAL) MIN(SAL) MAX(SAL)
--------- ---------- ---------- ----------
CLERK 1037.5 800 1300
SALESMAN 1400 1250 1600
ANALYST 3000 3000 3000
MANAGER 2758.33333 2450 2975
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
72
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
73. Difference between Nested Subquery and Correlated subquery :
Nested Query
In Nested Query, Inner query runs first, and only once. Outer query is executed with result from Inner
query. Hence, Inner query is used in execution of Outer query.
Example : Consider EMP and Dept Tables
SQL> select deptno from dept where deptno not in ( select deptno from emp );
DEPTNO
----------
40
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 : Consider EMP,Dept Tables
SQL> Select dname from dept where deptno not in ( select deptno from emp );
DNAME
--------------
OPERATIONS
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
73
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
74. Difference between Nested Query, Correlated Query and Join Operation
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
74
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Parameters Nested Query Correlated Query Join Operation
Definition In Nested query, a
query is written
inside another query
and the result of
inner query is used
in execution of outer
query.
In Correlated query, a
query is nested inside
another query and inner
query uses values from
outer
query.
Join operation is used to
combine data or rows from
two or more tables based on
a common field between
them. INNER JOIN, LEFT
JOIN, RIGHT JOIN, FULL
JOIN are different types of
Joins.
Approach Bottom up approach
i.e. Inner query runs
first, and only once.
Outer query is
executed with result
from Inner query.
Top to Down Approach
i.e. Outer query
executes first and for
every Outer query row
Inner query is executed.
It is basically cross product
satisfying a condition.
75. Parameters Nested Query Correlated Query Join Operation
Dependency Inner query execution
is not dependent on
Outer query.
Inner query is
dependent on Outer
query.
There is no Inner Query
or Outer Query. Hence,
no dependency is there.
Performance Performs better than
Correlated Query but is
slower than Join
Operation.
Performs slower than
both Nested Query and
Join operations as for
every outer query inner
query is executed.
By using joins we
maximize the calculation
burden on the database
but joins are better
optimized by the server so
the retrieval time of the
query using joins will
almost always be faster
than that of a subquery.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
75
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Difference between Nested Query, Correlated Query and Join Operation
76. Views
Views are defined using view updation rule set by Edger.F Codds
View updation rule is not fully satisfied till.
View is a Virtual table
Virtual table (view) based on the result of query statement.
Views can be created from single table
Views can be created from single table using selected columns
Views can be created from single table using selected rows
Views can be created from multiple tables
Views can be created from multiple tables using selected columns
Views can be created from multiple tables using selected rows
Data manipulation is possible in views with restrictions
The changes made in the base table(s) will be reflected in view(s)
The changes made in the views will reflected in base table with restrictions
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
76
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
77. VIEWS
General Syntax
CREATE VIEW view_name AS SELECT column1, column2, ...
FROM table_name(s) WHERE condition;
Example 1: Creating a view from emp table
SQL>create view emp_view as select * from emp;
View created
SQL> desc emp_view
Name Null? Type
---------------------------------------- -------- ----------------------------
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
77
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
78. Views
Output of Example 1:
SQL> select * from emp_view;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- - --------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
14 rows selected.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
78
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
79. Views
Example 2: Creating a view from emp table using ename, job and sal columns
SQL> create view emp_view1 as select ename, job, sal from emp;
View created.
SQL> select * from emp_view1;
ENAME JOB SAL
---------- --------- ----------
SMITH CLERK 800
ALLEN SALESMAN 1600
WARD SALESMAN 1250
JONES MANAGER 2975
MARTIN SALESMAN 1250
BLAKE MANAGER 2850
CLARK MANAGER 2450
SCOTT ANALYST 3000
KING PRESIDENT 5000
TURNER SALESMAN 1500
ADAMS CLERK 1100
JAMES CLERK 950
FORD ANALYST 3000
MILLER CLERK 1300
14 rows selected.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
79
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
80. Views
Example 3: Creating a view from emp table using selected rows
SQL> create view emp_view2 as select * from emp where deptno=10;
View created.
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
80
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
81. Views
Example 4: Creating a view from emp table using selected rows
SQL> create view emp_view3 as select ename,job from emp where sal>2000;
View created.
SQL> select * from emp_view3;
ENAME JOB
---------- ---------
JONES MANAGER
BLAKE MANAGER
CLARK MANAGER
SCOTT ANALYST
KING PRESIDENT
FORD ANALYST
6 rows selected.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
81
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
82. Views
Example 4: Creating a view from emp and dept table
SQL> create view emp_dept as select ename,dname from emp, dept where emp.deptno=dept.deptno;
View created.
ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
JAMES SALES
FORD RESEARCH
MILLER ACCOUNTING
14 rows selected.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
82
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
83. Data manipulation in Views
If view has been created from single table using all the fields the data
manipulation is possible in view and table.
• Whatever the changes made in table , that will reflected in view and vice
versa.
If view has been created from single table using selected fields including NOT
NULL and PRIMARY KEY columns , data manipulation is possible.
• Whatever the changes made in table , that will reflected in view and vice
versa.
If view has been created from single table using selected fields excluding NOT
NULL and PRIMARY key fields, data manipulation is having some restrictions
• Insertion is not possible
• Updation and Deletion is possible
If view has been created from multiple tables , data manipulation is not
possible.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
83
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
84. Data manipulation in Views
Click the following link for examples
C:UsersAdminDesktopAcademic Year 2021_2022 EVEN
Semester18CSC303J DBMSExample for Data Manipulation in View.docx
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
84
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
85. TCL Commands
Used to give / get back / control the privileges of an object by the owner
GRANT : To give access privileges of an object to other user by the owner
Syntax : GRANT [ ALL / INSERT /UPDATE /DELETE /SELECT ]
on <OBJECT_NAME> to <USER_NAME>;
Example: GRANT all on emp to scott;
REVOKE : To get back all the privileges from the user who has been granted
Syntax : REVOKE [ ALL / INSERT /UPDATE /DELETE /SELECT ]
on <OBJECT_NAME> from <USER_NAME>;
Example: REVOKE all on emp from scott;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
85
S-8 SLO-1 : Transaction Control Commands
86. TCL Commands
To control the database operation
– COMMIT: Commits a Transaction. Save the changes permanently , can’t
rollback
– ROLLBACK: Rollbacks a transaction in case of any error occurs.
– SAVEPOINT: Sets a savepoint within a transaction. Rolled back from the
specified savepoint
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
86
S-8 SLO-2 : Commit, Rollback, Savepoint
87. Set Operators
Refer slide numbers : 50 to 59
Views
Refer slide nubmbers : 76 to 83
Click the following link for examples
C:UsersAdminDesktopAcademic Year 2021_2022 EVEN
Semester18CSC303J DBMSExample for Data Manipulation
in View.docx
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
87
S-9-10 SLO-1 & SLO-2 : Lab 8: Set Operators & Views
88. PL/SQL concepts
PL/SQL is an extension of SQL.
It is a procedural language , where SQL is a non procedural language.
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database.
Block of SQL statements can be executed using PL/SQL
PL/SQL is a completely portable, high-performance transaction-processing language.
PL/SQL provides a built-in, interpreted and OS independent programming environment.
There are four type of PL/SQL blocks
Anonymous Block
Named Block
Sub Programs ( Procedures, Functions and Packages)
Triggers
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
88
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
89. Features of PL/SQL
Tightly integrated with SQL.
Extensive error checking.
Several data types.
Variety of programming structures.
Structured programming through functions and procedures.
Supports object-oriented programming.
Easy development of web applications and server pages.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
89
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
90. Structure of PL/SQL block
DECLARE
<declarations section>
BEGIN
<executable statements>
EXCEPTION
<exception handling>
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
90
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
91. Structure of PL/SQL block
Declarations
This section starts with the keyword DECLARE.
It is an optional section
Defines all variables, cursors, subprograms, and other elements to be
used in the program.
Each and every variables to be declared individually.
Executable Statements
Program execution starts from BEGIN
Between BEGIN and END is called BODY of PL/SQL block.
Nested BODY is permitted
It consists of executable statements.
Exception Handling
This is an optional section , starts with Exception
It is used to handle the logical errors during run time.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
91
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
92. Simple Example
DECLARE
message varchar2(100):= ‘Welcome to SRMIST';
BEGIN
dbms_output.put_line(message);
END;
Output :
Welcome to SRMIST
PL/SQL procedure successfully completed
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
92
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
93. Comments in PL/SQL
Double hypen (--) is Single line comment
Multiline comments enclosed by /* and */
Example
DECLARE
-- variable declaration Single line comment
message varchar2(20):= ‘Welcome to SRMIST ';
BEGIN
/* PL/SQL executable statement(s) Multi-line Comment
This Program display a Welcome note*/
dbms_output.put_line(message);
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
93
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
94. Data types in PL/SQL
All data types used in SQL can be used in PL/SQL
Numeric - Numeric values on which arithmetic operations are
performed.
Character - Alphanumeric values that represent single
characters or strings of characters.
Boolean - Logical values on which logical operations are
performed.
Datetime - Dates and times.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
94
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
96. Simple Example for variable declarations
DECLARE
a number := 10;
b number := 20;
c number (10,4);
f float;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 100.0/3.0;
dbms_output.put_line('Value of f: ' || round(f,4));
END;
Output
Value of c: 30
Value of f: 33.3333
PL/SQL procedure successfully completed.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
96
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
97. Assigning SQL query result to PL/SQL variables using INTO clause
(Consider EMP table)
DECLARE
emp_no emp.empno%type:=&emp_no;
emp_name emp.ename%type;
emp_job emp.job%type;
emp_sal emp.sal%type;
BEGIN
SELECT ename,job,sal INTO emp_name,emp_job,emp_sal
FROM emp WHERE empno = emp_no;
dbms_output.put_line
('Employee ' ||emp_name || ' working as ' || emp_job || ' and his salary is ' || emp_sal);
END;
Output
Enter value for emp_no: 7499
old 2: emp_no emp.empno%type:=&emp_no;
new 2: emp_no emp.empno%type:=7499;
Employee ALLEN working as SALESMAN his salary is 1600
PL/SQL procedure successfully completed.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
97
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
99. Conditional Statement in PL/SQL
IF - THEN statement
IF-THEN-ELSE statement
IF-THEN-ELSIF statement
Case statement
Nested IF-THEN-ELSE
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
99
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Loop Statement in PL/SQL
Basic Loop statement
While Loop statement
For loop statement
Nested Loop statement
Loop Control Statement
Exit
Continue
Goto
100. Cursors
Cursor is a private SQL workgroup area allocated temporarily
The required amount of memory space will be allocated in cursor name
A cursor holds the records written by select statement
There are two types of cursors
• Implicit Cursors
• Explicit Cursors
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
100
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
101. Implicit Cursors
Oracle create implicit cursor automatically whenever the DML statements (
INSERT, UPDATE and DELETE) are executed.
The implicit cursors are SQL cursors
The SQL cursors has four attributes
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
101
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Attribute Description
SQL%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
SQL%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or
more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.
SQL%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement returned
no rows. Otherwise, it returns FALSE.
SQL%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
102. Example for Implicit Cursors ( Consider EMP table)
DECLARE
total_rows number(2);
BEGIN
UPDATE emp SET sal = sal + 500 where comm is null ;
IF sql%notfound THEN
dbms_output.put_line('No Employee selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' Employees selected ');
END IF;
END;
Output
10 Employees selected
PL/SQL procedure successfully completed.
Note : Sal updated in EMP table for 10 employees , those commission is null
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
102
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
103. Explicit Cursors
Explicit cursors are user-defined cursors
It should be defined in the declaration section of the PL/SQL Block.
Syntax
CURSOR cursor_name IS select_statement;
The following steps to be followed for explicit cursors
Declare the cursor for initialize the memory
Open the cursor for allocating memory
Fetch the cursor values into local variables
Close the cursor for release the memory
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
103
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
104. Example for Explicit Cursors
DECLARE
emp_no emp.empno%type;
emp_name emp.ename%type;
emp_sal emp.sal%type;
CURSOR emp_cur is SELECT empno,ename,sal FROM emp;
BEGIN
OPEN emp_cur;
dbms_output.put_line(‘emp_no’ || ' ' || ‘emp_name’ || ' ' ||’emp_sal’);
LOOP
FETCH emp_cur into emp_no,emp_name,emp_sal;
EXIT WHEN emp_cur%notfound;
dbms_output.put_line(emp_no || ' ' || emp_name || ' ' || emp_sal);
END LOOP;
CLOSE emp_cur;
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
104
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Output
emp_no emp_name emp_sal
7369 SMITH 800
7499 ALLEN 1600
7521 WARD 1250
7566 JONES 2975
7654 MARTIN 1250
7698 BLAKE 2850
7782 CLARK 2450
7788 SCOTT 3000
7839 KING 5000
7844 TURNER 1500
7876 ADAMS 1100
7900 JAMES 950
7902 FORD 3000
7934 MILLER 1300
PL/SQL procedure successfully completed.
105. Cursor based Records
DECLARE
CURSOR emp_currec is SELECT empno, ename FROM emp;
emp_rec emp_currec%rowtype;
BEGIN
OPEN emp_currec;
DBMS_OUTPUT.put_line(‘Employee Number’ || ' ' || ‘Name’);
LOOP
FETCH emp_currec into emp_rec;
EXIT WHEN emp_currec%notfound;
DBMS_OUTPUT.put_line(emp_rec.empno || ' ' || emp_rec.ename);
END LOOP;
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
105
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Output
Employee Number Name
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
PL/SQL procedure successfully completed.
106. Sub Program
A program which can be called and executed in another program.
Sub program will user identification and program identification
( procedure / function name).
The program which is calling the sub program is known as calling
program or main program.
In PL/SQL there are two types of sub programs.
• Procedures
• Functions
The collection of procedure(s) and Function(s) is a PACKAGE.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
106
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
107. Procedures
Procedures do not return directly
Used to perform a specific task
General Syntax for Procedure
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS}
BEGIN
< procedure_body >
END procedure_name;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
107
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
108. Procedures
In the given syntax
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the parameters.
• IN parameter lets you pass a value to the subprogram. It is a read-only
parameter.
• OUT parameter returns a value to the calling program. Inside the
subprogram, an OUT parameter acts like a variable.
• IN OUT parameter passes an initial value to a subprogram and returns an
updated value to the caller.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
108
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
109. Example: Welcome note
CREATE OR REPLACE PROCEDURE
welcome
AS
BEGIN
dbms_output.put_line
('Welcome to SRMIST');
END;
Output
SQL> exec welcome; -- to run the
procedure
Welcome to SRMIST
PL/SQL procedure successfully completed.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
109
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
The procedure can be executed as given
below also
SQL> begin
2 welcome;
3 end;
4 /
Welcome to SRMIST
PL/SQL procedure successfully completed.
110. Example : Parameters
DECLARE
a number:=&a;
b number:=&b;
c number;
PROCEDURE findMin
(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
findMin(a, b, c);
dbms_output.put_line
(' Minimum of '|| a ||' and ' ||b || ' is :' || c);
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
110
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Output
Enter value for a: 100
old 2: a number:=&a;
New 2: a number:=100;
Enter value for b: 200
old 3: b number:=&b;
New 3: b number:=200;
Minimum of 100 and 200 is :100
PL/SQL procedure successfully completed.
111. Example : Parameters
DECLARE
a number := &a;
PROCEDURE square (x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
square(a);
dbms_output.put_line (' Square is : ' || a);
END;
Output
Enter value for a: 10
old 2: a number := &a;
new 2: a number := 10;
Square is : 100
PL/SQL procedure successfully completed.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
111
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
112. Example : Display ename from emp table
create or replace PROCEDURE get_ename IS
emp_name VARCHAR2(10);
CURSOR c1 IS SELECT ename FROM
emp;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO emp_name;
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(emp_name);
END LOOP;
CLOSE c1;
END get_ename;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
112
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Output
SQL> exec get_ename;
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
PL/SQL procedure successfully completed.
113. Example : Display employee record
CREATE OR REPLACE PROCEDURE get_emp_rec (emp_number IN emp.empno%TYPE) AS
emp_ret emp%ROWTYPE;
BEGIN
SELECT empno, ename, job, mgr, hiredate, sal, comm, deptno
INTO emp_ret
FROM emp
WHERE empno = emp_number;
DBMS_OUTPUT.PUT_LINE(emp_ret.empno||' '||emp_ret.ename||' '||
emp_ret.job||' '||emp_ret.sal);
END;
Output
SQL> exec get_emp_rec (7499);
7499 ALLEN SALESMAN 1600
PL/SQL procedure successfully completed.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
113
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
114. Functions
Function is like procedure , but it should return a value and it returns
only one value
General syntax for Function creation
CREATE [OR REPLACE] FUNCTION function_name [(parameter_name
[IN | OUT | IN OUT] type [, ...])] RETURN return_datatype {IS | AS}
BEGIN
< function_body >
END [function_name];
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
114
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
115. Functions
In the given syntax
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters.
• IN parameter lets you pass a value to the subprogram. It is a read-only parameter.
• OUT parameter returns a value to the calling program. Inside the subprogram, an
OUT parameter acts like a variable.
• IN OUT parameter passes an initial value to a subprogram and returns an updated
value to the caller.
The function must contain a return statement.
The RETURN clause specifies the 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.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
115
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
116. Creation of Function:
CREATE OR REPLACE FUNCTION
total_employee RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total FROM
emp;
RETURN total;
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
116
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Calling the Function
DECLARE
n number(2);
BEGIN
n := total_employee();
dbms_output.put_line('Total no. of
Employees: ' || n);
END;
Output
Total no. of Employees: 14
PL/SQL procedure successfully completed.
Example : To count the number of employees in emp table
117. DECLARE
a number := &a;
b number := &b;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
z:= y;
END IF;
RETURN z;
END;
BEGIN
c := findMax(a, b);
dbms_output.put_line(' Maximum of '||a||' and '||b|| ' is: ' || c);
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
117
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : Function to find the maximum of given two numbers
Output
Enter value for a: 100
old 2: a number := &a;
New 2: a number := 100;
Enter value for b: 200
old 3: b number := &b;
New 3: b number := 200;
Maximum of 100 and 200 is: 200
PL/SQL procedure successfully completed.
118. DECLARE
num number;
factorial number;
FUNCTION fact(x number) RETURN number IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= #
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
118
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Recursive Function in PL/SQL : Find the Factorial of a number
Output
Enter value for num: 5
old 17: num:= #
new 17: num:= 5;
Factorial 5 is 120
PL/SQL procedure successfully
completed.
119. Triggers
Triggers are event driven program
Not necessary to execute manually
Triggers are automatically executed when the event ocuurs
There are 12 events are there in PL/SQL
• Before insert
• Before delete
• Before update
• After insert
• After delete
• After update
The above mentioned events can be executed for each row or each statements
Apart from these triggers, Instead of triggers are also available which is used to
insert into the views which is created from more than one tables
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
119
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
120. Syntax for Trigger
CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name
[REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition)
DECLARE
<Declaration-statements>
BEGIN
<Executable-statements>
EXCEPTION
<Exception-handling-statements>
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
120
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
121. In the given syntax
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the
SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
121
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
122. create or replace trigger display_salary_changes
before delete or insert or update on emp
for each row
when (new.empno > 0)
declare
sal_diff number;
begin
sal_diff := :new.sal - :old.sal;
dbms_output.put_line('old salary: ' ||
:old.sal);
dbms_output.put_line('new salary: ' ||
:new.sal);
dbms_output.put_line('salary difference: ' ||
sal_diff);
end;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
122
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : Display the salary difference in emp table
Output
SQL> update emp set sal = 1111 where empno = 7900;
Old salary: 950
New salary: 1111
Salary difference: 161
1 row updated.
SQL> insert into emp values
(1234,'NANTHA','MANAGER',7839,'23-MAR-
83',4000,NULL,30);
Old salary:
New salary: 4000
Salary difference:
1 row created.
SQL> delete from emp where empno=1234;
1 row deleted.
123. Example for Triggers
Voters_list and polling
Click the following link
C:UsersAdminDesktopAcademic Year 2021_2022 EVEN
Semester18CSC303J DBMSBM_DBMS_PPT_18CSC303JTriggers
Example.docx
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
123
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
124. Exception Handling
Exception handling is an error handling mechanism
It will handle the logical errors during the runtime
While the occurrence of logical errors , exceptions are used to continue the program execution
instead stop the execution.
There are two types of exceptions are in PL/SQL
• System defined Exception
• No_data_found
• Login_denied
• Too_many_rows
• Value_error
• Zero_divide
• User defined Exception
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
124
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
125. Exception Handling
General Syntax
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN exception1-handling-statements
WHEN exception2 THEN exception2-handling-statements
WHEN exception3 THEN exception3-handling-statements
........
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
125
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
126. Example : System defined Exception
declare
emp_number number(10) := &empno;
emp_name varchar2(10);
begin
select ename into emp_name from emp
where empno = emp_number;
dbms_output.put_line('employee name
is ' || emp_name);
exception
when no_data_found then
dbms_output.put_line('no such
employee: ' || emp_number);
end;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
126
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Output
Enter value for empno: 7499
old 2: emp_number number(10) := &empno;
New 2: emp_number number(10) := 7499;
Employee name is ALLEN
PL/SQL procedure successfully completed.
SQL> /
Enter value for empno: 1234
old 2: emp_number number(10) := &empno;
New 2: emp_number number(10) := 1234;
No such employee: 1234
PL/SQL procedure successfully completed.
127. DECLARE
emp_name VARCHAR2(10);
emp_number NUMBER;
empno_out_of_range EXCEPTION;
BEGIN
emp_number := &empno;
IF emp_number > 9999 OR emp_number < 1000 THEN
RAISE empno_out_of_range;
ELSE
SELECT ename INTO emp_name FROM emp WHERE empno = emp_number;
DBMS_OUTPUT.PUT_LINE('Employee name is ' || emp_name);
END IF;
EXCEPTION
WHEN empno_out_of_range THEN
DBMS_OUTPUT.PUT_LINE('Employee number ' || emp_number || ' is out of range.');
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
127
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example for User defined exception With Raise command
128. Output
SQL> /
Enter value for empno: 7499
old 6: emp_number := &empno;
new 6: emp_number := 7499;
Employee name is ALLEN
PL/SQL procedure successfully completed.
SQL> /
Enter value for empno: 900
old 6: emp_number := &empno;
new 6: emp_number := 900;
Employee number 900 is out of range.
PL/SQL procedure successfully completed.
SQL> /
Enter value for empno: 10000
old 6: emp_number := &empno;
new 6: emp_number := 10000;
Employee number 10000 is out of range.
PL/SQL procedure successfully completed.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
128
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
129. DECLARE
emp_name VARCHAR2(10);
emp_number NUMBER;
empno_out_of_range EXCEPTION;
BEGIN
emp_number := &empno;
IF emp_number > 9999 OR emp_number < 1000 THEN
RAISE empno_out_of_range;
ELSE
SELECT ename INTO emp_name FROM emp
WHERE empno = emp_number;
DBMS_OUTPUT.PUT_LINE('Employee name is ' || emp_name);
END IF;
EXCEPTION
WHEN empno_out_of_range THEN
DBMS_OUTPUT.PUT_LINE('Employee number ' || emp_number ||
' is out of range.');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('Employee number does not exist');
END;
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
129
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : With user defined and System defined Exceptions
Output
SQL> /
Enter value for empno: 7499
old 6: emp_number := &empno;
new 6: emp_number := 7499;
Employee name is ALLEN
PL/SQL procedure successfully completed.
SQL> /
Enter value for empno: 1234
old 6: emp_number := &empno;
new 6: emp_number := 1234;
Employee number does not exist
PL/SQL procedure successfully completed.
SQL> /
Enter value for empno: 500
old 6: emp_number := &empno;
new 6: emp_number := 500;
Employee number 500 is out of range.
PL/SQL procedure successfully completed.
SQL> /
Enter value for empno: 20000
old 6: emp_number := &empno;
new 6: emp_number := 20000;
Employee number 20000 is out of range.
PL/SQL procedure successfully completed.
130. Query processing is the process of identifying the fessible
solution to execute the query.
There are number of ways to execute the query , from that
optimal solution will be identified and executed.
The basic steps in Query processing are
• Parsing and translation
• Optimization
• Evaluation
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
130
S-13 SLO-1 & SLO-2 : Query Processing
131. 09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
131
S-13 SLO-1 & SLO-2 : Query Processing
Query
Parser and
Translator
Relational Algebra
Expression
Optimizer
Execution Plan
Evaluation
Engine
Query Output
Data
Statistics about
Data
Data
132. Basic Steps in Query Processing
Parsing and translation
• Translate the query into its internal form.
• This is then translated into relational algebra.
• Parser checks syntax, verifies relations
Evaluation
• The query-execution engine takes a query-evaluation plan, executes that
plan, and returns the answers to the query.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
132
S-13 SLO-1 & SLO-2 : Query Processing
133. Basic steps in Query Optimization
A relational algebra expression may have many equivalent expressions
• E.g., salary75000(salary(instructor)) is equivalent to
salary(salary75000(instructor))
Each relational algebra operation can be evaluated using one of several different
algorithms
• Correspondingly, a relational-algebra expression can be evaluated in many
ways.
Annotated expression specifying detailed evaluation strategy is called an
evaluation-plan.
• E.g., can use an index on salary to find instructors with salary < 75000,
• or can perform complete relation scan and discard instructors with salary
75000
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
133
S-13 SLO-1 & SLO-2 : Query Processing
134. Basic steps in Query Optimization
Query Optimization: Amongst all equivalent evaluation plans choose
the one with lowest cost.
• Cost is estimated using statistical information from the
database catalog
e.g. number of tuples in each relation, size of tuples, etc.
In this chapter we study
• How to measure query costs
• Algorithms for evaluating relational algebra operations
• How to combine algorithms for individual operations in order to
evaluate a complete expression
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
134
S-13 SLO-1 & SLO-2 : Query Processing
135. Measures of Query Cost
Cost is generally measured as total elapsed time for answering query
• Many factors contribute to time cost
disk accesses, CPU, or even network communication
Typically disk access is the predominant cost, and is also relatively easy to
estimate. Measured by taking into account
• Number of seeks * average-seek-cost
• Number of blocks read * average-block-read-cost
• Number of blocks written * average-block-write-cost
Cost to write a block is greater than cost to read a block
• data is read back after being written to ensure that the write was
successful
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
135
S-13 SLO-1 & SLO-2 : Query Processing
136. Measures of Query Cost
For simplicity we just use the number of block transfers from disk and the number of seeks
as the cost measures
• tT – time to transfer one block
• tS – time for one seek
• Cost for b block transfers plus S seeks
b * tT + S * tS
We ignore CPU costs for simplicity
• Real systems do take CPU cost into account
We do not include cost to writing output to disk in our cost formulae
Several algorithms can reduce disk IO by using extra buffer space
• Amount of real memory available to buffer depends on other concurrent queries and OS
processes, known only during execution
We often use worst case estimates, assuming only the minimum amount of memory
needed for the operation is available
Required data may be buffer resident already, avoiding disk I/O
• But hard to take into account for cost estimation
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
136
S-13 SLO-1 & SLO-2 : Query Processing
137. Selection Operation
File scan
Algorithm A1 (linear search). Scan each file block and test all records to see
whether they satisfy the selection condition.
• Cost estimate = br block transfers + 1 seek
br denotes number of blocks containing records from relation r
• If selection is on a key attribute, can stop on finding record
cost = (br /2) block transfers + 1 seek
• Linear search can be applied regardless of
selection condition or
ordering of records in the file, or
availability of indices
Note: binary search generally does not make sense since data is not stored
consecutively
• except when there is an index available,
• and binary search requires more seeks than index search
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
137
S-13 SLO-1 & SLO-2 : Query Processing
138. Selection using Indices
Index scan – search algorithms that use an index
• selection condition must be on search-key of index.
A2 (primary index, equality on key). Retrieve a single record
that satisfies the corresponding equality condition
• Cost = (hi + 1) * (tT + tS)
A3 (primary index, equality on nonkey) Retrieve multiple
records.
• Records will be on consecutive blocks
Let b = number of blocks containing matching records
• Cost = hi * (tT + tS) + tS + tT * b
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
138
S-13 SLO-1 & SLO-2 : Query Processing
139. Selection using Indices
A4 (secondary index, equality on nonkey).
• Retrieve a single record if the search-key is a candidate key
Cost = (hi + 1) * (tT + tS)
• Retrieve multiple records if search-key is not a candidate key
each of n matching records may be on a different block
Cost = (hi + n) * (tT + tS)
oCan be very expensive!
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
139
S-13 SLO-1 & SLO-2 : Query Processing
140. Selection using Indices
Can implement selections of the form AV (r) or A V(r) by using
• a linear file scan,
• or by using indices in the following ways:
A5 (primary index, comparison). (Relation is sorted on A)
• For A V(r) use index to find first tuple v and scan relation sequentially
from there
• For AV (r) just scan relation sequentially till first tuple > v; do not use index
A6 (secondary index, comparison).
• For A V(r) use index to find first index entry v and scan index sequentially
from there, to find pointers to records.
• For AV (r) just scan leaf pages of index finding pointers to records, till first
entry > v
• In either case, retrieve records that are pointed to
requires an I/O for each record
Linear file scan may be cheaper
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
140
S-13 SLO-1 & SLO-2 : Query Processing
141. Conjunction: 1 2. . . n(r)
A7 (conjunctive selection using one index).
• Select a combination of i and algorithms A1 through A7 that results in
the least cost for i (r).
• Test other conditions on tuple after fetching it into memory buffer.
A8 (conjunctive selection using composite index).
• Use appropriate composite (multiple-key) index if available.
A9 (conjunctive selection by intersection of identifiers).
• Requires indices with record pointers.
• Use corresponding index for each condition, and take intersection of all
the obtained sets of record pointers.
• Then fetch records from file
• If some conditions do not have appropriate indices, apply test in memory.
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
141
S-13 SLO-1 & SLO-2 : Query Processing
142. Disjunction: 1 2 . . . n (r).
A10 (disjunctive selection by union of identifiers).
• Applicable if all conditions have available indices.
Otherwise use linear scan.
• Use corresponding index for each condition, and take union
of all the obtained sets of record pointers.
• Then fetch records from file
Negation: (r)
• Use linear scan on file
• If very few records satisfy , and an index is applicable to
Find satisfying records using index and fetch from file
09-05-2024
Dr.B.Muruganantham
Associate Professor / C.Tech
142
S-13 SLO-1 & SLO-2 : Query Processing