0% found this document useful (0 votes)
6 views25 pages

Advanced SQL Techniques Overview

Chapter 5 of 'Database System Concepts' covers advanced SQL topics including accessing SQL from programming languages, functions and procedures, triggers, recursive queries, and advanced aggregation features. It discusses how to use JDBC and ODBC for database communication, the concept of dynamic SQL, and the creation of functions and procedures to encapsulate business logic. Additionally, it explains the design and implementation of triggers that execute automatically in response to database modifications.

Uploaded by

hariramsathya2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

Advanced SQL Techniques Overview

Chapter 5 of 'Database System Concepts' covers advanced SQL topics including accessing SQL from programming languages, functions and procedures, triggers, recursive queries, and advanced aggregation features. It discusses how to use JDBC and ODBC for database communication, the concept of dynamic SQL, and the creation of functions and procedures to encapsulate business logic. Additionally, it explains the design and implementation of triggers that execute automatically in response to database modifications.

Uploaded by

hariramsathya2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Chapter 5: Advanced SQL

Database System Concepts, 7th Ed.


©Silberschatz, Korth and Sudarshan
See [Link] for conditions on re-use
Outline

 Accessing SQL From a Programming Language


 Functions and Procedures
 Triggers
 Recursive Queries
 Advanced Aggregation Features

Database System Concepts - 7th Edition 5.2 ©Silberschatz, Korth and Sudarshan
Accessing SQL from a Programming Language

A database programmer must have access to a general-purpose programming


language for at least two reasons
 Not all queries can be expressed in SQL, since SQL does not provide
the full expressive power of a general-purpose language.
 Non-declarative actions -- such as printing a report, interacting with a
user, or sending the results of a query to a graphical user interface --
cannot be done from within SQL.

Database System Concepts - 7th Edition 5.3 ©Silberschatz, Korth and Sudarshan
Accessing SQL from a Programming Language (Cont.)

There are two approaches to accessing SQL from a general-purpose


programming language
 A general-purpose program -- can connect to and communicate with
a database server using a collection of functions
 Embedded SQL -- provides a means by which a program can interact
with a database server.
 The SQL statements are translated at compile time into function
calls.
 At runtime, these function calls connect to the database using an
API that provides dynamic SQL facilities.

Database System Concepts - 7th Edition 5.4 ©Silberschatz, Korth and Sudarshan
JDBC

Database System Concepts - 7th Edition 5.5 ©Silberschatz, Korth and Sudarshan
JDBC
 JDBC is a Java API for communicating with database systems supporting
SQL.
 JDBC supports a variety of features for querying and updating data, and
for retrieving query results.
 JDBC also supports metadata retrieval, such as querying about relations
present in the database and the names and types of relation attributes.
 Model for communicating with the database:
 Open a connection
 Create a “statement” object
 Execute queries using the statement object to send queries and fetch
results
 Exception mechanism to handle errors

Database System Concepts - 7th Edition 5.6 ©Silberschatz, Korth and Sudarshan
JDBC Code

public static void JDBCexample(String dbid, String userid, String passwd)


{
try (Connection conn = [Link](
"jdbc:oracle:thin:@[Link]:univdb", userid, passwd);
Statement stmt = [Link]();
)
{
… Do Actual Work ….
}
catch (SQLException sqle) {
[Link]("SQLException : " + sqle);
}
}

Database System Concepts - 7th Edition 5.7 ©Silberschatz, Korth and Sudarshan
JDBC Code (Cont.)

 Update to database

try {
[Link](
"insert into instructor values('77987', 'Kim', 'Physics', 98000)");
} catch (SQLException sqle)
{
[Link]("Could not insert tuple. " + sqle);
}
 Execute query and fetch and print results
ResultSet rset = [Link](
"select dept_name, avg (salary)
from instructor
group by dept_name");
while ([Link]()) {
[Link]([Link]("dept_name") + " " +
[Link](2));
}

Database System Concepts - 7th Edition 5.9 ©Silberschatz, Korth and Sudarshan
JDBC Resources

 JDBC Basics Tutorial


• [Link]

Database System Concepts - 7th Edition 5.10 ©Silberschatz, Korth and Sudarshan
ODBC

Database System Concepts - 7th Edition 5.11 ©Silberschatz, Korth and Sudarshan
ODBC

 Open DataBase Connectivity (ODBC) standard


 standard for application program to communicate with a database
server.
 application program interface (API) to
 open a connection with a database,
 send queries and updates,
 get back results.
 Applications such as GUI, spreadsheets, etc. can use ODBC

Database System Concepts - 7th Edition 5.12 ©Silberschatz, Korth and Sudarshan
Database System Concepts - 7th Edition 5.14 ©Silberschatz, Korth and Sudarshan
Database System Concepts - 7th Edition 5.15 ©Silberschatz, Korth and Sudarshan
Dynamic SQL

 Dynamic SQL involves the creation and execution of SQL


statements at runtime.
 Dynamic SQL allows developers to generate SQL statements
dynamically based on runtime conditions or user input.
 Dynamic SQL is a good choice when the SQL statements need to
change in response to evolving needs or user inputs.

Database System Concepts - 7th Edition 5.16 ©Silberschatz, Korth and Sudarshan
Functions and Procedures

Database System Concepts - 7th Edition 5.18 ©Silberschatz, Korth and Sudarshan
Functions and Procedures

 Functions and procedures allow “business logic” to be stored in the


database and executed from SQL statements.
 These can be defined either by the procedural component of SQL or by an
external programming language such as Java, C, or C++.
 The syntax we present here is defined by the SQL standard.
 Most databases implement nonstandard versions of this syntax.

Database System Concepts - 7th Edition 5.19 ©Silberschatz, Korth and Sudarshan
 Syntax:

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name type [, …])]
// this statement is must for functions
RETURN return_datatype
{IS | AS}
BEGIN
// program code
[EXCEPTION
exception_section;
END [function_name];

Database System Concepts - 7th Edition 5.20 ©Silberschatz, Korth and Sudarshan
Declaring SQL Functions
 Define a function that, given the name of a department, returns the count of
the number of instructors in that department.
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
 The function dept_count can be used to find the department names and
budget of all departments with more that 12 instructors.
select dept_name, budget
from department
where dept_count (dept_name ) > 12

Database System Concepts - 7th Edition 5.21 ©Silberschatz, Korth and Sudarshan
SQL Procedures

 A stored procedure is a prepared SQL code that you can save, so the code
can be reused over and over again.

Syntax
CREATE PROCEDURE procedure_name
Begin
sql_statement
End;

Execute a Stored Procedure


EXEC procedure_name;

Database System Concepts - 7th Edition 5.22 ©Silberschatz, Korth and Sudarshan
 The dept_count function could instead be written as procedure:
create procedure dept_count_proc (in dept_name varchar(20),
out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_count_proc.dept_name
end
 . The keywords in and out are parameters that are expected to have
values assigned to them and parameters whose values are set in the
procedure in order to return results

Database System Concepts - 7th Edition 5.23 ©Silberschatz, Korth and Sudarshan
SQL Procedures (Cont.)

 Procedures can be invoked either from an SQL procedure or from


embedded SQL, using the call statement.
 Procedures and functions can be invoked also from dynamic SQL
 SQL allows more than one procedure with the same name, so long as the
number of arguments of the procedures with the same name is different.
 The name, along with the number of arguments, is used to identify the
procedure.

Database System Concepts - 7th Edition 5.24 ©Silberschatz, Korth and Sudarshan
Triggers

Database System Concepts - 7th Edition 5.25 ©Silberschatz, Korth and Sudarshan
Triggers

 A trigger is a statement that is executed automatically by the system as a


side effect of a modification to the database.
 To design a trigger mechanism, we must:
 Specify the conditions under which the trigger is to be executed.
 Specify the actions to be taken when the trigger executes.

Database System Concepts - 7th Edition 5.26 ©Silberschatz, Korth and Sudarshan
Database System Concepts - 7th Edition 5.27 ©Silberschatz, Korth and Sudarshan
Database System Concepts - 7th Edition 5.30 ©Silberschatz, Korth and Sudarshan

Common questions

Powered by AI

Functions in SQL return a single value and are typically used for calculations. They can be invoked from a SELECT statement. Procedures do not return values directly but can return them through OUT parameters; they can encapsulate a series of operations and are invoked using the CALL statement. The main implication for their use is that functions are suitable for operations that fit within a single expression, while procedures are better for complex transactions or operations that involve multiple steps .

Stored procedures are preferred over dynamic SQL when there is a need for repetitive execution of a predefined set of SQL statements, which allows for code reuse, better security, and performance optimizations. Stored procedures also encapsulate business logic within the database, making it easier to maintain and debug applications, as they can be executed consistently without the overhead of recompiling SQL statements each time .

The potential drawbacks of using triggers include increased complexity of the database schema, as triggers add layers of abstraction that can obscure the direct effects of SQL operations. Additionally, they can lead to performance overhead if not implemented judiciously, as triggers lead to additional processing on each record modification that meets the trigger condition. Triggers can also complicate debugging and maintenance, as they operate implicitly under the hood .

SQL, being a declarative language, lacks the full expressive power of general-purpose programming languages, which are needed for operations like interacting with a user interface, performing non-declarative actions such as printing reports, or dynamically controlling application flow based on conditions and loops. Thus, integration with a general-purpose programming language is necessary to perform these tasks not inherently supported by SQL .

The main challenges of implementing dynamic SQL include potential security risks, such as SQL injection attacks, due to the dynamic nature of query generation based on user input. This requires rigorous input validation and sanitation. Also, dynamically generated SQL statements can lead to performance bottlenecks if not carefully optimized, as they may not benefit from precompilation. Maintaining dynamic SQL can also be difficult, as it adds complexity to code readability and debugging .

JDBC, which is a Java API for communicating with database systems that support SQL, primarily serves to open a connection with the database, create a statement object, and execute queries to send and retrieve results. It also supports metadata retrieval, which allows querying about the relations present in the database and the names and types of relation attributes .

Metadata retrieval in JDBC is vital as it provides information about the underlying database structure, such as the tables, columns, and data types present. This information is crucial for applications that need to dynamically interact with the database schema or need to adapt their behavior based on the database structure, allowing for more robust, adaptable, and schema-independent database management .

Dynamic SQL allows developers to generate SQL statements at runtime, which enhances flexibility by enabling the SQL to adapt to changing conditions or user inputs. This approach is particularly useful when SQL statements need to adjust based on runtime parameters, thereby providing a more dynamic interaction model with the database .

ODBC standardizes communication between application programs and database servers by providing a standard API that applications can use to open connections, send queries, perform updates, and retrieve results irrespective of the specific database systems in use. It abstracts the database interaction layer, enabling applications to communicate with different databases without needing to be rewritten for each database type individually .

Triggers can be designed to automatically execute specified actions when certain conditions in the database are met, such as updates, inserts, or deletes. They help maintain data integrity by ensuring that dependent tables remain consistent when changes occur and can automatically enforce business rules or update audit records without manual intervention .

You might also like