SlideShare une entreprise Scribd logo
1  sur  11
SQL
1
Fall 2001 Database Systems 1
Scalar subqueries
• A scalar subquery is any expression that produces a
single value (single tuple/ single column)
• Examples:
SELECT max(amount) FROM bids
SELECT count(*) FROM items
• Scalar subqueries can be used as if they were
“constants”
– in expressions in the WHERE clause, and
– to output values in the SELECT clause
Fall 2001 Database Systems 2
Scalar subqueries
• Find items with average bid 60 or more. Print the
name of the item and the average bid.
SELECT I.name, avg(B.amount)
FROM Items I, Bids B
WHERE I.iid=B.iid
GROUP BY I.iid, I.name
HAVING avg(B.amount) > 60
SQL
2
Fall 2001 Database Systems 3
Scalar subqueries
• Find items with average bid 60 or more. Print the name
of the item and the average bid.
SELECT I.name,
FROM Items I
WHERE 60 < (SELECT avg(B.amount)
FROM bids B
WHERE B.iid = I.iid)
(SELECT avg(B2.amount)
FROM Bids B2
WHERE B2.iid = I.iid) avgAmount
Return a single
value for each tuple
Check the boolean condition
for each tuple
Fall 2001 Database Systems 4
What can’t you do with SQL
or can you?
• You are limited by the functions implemented in the
database
– Not allowed: SELECT median(salary) …
– You can add new functions to the database engine and
implement new types in a native programming language like
C,C++ (support varies)
• You can have subselects in FROM and WHERE that
return a set of values, but not in SELECT
– Allowed: SELECT * FROM (SELECT b.bid FROM bids b
WHERE b.amount>20)
– Not allowed: SELECT avg(SELECT b.amount FROM .. ) FROM
..
SQL
3
Fall 2001 Database Systems 5
What can’t you do with SQL
or can you?
• You cannot ask transitive queries
– Given a relation “emp(A,B)” for immediate managers B or A, you cannot
find all managers of a person A.
– SQL3 includes a recursive query definition construct –not implemented
in Oracle.
WITH RECURSIVE manages(emp, mgr) AS
(SELECT E1.emp, E1.mgr FROM employee E1)
UNION
(SELECT M.emp, E2.mgr FROM manages M, employee E2
WHERE M.mgr = E.id)
SELECT M2.emp
FROM manages M2
WHERE M2.emp = M2.mgr ;
Recursive queries may produce infinite loops and it is best left to programmers
with solid logic background.
Fall 2001 Database Systems 6
Embedded SQL
• You can embed SQL statements into many programming
languages
 
procedural power (loops, variables, etc.)
• The main components of embedded SQL programming:
– Regular program blocks
– SQL code
– Methods to connect to the database, invoke the SQL code and
retrieve results
– Methods to pass data from program variables to the SQL code
– Methods to retrieve data from the result of queries to program
variables
SQL
4
Fall 2001 Database Systems 7
#include <stdio.h>
exec sql include sqlca;
char user_prompt[] = "Please enter username and password: ";
char cid_prompt[] = "Please enter customer ID: ";
int main()
{
exec sql begin declare section; /* declare SQL host variables */
char cust_id[5];
char cust_name[14];
float cust_discnt; /* host var for discnt value */
char user_name[20], user_pwd[20];
exec sql end declare section;
exec sql whenever sqlerror goto report_error; /* error trap condition */
exec sql whenever not found goto notfound; /* not found condition */
exec sql connect :user_name
identified by :user_pwd; /* ORACLE format: connect */
while (prompt(cid_prompt, 1, cust_id, 4) >= 0) {
exec sql select cname,
discnt into :cust_name, :cust_discnt /* retrieve cname, discnt */
from customers where cid = :cust_id;
exec sql commit work; /* release read lock on row */
printf("CUSTOMER'S NAME IS %s AND DISCNT IS %5.1fn",
cust_name, cust_discnt); /* NOTE, (:) not used here */
continue;
Fall 2001 Database Systems 8
ProC
• Each ESQL statement starts with EXEC SQL keyword
and ends with a semicolon ;
• A pre-compiler will scan a program file and only read the
statements enclosed within EXEC SQL statements and
disregard everything else.
• SQLCA is a specific data structure for storing status
codes of all SQL operations
/* always have this for error handling*/
exec sql include sqlca ;
SQL
5
Fall 2001 Database Systems 9
Program.pc
Program.c
Fall 2001 Database Systems 10
Variables in ESQL
• All variables that will be used in an SQL statement must be declared
using an ESQL declaration and data type
exec sql begin declare section ;
VARCHAR e_name[30], username[30], passwd[30] ;
INTEGER e_ssn, e_dept_id ;
exec sql end declare section ;
• You can use almost any SQL command in ESQL as long as proper
input to these commands are provided in the form of program
variables.
• To execute any command, you must first connect to a database in
which all your tables reside.
exec sql connect :username identified by :passwd ;
SQL
6
Fall 2001 Database Systems 11
Executing SQL commands
• Suppose we want to find the name of an employee given his/her
SSN (input by the user of the program):
exec sql select name, dept_id into :e_name, :e_dept_id
from employee
where ssn = :e_ssn ;
Read the value of the variable “e_ssn” and execute the SQL
statement using this value, store the returned values of columns
“name” and “dept_id” in the program variables “e_name” and
“e_dept_id”.
Compare the above query with the expression below. What is the difference?
exec sql select name, dept_id
from employee where ssn = e_ssn ;
Program variables are
preceded by “:”
Fall 2001 Database Systems 12
Dealing with Strings
• There is a mismatch between the definition of a string in Oracle and
in C/C++.
– In C, the end of a string is identified by the null character ‘0’. Hence,
“Sibel” would be stored as characters ‘S’,’i’,’b’,’e’,’l’,’0’.
– In Oracle, the length of a string is stored together with the string and
there is no special end of string character.
– If you convert a data string from Oracle to C, you must pad it with ‘0’
manually!
• The data type VARCHAR e_name[30] is translated by the pre-
compiler to the following structure:
struct {
unsigned short len
unsigned char arr[30]
} e_name ;
SQL
7
Fall 2001 Database Systems 13
More on strings
Putting the pieces together:
strcpy(username.arr, “Sibel Adali”) ;
username.len = strlen(“Sibel Adali”) ;
strcpy(passwd.arr, “tweety-bird”) ;
passwd.len = strlen(“tweety-bird”) ;
exec sql connect :username identified by :passwd ;
scanf(“%d”, &e_ssn) ;
exec sql select name, dept_id into :e_name, :e_dept_id
from employee where ssn = :e_ssn ;
e_name.arr[e_name.len] = ‘0’ ; /* so can use string in C*/
printf(“%s”, e_name.arr) ;
exec sql commit work ; /* make any changes permanent */
exec sql disconnect ; /* disconnect from the database */
Fall 2001 Database Systems 14
ESQL - Cursors
• When a select statement returns a set of tuples, then the
tuples (rows) can only be retrieved one by one.
– programming language variables can contain only one
value at a time
– this is sometimes called an impedance mismatch
• Cursor operations
– declare a cursor using a regular SQL query (no “into”).
exec sql declare emps_dept cursor for
select ssn, name from employee
where dept_id = :e_dept_id ;
SQL
8
Fall 2001 Database Systems 15
ESQL – More Cursors
• More cursor operations
– open a cursor: means the corresponding SQL query is
executed, the results are written to a file (or a data
structure) and the cursor is pointing to the first row.
exec sql open emps_dept ;
– read the current row pointed to by the cursor using
“fetch”. At the end of fetch, the cursor is moved to point
to the next tuple.
exec sql fetch emps_dept into :e_ssn, :e_name ;
Fall 2001 Database Systems 16
How do we know when we
reach the end of a cursor?
• Each SQL statement executed in a program produces
a status code that can be retrieved from the SQL
Communication Area (SQLCA) variables.
• Check the “sqlcode” to see if the end of a cursor is
reached (its expected value depends on the system).
if (sqlca.sqlcode == -1) { … }
• Error handling statements
exec sql whenever sqlerror
{continue, stop, goto label, call function}
– exec sql whenever is a trap condition, it hold for all
exec sql statements unless a new trap condition
overrides the current one.
SQL
9
Fall 2001 Database Systems 17
Transactions
• The most common ESQL statements are SELECT, INSERT
INTO, and UPDATE statements.
• A transaction in a program starts with the first read or write to
a database (not with connect) and ends when either one of
the following commands is executed
– exec sql commit work ; /* changes to the database
are made permanent */
– exec sql rollback work ; /* restore all tuples to their
original values */
• If a program did not complete correctly, then changes can be
undone to restore a consistent state.
Fall 2001 Database Systems 18
Dynamic SQL
• In Dynamic SQL, embedded SQL statements are created on the fly
using strings!
– these strings are fed to an exec sql statement
exec sql execute immediate :sql_string
• Since dynamic SQL statements are not known to the pre-compiler at
compile time, they must be optimized at run time!
• Create a query once using a prepare statement and run it multiple
times using the execute statement.
strcopy(sqltext.arr, “delete from employee where ssn = ?”) ;
sqltext.len=str.len(sqltext.arr) ;
exec sql prepare del_emp from :sqltext ;
exec sql execute del_emp using :cust_id ;
SQL
10
Fall 2001 Database Systems 19
SQLDA
• When we execute a dynamic SQL statement, we do not know which
columns will be returned and how many columns will be returned.
• The SQLDA descriptor definition allows us to find the number of
columns and the value for each column.
exec sql include sqlda ;
exec sql declare sel_curs cursor for sel_emps ;
exec sql prepare sel_emps from :sqltext ;
exec sql describe sel_emps into sqlda ;
exec sql open sel_curs ;
exec sql fetch sel_curs using descriptor sqlda ;
Fall 2001 Database Systems 20
JDBC – Dynamic SQL
• Driver is a piece of software that enables
communication between a program and a
database system (DMBS specific packages).
• It implements a number of main classes:
– Connection (opening, closing, committing)
– Statement (executing queries)
– Result set (going through cursors, extracting
information)
SQL
11
Fall 2001 Database Systems 21
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
class Employee
{
public static void main (String args []) throws SQLException
{//Set your user name and the password
String userName = "dummy" ;
String passWord = "dummy" ;
// Load the Oracle JDBC driver
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
Connection conn =
DriverManager.getConnection
("jdbc:oracle:thin:@vcmr-57.server.rpi.edu:1521:ora8",
userName,passWord);
Fall 2001 Database Systems 22
// Create a statement which will return a cursor that will allow
you to
// scroll the result set using both "next" and "previous"
methods
Statement stmt = conn.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rset = stmt.executeQuery
("SELECT name, oid FROM items ");
// Iterate through the result and print the item names
while (rset.next ()) {
//Get item name, which is the first column
System.out.println (rset.getString (1));
PreparedStatement pstmt = conn.prepareStatement
("SELECT name FROM owners WHERE oid = ?") ;
//Feed the owner id retrieved from rset into pstmt
pstmt.setInt(1, rset.getInt (2));
ResultSet dset = pstmt.executeQuery() ;
if (dset.next())
System.out.println(dset.getString (1));
} } }

Contenu connexe

Tendances

TSQL Coding Guidelines
TSQL Coding GuidelinesTSQL Coding Guidelines
TSQL Coding GuidelinesChris Adkin
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQLrehaniltifat
 
11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilarrehaniltifat
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsSalman Memon
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals INick Buytaert
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseSalman Memon
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...rehaniltifat
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 

Tendances (20)

ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
Pl sql-ch3
Pl sql-ch3Pl sql-ch3
Pl sql-ch3
 
TSQL Coding Guidelines
TSQL Coding GuidelinesTSQL Coding Guidelines
TSQL Coding Guidelines
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
Chapter8 pl sql
Chapter8 pl sqlChapter8 pl sql
Chapter8 pl sql
 
11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar
 
plsql Les08
plsql Les08 plsql Les08
plsql Les08
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
Plsql guide 2
Plsql guide 2Plsql guide 2
Plsql guide 2
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Pl sql chapter 1
Pl sql chapter 1Pl sql chapter 1
Pl sql chapter 1
 
Plsql
PlsqlPlsql
Plsql
 
Pl sql-ch2
Pl sql-ch2Pl sql-ch2
Pl sql-ch2
 
Database Objects
Database ObjectsDatabase Objects
Database Objects
 

En vedette

[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02AnusAhmad
 

En vedette (6)

[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02
 

Similaire à [Www.pkbulk.blogspot.com]dbms07

Chapter 14 sql injection
Chapter 14 sql injectionChapter 14 sql injection
Chapter 14 sql injectionnewbie2019
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJDharita Chokshi
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...TAISEEREISA
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlChema Alonso
 
MS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And ProceduresMS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And Proceduressqlserver content
 
MS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And ProceduresMS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And Proceduressqlserver content
 
Deep Dive of ADBMS Migration to Apache Spark—Use Cases Sharing
Deep Dive of ADBMS Migration to Apache Spark—Use Cases SharingDeep Dive of ADBMS Migration to Apache Spark—Use Cases Sharing
Deep Dive of ADBMS Migration to Apache Spark—Use Cases SharingDatabricks
 

Similaire à [Www.pkbulk.blogspot.com]dbms07 (20)

Sql injection
Sql injectionSql injection
Sql injection
 
Chapter 14 sql injection
Chapter 14 sql injectionChapter 14 sql injection
Chapter 14 sql injection
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
embedded-static-&dynamic
embedded-static-&dynamicembedded-static-&dynamic
embedded-static-&dynamic
 
Sql injection
Sql injectionSql injection
Sql injection
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)Sql
 
Erik_van_Roon.pdf
Erik_van_Roon.pdfErik_van_Roon.pdf
Erik_van_Roon.pdf
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 
MS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And ProceduresMS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And Procedures
 
MS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And ProceduresMS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And Procedures
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Deep Dive of ADBMS Migration to Apache Spark—Use Cases Sharing
Deep Dive of ADBMS Migration to Apache Spark—Use Cases SharingDeep Dive of ADBMS Migration to Apache Spark—Use Cases Sharing
Deep Dive of ADBMS Migration to Apache Spark—Use Cases Sharing
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Beg sql
Beg sqlBeg sql
Beg sql
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 

Plus de AnusAhmad

[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexingAnusAhmad
 
[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13AnusAhmad
 
9. java server faces
9. java server faces9. java server faces
9. java server facesAnusAhmad
 
8. java script
8. java script8. java script
8. java scriptAnusAhmad
 
2. http, html
2. http, html2. http, html
2. http, htmlAnusAhmad
 
6. hibernate
6. hibernate6. hibernate
6. hibernateAnusAhmad
 

Plus de AnusAhmad (15)

[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing
 
[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11
 
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10
 
[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13
 
9. java server faces
9. java server faces9. java server faces
9. java server faces
 
8. java script
8. java script8. java script
8. java script
 
7. struts
7. struts7. struts
7. struts
 
5. servlets
5. servlets5. servlets
5. servlets
 
4. jsp
4. jsp4. jsp
4. jsp
 
3. applets
3. applets3. applets
3. applets
 
2. http, html
2. http, html2. http, html
2. http, html
 
1. intro
1. intro1. intro
1. intro
 
6. hibernate
6. hibernate6. hibernate
6. hibernate
 

Dernier

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 

Dernier (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 

[Www.pkbulk.blogspot.com]dbms07

  • 1. SQL 1 Fall 2001 Database Systems 1 Scalar subqueries • A scalar subquery is any expression that produces a single value (single tuple/ single column) • Examples: SELECT max(amount) FROM bids SELECT count(*) FROM items • Scalar subqueries can be used as if they were “constants” – in expressions in the WHERE clause, and – to output values in the SELECT clause Fall 2001 Database Systems 2 Scalar subqueries • Find items with average bid 60 or more. Print the name of the item and the average bid. SELECT I.name, avg(B.amount) FROM Items I, Bids B WHERE I.iid=B.iid GROUP BY I.iid, I.name HAVING avg(B.amount) > 60
  • 2. SQL 2 Fall 2001 Database Systems 3 Scalar subqueries • Find items with average bid 60 or more. Print the name of the item and the average bid. SELECT I.name, FROM Items I WHERE 60 < (SELECT avg(B.amount) FROM bids B WHERE B.iid = I.iid) (SELECT avg(B2.amount) FROM Bids B2 WHERE B2.iid = I.iid) avgAmount Return a single value for each tuple Check the boolean condition for each tuple Fall 2001 Database Systems 4 What can’t you do with SQL or can you? • You are limited by the functions implemented in the database – Not allowed: SELECT median(salary) … – You can add new functions to the database engine and implement new types in a native programming language like C,C++ (support varies) • You can have subselects in FROM and WHERE that return a set of values, but not in SELECT – Allowed: SELECT * FROM (SELECT b.bid FROM bids b WHERE b.amount>20) – Not allowed: SELECT avg(SELECT b.amount FROM .. ) FROM ..
  • 3. SQL 3 Fall 2001 Database Systems 5 What can’t you do with SQL or can you? • You cannot ask transitive queries – Given a relation “emp(A,B)” for immediate managers B or A, you cannot find all managers of a person A. – SQL3 includes a recursive query definition construct –not implemented in Oracle. WITH RECURSIVE manages(emp, mgr) AS (SELECT E1.emp, E1.mgr FROM employee E1) UNION (SELECT M.emp, E2.mgr FROM manages M, employee E2 WHERE M.mgr = E.id) SELECT M2.emp FROM manages M2 WHERE M2.emp = M2.mgr ; Recursive queries may produce infinite loops and it is best left to programmers with solid logic background. Fall 2001 Database Systems 6 Embedded SQL • You can embed SQL statements into many programming languages   procedural power (loops, variables, etc.) • The main components of embedded SQL programming: – Regular program blocks – SQL code – Methods to connect to the database, invoke the SQL code and retrieve results – Methods to pass data from program variables to the SQL code – Methods to retrieve data from the result of queries to program variables
  • 4. SQL 4 Fall 2001 Database Systems 7 #include <stdio.h> exec sql include sqlca; char user_prompt[] = "Please enter username and password: "; char cid_prompt[] = "Please enter customer ID: "; int main() { exec sql begin declare section; /* declare SQL host variables */ char cust_id[5]; char cust_name[14]; float cust_discnt; /* host var for discnt value */ char user_name[20], user_pwd[20]; exec sql end declare section; exec sql whenever sqlerror goto report_error; /* error trap condition */ exec sql whenever not found goto notfound; /* not found condition */ exec sql connect :user_name identified by :user_pwd; /* ORACLE format: connect */ while (prompt(cid_prompt, 1, cust_id, 4) >= 0) { exec sql select cname, discnt into :cust_name, :cust_discnt /* retrieve cname, discnt */ from customers where cid = :cust_id; exec sql commit work; /* release read lock on row */ printf("CUSTOMER'S NAME IS %s AND DISCNT IS %5.1fn", cust_name, cust_discnt); /* NOTE, (:) not used here */ continue; Fall 2001 Database Systems 8 ProC • Each ESQL statement starts with EXEC SQL keyword and ends with a semicolon ; • A pre-compiler will scan a program file and only read the statements enclosed within EXEC SQL statements and disregard everything else. • SQLCA is a specific data structure for storing status codes of all SQL operations /* always have this for error handling*/ exec sql include sqlca ;
  • 5. SQL 5 Fall 2001 Database Systems 9 Program.pc Program.c Fall 2001 Database Systems 10 Variables in ESQL • All variables that will be used in an SQL statement must be declared using an ESQL declaration and data type exec sql begin declare section ; VARCHAR e_name[30], username[30], passwd[30] ; INTEGER e_ssn, e_dept_id ; exec sql end declare section ; • You can use almost any SQL command in ESQL as long as proper input to these commands are provided in the form of program variables. • To execute any command, you must first connect to a database in which all your tables reside. exec sql connect :username identified by :passwd ;
  • 6. SQL 6 Fall 2001 Database Systems 11 Executing SQL commands • Suppose we want to find the name of an employee given his/her SSN (input by the user of the program): exec sql select name, dept_id into :e_name, :e_dept_id from employee where ssn = :e_ssn ; Read the value of the variable “e_ssn” and execute the SQL statement using this value, store the returned values of columns “name” and “dept_id” in the program variables “e_name” and “e_dept_id”. Compare the above query with the expression below. What is the difference? exec sql select name, dept_id from employee where ssn = e_ssn ; Program variables are preceded by “:” Fall 2001 Database Systems 12 Dealing with Strings • There is a mismatch between the definition of a string in Oracle and in C/C++. – In C, the end of a string is identified by the null character ‘0’. Hence, “Sibel” would be stored as characters ‘S’,’i’,’b’,’e’,’l’,’0’. – In Oracle, the length of a string is stored together with the string and there is no special end of string character. – If you convert a data string from Oracle to C, you must pad it with ‘0’ manually! • The data type VARCHAR e_name[30] is translated by the pre- compiler to the following structure: struct { unsigned short len unsigned char arr[30] } e_name ;
  • 7. SQL 7 Fall 2001 Database Systems 13 More on strings Putting the pieces together: strcpy(username.arr, “Sibel Adali”) ; username.len = strlen(“Sibel Adali”) ; strcpy(passwd.arr, “tweety-bird”) ; passwd.len = strlen(“tweety-bird”) ; exec sql connect :username identified by :passwd ; scanf(“%d”, &e_ssn) ; exec sql select name, dept_id into :e_name, :e_dept_id from employee where ssn = :e_ssn ; e_name.arr[e_name.len] = ‘0’ ; /* so can use string in C*/ printf(“%s”, e_name.arr) ; exec sql commit work ; /* make any changes permanent */ exec sql disconnect ; /* disconnect from the database */ Fall 2001 Database Systems 14 ESQL - Cursors • When a select statement returns a set of tuples, then the tuples (rows) can only be retrieved one by one. – programming language variables can contain only one value at a time – this is sometimes called an impedance mismatch • Cursor operations – declare a cursor using a regular SQL query (no “into”). exec sql declare emps_dept cursor for select ssn, name from employee where dept_id = :e_dept_id ;
  • 8. SQL 8 Fall 2001 Database Systems 15 ESQL – More Cursors • More cursor operations – open a cursor: means the corresponding SQL query is executed, the results are written to a file (or a data structure) and the cursor is pointing to the first row. exec sql open emps_dept ; – read the current row pointed to by the cursor using “fetch”. At the end of fetch, the cursor is moved to point to the next tuple. exec sql fetch emps_dept into :e_ssn, :e_name ; Fall 2001 Database Systems 16 How do we know when we reach the end of a cursor? • Each SQL statement executed in a program produces a status code that can be retrieved from the SQL Communication Area (SQLCA) variables. • Check the “sqlcode” to see if the end of a cursor is reached (its expected value depends on the system). if (sqlca.sqlcode == -1) { … } • Error handling statements exec sql whenever sqlerror {continue, stop, goto label, call function} – exec sql whenever is a trap condition, it hold for all exec sql statements unless a new trap condition overrides the current one.
  • 9. SQL 9 Fall 2001 Database Systems 17 Transactions • The most common ESQL statements are SELECT, INSERT INTO, and UPDATE statements. • A transaction in a program starts with the first read or write to a database (not with connect) and ends when either one of the following commands is executed – exec sql commit work ; /* changes to the database are made permanent */ – exec sql rollback work ; /* restore all tuples to their original values */ • If a program did not complete correctly, then changes can be undone to restore a consistent state. Fall 2001 Database Systems 18 Dynamic SQL • In Dynamic SQL, embedded SQL statements are created on the fly using strings! – these strings are fed to an exec sql statement exec sql execute immediate :sql_string • Since dynamic SQL statements are not known to the pre-compiler at compile time, they must be optimized at run time! • Create a query once using a prepare statement and run it multiple times using the execute statement. strcopy(sqltext.arr, “delete from employee where ssn = ?”) ; sqltext.len=str.len(sqltext.arr) ; exec sql prepare del_emp from :sqltext ; exec sql execute del_emp using :cust_id ;
  • 10. SQL 10 Fall 2001 Database Systems 19 SQLDA • When we execute a dynamic SQL statement, we do not know which columns will be returned and how many columns will be returned. • The SQLDA descriptor definition allows us to find the number of columns and the value for each column. exec sql include sqlda ; exec sql declare sel_curs cursor for sel_emps ; exec sql prepare sel_emps from :sqltext ; exec sql describe sel_emps into sqlda ; exec sql open sel_curs ; exec sql fetch sel_curs using descriptor sqlda ; Fall 2001 Database Systems 20 JDBC – Dynamic SQL • Driver is a piece of software that enables communication between a program and a database system (DMBS specific packages). • It implements a number of main classes: – Connection (opening, closing, committing) – Statement (executing queries) – Result set (going through cursors, extracting information)
  • 11. SQL 11 Fall 2001 Database Systems 21 import java.sql.*; import oracle.sql.*; import oracle.jdbc.driver.*; class Employee { public static void main (String args []) throws SQLException {//Set your user name and the password String userName = "dummy" ; String passWord = "dummy" ; // Load the Oracle JDBC driver DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@vcmr-57.server.rpi.edu:1521:ora8", userName,passWord); Fall 2001 Database Systems 22 // Create a statement which will return a cursor that will allow you to // scroll the result set using both "next" and "previous" methods Statement stmt = conn.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rset = stmt.executeQuery ("SELECT name, oid FROM items "); // Iterate through the result and print the item names while (rset.next ()) { //Get item name, which is the first column System.out.println (rset.getString (1)); PreparedStatement pstmt = conn.prepareStatement ("SELECT name FROM owners WHERE oid = ?") ; //Feed the owner id retrieved from rset into pstmt pstmt.setInt(1, rset.getInt (2)); ResultSet dset = pstmt.executeQuery() ; if (dset.next()) System.out.println(dset.getString (1)); } } }