Advanced SQLSQL المتقدمة

الشريحة 1 من 23

مقدمة الفصل

تفاصيل المصدرالفصل 2 · الشريحة ⁦2⁩
المصدر
الفصل 2 · الشريحة ⁦2⁩

Accessing SQL from a programming languageSQL من لغة برمجة

  • Slide 4 (Accessing SQL from a Programming Language) draws the DBMS between the database and its three kinds of clients: developer, user and app.

Why a general-purpose language is needed (slide 5)

  • Not all queries can be expressed in SQL — it does not provide the full expressive power of a general-purpose language.
  • Non-declarative actions — printing a report, interacting with a user, sending query results to a GUI — cannot be done from within SQL.

An application program makes calls to (slide 6)

  1. 1

    Connect with the database server

  2. 2

    Send SQL commands to the database server

  3. 3

    Fetch tuples of result one-by-one into program variables

Tools

  • ODBC: C, C++, C#, Visual Basic
  • ADO.NET (on top of ODBC)
  • JDBC: Java
  • Embedded SQL

A program must send the results of a query to a graphical user interface. Why can't this be done in SQL alone?

تفاصيل المصدرالفصل 2 · الشرائح ⁦4–6⁩
المصدر
الفصل 2 · الشرائح ⁦4–6⁩

ODBCODBC

Open Database Connectivity (ODBC)
Standard for an application program to communicate with a database server: open a connection with a database, send queries and updates, get back results. Applications such as GUI, spreadsheets, etc. can use ODBC.
تفاصيل المصدرالفصل 2 · الشريحة ⁦7⁩
المصدر
الفصل 2 · الشريحة ⁦7⁩

JDBC: model and codeJDBC

JDBC
A Java API for communicating with database systems supporting SQL; supports querying and updating data, retrieving query results, and metadata retrieval.

Model for communicating with the database (slide 8)

  1. 1

    Open a connection

  2. 2

    Create a "statement" object

  3. 3

    Execute queries using the Statement object to send queries and fetch results

  4. 4

    Exception mechanism to handle errors

من الشرائح

  • Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@db.yale.edu:2000:univdb", uid, pwd); Statement stmt = conn.createStatement(); — resources opened in "try ( … )" are automatically closed at the end of the try block.
  • stmt.executeUpdate("insert into INSTRUCTOR values('77987', 'Kim', 'Physics', 98000)");
  • ResultSet rset = stmt.executeQuery("select dept_name, avg (salary) from INSTRUCTOR group by dept_name"); while (rset.next()) { … }

Which JDBC call should run "select dept_name, avg (salary) from INSTRUCTOR group by dept_name" and give back the rows?

تفاصيل المصدرالفصل 2 · الشرائح ⁦8–11⁩
المصدر
الفصل 2 · الشرائح ⁦8–11⁩

Nulls and prepared statementsالقيم الفارغة والجمل المعدّة

JDBC

  • Result fields can be read by column name, e.g. rset.getString("dept_name"), or by position.
  • Dealing with null values: int a = rset.getInt("a"); if (rset.wasNull()) … "Got null value".

من الشرائح

  • PreparedStatement pStmt = conn.prepareStatement("insert into INSTRUCTOR values(?,?,?,?)"); pStmt.setString(1, "88877"); pStmt.setString(2, "Perry"); pStmt.setString(3, "Finance"); pStmt.setInt(4, 125000); pStmt.executeUpdate();
WARNING (slide 13)
Always use preparedStatements while reading input from the user and adding it to a query. NEVER create a query by concatenating strings — what if name is "D'Souza"?

A web form lets a user type a name that is inserted into INSTRUCTOR. What is required to do this safely?

تفاصيل المصدرالفصل 2 · الشرائح ⁦12–13⁩
المصدر
الفصل 2 · الشرائح ⁦12–13⁩

Metadata featuresالبيانات الوصفية

JDBC

ResultSet

  • Holds the actual data (rows)

ResultSetMetaData

  • Provides the structural data (metadata) about those records
  • Structure, types and properties of the columns
  • getColumnCount(), getColumnName(i), getColumnTypeName(i)

DatabaseMetaData (dbmd = conn.getMetaData())

  • getColumns(…) — one row for each column (COLUMN_NAME, TYPE_NAME).
  • getTables(…) — one row for each table (TABLE_NAME, TABLE_CAT, TABLE_TYPE).
  • getPrimaryKeys("", "", tableName) — KEY_SEQ gives the position of the attribute in the primary key (needed when the key has multiple attributes).
  • Arguments: null = all catalogs/schemas; "" = current catalog/schema; "%" = same meaning as the SQL like clause.
تفاصيل المصدرالفصل 2 · الشرائح ⁦14–17⁩
المصدر
الفصل 2 · الشرائح ⁦14–17⁩

Transaction control in JDBCالتحكم في المعاملات

Automatic commit (default)
Each SQL statement is treated as a separate transaction: it is executed and committed automatically.
  1. setAutoCommit(false)

    Turn off automatic commit for a connection: statements are not automatically committed — transactions are managed manually.

  2. conn.commit()

    Save the changes to the database.

  3. conn.rollback()

    Discard the changes made during the transaction.

  4. setAutoCommit(true)

    Turn automatic commit back on.

A program must transfer money with two updates that succeed or fail together. Which JDBC sequence is correct?

تفاصيل المصدرالفصل 2 · الشرائح ⁦18–19⁩
المصدر
الفصل 2 · الشرائح ⁦18–19⁩

Embedded SQLSQL المضمّنة

Embedded SQL
Including SQL statements directly within a program written in a high-level programming language like C, C++, COBOL, or Java.

من الشرائح

  • EXEC SQL BEGIN DECLARE SECTION; char name[50]; int employee_id; EXEC SQL END DECLARE SECTION;
  • EXEC SQL CONNECT TO database_name; EXEC SQL INSERT INTO employees (id, name) VALUES (:employee_id, :name); EXEC SQL COMMIT; EXEC SQL DISCONNECT;
تفاصيل المصدرالفصل 2 · الشرائح ⁦21–22⁩
المصدر
الفصل 2 · الشرائح ⁦21–22⁩

Functions in SQLالدوال في SQL

Functions and procedures

  • SQL:1999 introduced support for functions and procedures, written in SQL or in an external language (e.g., C, Java).
  • SQL:1999 imperative constructs: loops, if-then-else, assignment.

من الشرائح

  • 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
  • select dept_name, budget from department where dept_count (dept_name) > 12
begin … end
Compound statement; may contain multiple SQL statements.
returns
Indicates the variable-type that is returned (e.g., integer).
return
Specifies the values that are returned as the result of invoking the function.
Table functions
SQL:2003 added functions that return a relation as a result: select * from table (instructor_of ('Music')).

In create function dept_count (dept_name varchar(20)) returns integer … return d_count;, what does "returns integer" indicate?

تفاصيل المصدرالفصل 2 · الشرائح ⁦24–27⁩
المصدر
الفصل 2 · الشرائح ⁦24–27⁩

Stored proceduresالإجراءات المخزّنة

Functions and procedures

Stored procedure
A precompiled SQL code that can be saved and reused; can have parameters; provides code reusability, improved performance, and database security.

من الشرائح

  • 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
  • declare d_count integer; call dept_count_proc('Physics', d_count);
  • MySQL: CALL procedure_name('value1', 'value2'); DROP PROCEDURE procedure_name;
Name overloading (SQL:1999)
More than one function/procedure of the same name, as long as the number of arguments differ, or at least the types of the arguments differ.

Two procedures are both named dept_count_proc. When does SQL:1999 allow this?

تفاصيل المصدرالفصل 2 · الشرائح ⁦28–30⁩
المصدر
الفصل 2 · الشرائح ⁦28–30⁩

Language constructs and external routinesالبنى اللغوية والروتينات الخارجية

Functions and procedures

Language constructs (slides 31–33)

  • while … do … end while
  • repeat … until … end repeat
  • for r as <query> do … end for
  • if-then-else
  • case
External language routines (slide 35)

Benefits

  • More efficient for many operations
  • More expressive power: computations that cannot be carried out in SQL

Drawbacks

  • Code may need to be loaded and executed in the database system's address space
  • Risk of accidental corruption of database structures
  • Security risk: users access to unauthorized data

Dealing with security (slide 36)

  • Sandbox techniques: a safe language like Java, which cannot be used to access/damage other parts of the database code.
  • A separate process with no access to the database process' memory; parameters and results via inter-process communication.
  • Both have performance overheads.

Which statement about external language routines is correct?

تفاصيل المصدرالفصل 2 · الشرائح ⁦31–36⁩
المصدر
الفصل 2 · الشرائح ⁦31–36⁩

Triggersالمشغّلات

Trigger
A stored procedure in a database that automatically invokes whenever a special event in the database occurs — e.g., when a row is inserted into a specified table or when specific table columns are updated.
Triggers vs stored procedures (slide 38)
TriggerStored procedure
How it runsAutomatically, when a special event occursCalled (e.g., with call)
Manual invocationCannot be manually invoked or executedYes
ParametersNo chance to receive parametersCan have parameters
Commit / rollback insideA transaction cannot be committed or rolled back inside a triggerلا تذكر الشرائح شيئًا هنا.

Syntax (slides 39–40)

  1. create trigger

    [trigger_name]

  2. before | after

    When the trigger will be executed

  3. insert | update | delete

    The DML operation

  4. on

    [table_name]: the table associated with the trigger

  5. for each row

    A row-level trigger: executed for each affected row

  6. BEGIN … END

    Trigger body: the operation performed as the trigger is fired

Which statement is true of a trigger but NOT of a stored procedure?

تفاصيل المصدرالفصل 2 · الشرائح ⁦38–40⁩
المصدر
الفصل 2 · الشرائح ⁦38–40⁩

A trigger example; statement-level triggers; when not to use triggersمثال ومتى نتجنبها

من الشرائح

  • CREATE TRIGGER update_last_updated BEFORE INSERT ON employee FOR EACH ROW BEGIN SET NEW.last_updated = NOW(); END;
  • INSERT INTO employee (employee_id, employee_name, hire_date) VALUES (1, 'John Smith', '2023-09-03');
Statement level triggers
A single action for all rows affected by a transaction: use for each statement instead of for each row; can be more efficient when SQL statements update a large number of rows.
  1. 1Performance concernsComplex logic or a large number of rows.
  2. 2Cross-database or cross-server operationsTriggers typically operate within a single database.
  3. 3Infinite loop potentialA trigger on Table A updates Table B, and Table B has a trigger that updates Table A.

A trigger on Table A updates Table B, and a trigger on Table B updates Table A. Which reason not to use triggers does this illustrate?

تفاصيل المصدرالفصل 2 · الشرائح ⁦41–45⁩
المصدر
الفصل 2 · الشرائح ⁦41–45⁩

Recursion in SQLالعودية في SQL

Recursive queries

  • SQL:1999 permits recursive view definition: convenient for hierarchical data (organizational structure, menu structure, tasks with sub-tasks).
  • Recursion uses a WITH statement, called common table expression (CTE).
  • It needs an initialization (base) query that seeds the recursion; when to stop is decided in the WHERE clause of the iterative query.
Syntax
WITH R AS (<base query> UNION ALL <recursive query involving R>)
Parent_Child (slide 48)
ParentChild
AliceCarol
BobCarol
CarolDave
CarolGeorge
DaveMary
EveMary
MaryFrank

المسألة

Find the ancestors of Frank (slide 49).

In WITH R AS (<base query> UNION ALL <recursive query involving R>), what decides when the recursion stops?

تفاصيل المصدرالفصل 2 · الشرائح ⁦47–49⁩
المصدر
الفصل 2 · الشرائح ⁦47–49⁩

Transitive closure and the fixed pointالإغلاق المتعدي والنقطة الثابتة

Recursive queries

Transitive closure
rec_prereq finds which courses are a prerequisite, whether directly or indirectly, for a specific course (CS-347); this view is called the transitive closure of the prereq relation.
Fixed-point computation for CS-347 (slide 52)
IterationTuples in c1
0لا تذكر الشرائح شيئًا هنا.
1(CS-319)
2(CS-319), (CS-315), (CS-101)
3(CS-319), (CS-315), (CS-101), (CS-190)
4(CS-319), (CS-315), (CS-101), (CS-190)
5done
  • Recursive views make it possible to write queries, such as transitive closure, that cannot be written without recursion or iteration: a non-recursive non-iterative query performs only a fixed number of joins.
  • Each iteration extends the view; the final result is called the fixed point.
  • Recursive views are required to be monotonic: adding tuples to prereq never removes tuples from rec_prereq.

In a recursive computation of the prerequisites of CS-347, iterations 3 and 4 give the same tuples. What is this final result called?

تفاصيل المصدرالفصل 2 · الشرائح ⁦51–54⁩
المصدر
الفصل 2 · الشرائح ⁦51–54⁩

Ranking: rank and dense_rankالترتيب

Ranking and windowing

RANK()
A window function used to assign a rank to each row within a partition of a result set, in conjunction with an order by specification: select ID, rank() over (order by GPA desc) as s_rank from student_grades — not sorted; an extra order by s_rank is needed to sort.
student_grades(ID, GPA): rank() and dense_rank() over (order by GPA desc) (slides 58–59)
IDGPArank()dense_rank()
707411
505411
909411
404342
202342
6062.563
303274
101274
  • Ranking may leave gaps: 3 students share the top GPA → all have rank 1, and the next rank is 4.
  • dense_rank does not leave gaps: the next dense rank would be 2.

In student_grades, three students have GPA 4 (the highest) and two have GPA 3. What dense_rank() over (order by GPA desc) do the GPA-3 students get?

تفاصيل المصدرالفصل 2 · الشرائح ⁦56–59⁩
المصدر
الفصل 2 · الشرائح ⁦56–59⁩

Windowingدوال النافذة

Window functions
Perform calculations across a specified set of rows known as a "window". The OVER clause is key to defining this window: PARTITION BY divides the data into sets, ORDER BY orders them.

من الشرائح

  • SELECT column_name1, window_function(column_name2) OVER([PARTITION BY column_name3]) AS new_column FROM table_name; — window_function = any aggregate or ranking function.
  • SELECT Name, Age, Department, Salary, AVG(Salary) OVER( PARTITION BY Department) AS Avg_Salary FROM employee — the average salary of each department next to every employee (data on slide 62: Ramesh, Suresh, Ram in Finance; Deep, Pradeep in Sales).

Which clause defines the window in SELECT Name, Salary, AVG(Salary) OVER( PARTITION BY Department ) AS Avg_Salary FROM employee?

تفاصيل المصدرالفصل 2 · الشرائح ⁦60–63⁩
المصدر
الفصل 2 · الشرائح ⁦60–63⁩

OLAP, cross-tabs and data cubesOLAP والمكعبات

Online Analytical Processing (OLAP)
Interactive analysis of data, allowing data to be summarized and viewed in different ways; multidimensional analysis on large volumes of data in a data warehouse, data lake or other repository. An OLAP database is optimised for analytical operations.
Cross-tab (pivot-table)
Values of one dimension attribute form the row headers, values of another the column headers; cells hold aggregates (sum) of the values that specify the cell.
Data cube
A multidimensional generalization of a cross-tab; can have n dimensions; cross-tabs can be used as views on a data cube.
Relational representation
Cross-tabs can be represented as relations, using the value all for aggregates — the SQL standard actually uses null in place of all.

What is a data cube?

تفاصيل المصدرالفصل 2 · الشرائح ⁦65–70⁩
المصدر
الفصل 2 · الشرائح ⁦65–70⁩

CUBE and ROLLUPCUBE و ROLLUP

group by cube(item_name, color, size)

  • Union of GROUP BY on every subset of the attributes
  • Eight groupings: (item_name, color, size), (item_name, color), (item_name, size), (color, size), (item_name), (color), (size), ( )

group by rollup(item_name, color, size)

  • Union on every prefix of the list of attributes
  • Four groupings: (item_name, color, size), (item_name, color), (item_name), ( )
  • Hierarchical aggregates; also known as DRILL UP; like zooming-out

المسألة

group by rollup(item_name), rollup(color, size) — which groupings? (slide 75)

A sales report uses group by rollup(item_name, color, size). How many grouping lists are unioned in the result?

تفاصيل المصدرالفصل 2 · الشرائح ⁦71–75⁩
المصدر
الفصل 2 · الشرائح ⁦71–75⁩

ROLLUP: the inventory exampleمثال ROLLUP

Extended aggregation: CUBE and ROLLUP

من الشرائح

  • SELECT c1, c2, aggregate_function(c3) FROM table GROUP BY ROLLUP (c1, c2);
  • In the syntax above, ROLLUP(c1,c2) generates three grouping sets: (c1,c2), (c1) and () (slide 76).
inventory (slides 77–78)
warehouseproductmodelquantity
San FransiscoiPhone6s50
San FransiscoiPhone710
San FransiscoiPhoneX200
San FransiscoSamsungGalaxy S200
San FransiscoSamsungNote 8100
San JoseiPhone6s100
San JoseiPhone750
San JoseiPhoneX150
San JoseSamsungGalaxy S200
San JoseSamsungNote 8150
SELECT warehouse, SUM(quantity) FROM inventory GROUP BY warehouse; (slide 77)
warehouseSUM(quantity)
San Fransisco560
San Jose650
SELECT warehouse, product, SUM(quantity) FROM inventory GROUP BY ROLLUP (warehouse, product); (slide 78)
warehouseproductSUM(quantity)Callout on the slide
San FransiscoiPhone260
San FransiscoSamsung300
San FransiscoNULL560Total inventory in San Fransisco
San JoseiPhone300
San JoseSamsung350
San JoseNULL650Total inventory in San Jose
NULLNULL1210Total inventory in all warehouses
تفاصيل المصدرالفصل 2 · الشرائح ⁦76–78⁩
المصدر
الفصل 2 · الشرائح ⁦76–78⁩

OLAP operationsعمليات OLAP

OLAP operations
OperationWhat it does (slides 72, 81, 84, 86)
Roll up (drill up)
  • Aggregates to a higher-level overview
  • like zooming-out on the data cube
Roll down (drill down)
  • Reverse of roll up
  • like zooming-in
  • from less detailed to more detailed data
SliceSubset of the cube for a single value of one or more dimension members (e.g., temperature = cool)
Pivot (rotation)Rotates the data axes in view, e.g., swapping rows and columns

من الشرائح

  • Slide 79: temperature levels hot (80-85), mild (70-75), cool (64-69).
  • Slide 80: roll-up on location from cities (Chicago, New York, Toronto, Vancouver) to countries (USA, Canada).
  • Slide 84: a slice with temperature = cool turns a three-dimensional cube into a two-dimensional one.

An analyst moves from yearly sales totals to monthly sales figures. Which OLAP operation is this?

تفاصيل المصدرالفصل 2 · الشرائح ⁦79, 80, 81, 84, 86⁩
المصدر
الفصل 2 · الشرائح ⁦79, 80, 81, 84, 86⁩

OLAP implementationتنفيذ OLAP

MOLAPمتعدد الأبعاد
The earliest OLAP systems: multidimensional arrays in memory to store data cubes.
ROLAPعلائقي
OLAP implementations using only relational database features.
HOLAPهجين
Store some summaries in memory and the base data and other summaries in a relational database.

What distinguishes a hybrid OLAP (HOLAP) system from a relational OLAP (ROLAP) system?

تفاصيل المصدرالفصل 2 · الشريحة ⁦88⁩
المصدر
الفصل 2 · الشريحة ⁦88⁩

الخلاصة

تفاصيل المصدر
المصدر
الفصل 2

خريطة الفصل

    1. 1مقدمة الفصل
  1. Accessing SQL from a programming language; ODBCالوصول إلى SQL من لغة برمجة وODBC

    1. 2Accessing SQL from a programming languageSQL من لغة برمجة
    2. 3ODBCODBC
  2. JDBCJDBC

    1. 4JDBC: model and codeJDBC
    2. 5Nulls and prepared statementsالقيم الفارغة والجمل المعدّة
    3. 6Metadata featuresالبيانات الوصفية
    4. 7Transaction control in JDBCالتحكم في المعاملات
    1. 8Embedded SQLSQL المضمّنة
  3. Functions and proceduresالدوال والإجراءات

    1. 9Functions in SQLالدوال في SQL
    2. 10Stored proceduresالإجراءات المخزّنة
    3. 11Language constructs and external routinesالبنى اللغوية والروتينات الخارجية
  4. Triggersالمشغّلات (Triggers)

    1. 12Triggersالمشغّلات
    2. 13A trigger example; statement-level triggers; when not to use triggersمثال ومتى نتجنبها
  5. Recursive queriesالاستعلامات العودية

    1. 14Recursion in SQLالعودية في SQL
    2. 15Transitive closure and the fixed pointالإغلاق المتعدي والنقطة الثابتة
  6. Ranking and windowingالترتيب والنوافذ

    1. 16Ranking: rank and dense_rankالترتيب
    2. 17Windowingدوال النافذة
    1. 18OLAP, cross-tabs and data cubesOLAP والمكعبات
  7. Extended aggregation: CUBE and ROLLUPالتجميع الموسّع: CUBE وROLLUP

    1. 19CUBE and ROLLUPCUBE و ROLLUP
    2. 20ROLLUP: the inventory exampleمثال ROLLUP
  8. OLAP operations and OLAP implementationعمليات OLAP وطرق تنفيذه

    1. 21OLAP operationsعمليات OLAP
    2. 22OLAP implementationتنفيذ OLAP
    1. 23الخلاصة