advanced sql advanced sql complex queries, joining tables

20
Advanced SQL Advanced SQL Complex Queries, Complex Queries, Joining Tables Joining Tables

Upload: bruno-bryant

Post on 02-Jan-2016

277 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Advanced SQL Advanced SQL

Complex Queries, Joining Complex Queries, Joining TablesTables

Page 2: Advanced SQL Advanced SQL Complex Queries, Joining Tables

FUNCTION OUTPUT

COUNT The number of rows containing the specified attribute.

MIN The minimum attribute value encountered.

MAX The maximum attribute value encountered.

AVG The arithmetic mean (average) for the specified attribute.

SUM The sum of all values for a selected attribute.

Some Basic SQL Numeric Functions

Page 3: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Example AggregateExample Aggregate Function Operations Function Operations

COUNTCOUNT

MAX and MINMAX and MIN

SELECT COUNT(DISTINCT V_CODE)FROM PRODUCT;

SELECT COUNT(DISTINCT V_CODE)FROM PRODUCTWHERE P_PRICE <= 10.00;

SELECT MIN(P_PRICE)FROM PRODUCT;

SELECT P_CODE, P_DESCRIPT, P_PRICEFROM PRODUCTWHERE P_PRICE = (SELECT MAX(P_PRICE) FROM PRODUCT);

Page 4: Advanced SQL Advanced SQL Complex Queries, Joining Tables

More Complex Queries and More Complex Queries and SQL FunctionsSQL Functions

More Complex Queries and More Complex Queries and SQL FunctionsSQL Functions

SUMSUM

SELECT SUM(P_ONHAND*P_PRICE)SELECT SUM(P_ONHAND*P_PRICE)FROM PRODUCT;FROM PRODUCT;

AVGAVG

SELECT P_DESCRIPT, P_ONHAND, P_PRICE, SELECT P_DESCRIPT, P_ONHAND, P_PRICE, V_CODEV_CODEFROM PRODUCTFROM PRODUCTWHERE P_PRICE > WHERE P_PRICE > (SELECT AVG(P_PRICE) FROM PRODUCT)(SELECT AVG(P_PRICE) FROM PRODUCT)ORDER BY P_PRICE DESC;ORDER BY P_PRICE DESC;

Page 5: Advanced SQL Advanced SQL Complex Queries, Joining Tables

More Complex Queries and More Complex Queries and SQL Functions (con’t.)SQL Functions (con’t.)

Grouping dataGrouping data– Creates frequency distributionsCreates frequency distributions– Only valid when used with SQL arithmetic functionsOnly valid when used with SQL arithmetic functions

– HAVING clause operates like WHERE for grouping outputHAVING clause operates like WHERE for grouping output

SELECT P_SALECODE, MIN(P_PRICE)FROM PRODUCTGROUP BY P_SALECODE;

SELECT V_CODE,COUNT(DISTINCT(P_CODE)),AVG(P_PRICE)FROM PRODUCTGROUP BY V_CODEHAVING AVG(P_PRICE) < 10;

Page 6: Advanced SQL Advanced SQL Complex Queries, Joining Tables

More Complex Queries and More Complex Queries and SQL FunctionsSQL Functions

More Complex Queries and More Complex Queries and SQL FunctionsSQL Functions

Virtual tables: creating a viewVirtual tables: creating a view– CREATE VIEW commandCREATE VIEW command– Creates logical table existing only in virtual memoryCreates logical table existing only in virtual memory

CREATE VIEW PRODUCT_3 ASCREATE VIEW PRODUCT_3 ASSELECT P_DESCRIPT, P_ONHAND, P_PRICESELECT P_DESCRIPT, P_ONHAND, P_PRICEFROM PRODUCTFROM PRODUCTWHERE P_PRICE > 50.00;WHERE P_PRICE > 50.00;

SQL indexes: used to improve the efficiency of SQL indexes: used to improve the efficiency of data searchesdata searches

CREATE INDEX P_CODEXCREATE INDEX P_CODEXON PRODUCT(P_CODE);ON PRODUCT(P_CODE);

- - Oracle automatically creates indexes on Oracle automatically creates indexes on primary keysprimary keys

Page 7: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Complex QueriesComplex QueriesComplex QueriesComplex QueriesJoining Database TablesJoining Database Tables

SELECT PRODUCT.P_DESCRIPT, SELECT PRODUCT.P_DESCRIPT, PRODUCT.P_PRICE, VENDOR.V_NAME, PRODUCT.P_PRICE, VENDOR.V_NAME, VENDOR.V_CONTACT, VENDOR.V_AREACODE, VENDOR.V_CONTACT, VENDOR.V_AREACODE, VENDOR.V_PHONEVENDOR.V_PHONEFROM PRODUCT, VENDORFROM PRODUCT, VENDORWHERE PRODUCT.V_CODE = VENDOR.V_CODEWHERE PRODUCT.V_CODE = VENDOR.V_CODE;;

Page 8: Advanced SQL Advanced SQL Complex Queries, Joining Tables

The Results of a JOIN

Page 9: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Using Prefixes when Joining TablesUsing Prefixes when Joining Tables

Most current-generation DBMS, such as Oracle, do not Most current-generation DBMS, such as Oracle, do not require the table name to be used as prefixes, unless the require the table name to be used as prefixes, unless the same attribute name occurs in more then 1 table being same attribute name occurs in more then 1 table being joined.joined.– If the product number was defined as p_prodnum in the product If the product number was defined as p_prodnum in the product

table and v_prodnum in the vendor table, the table name need table and v_prodnum in the vendor table, the table name need not be specified when referencednot be specified when referenced

If the same attribute name occurs in several places, its If the same attribute name occurs in several places, its origin(table) must be specifiedorigin(table) must be specified– Product.prod_num and Vendor.prod_numProduct.prod_num and Vendor.prod_num

Page 10: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Complex QueriesComplex QueriesComplex QueriesComplex Queries

SELECT P_DESCRIPT, P_PRICE, V_NAME, SELECT P_DESCRIPT, P_PRICE, V_NAME, V_CONTACT, V_AREACODE, V_PHONEV_CONTACT, V_AREACODE, V_PHONEFROM PRODUCT, VENDORFROM PRODUCT, VENDORWHERE PRODUCT.V_CODE = WHERE PRODUCT.V_CODE = VENDOR.V_CODEVENDOR.V_CODEAND P_INDATE > ‘08/15/1999’;AND P_INDATE > ‘08/15/1999’;

Page 11: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Natural JoinsNatural Joins

Old style:Old style: SELECT P_PRODUCT, V_VENDORSELECT P_PRODUCT, V_VENDOR

FROM PRODUCT, VENDORFROM PRODUCT, VENDOR

WHERE PRODUCT.V_CODE = WHERE PRODUCT.V_CODE = VENDOR.V_CODEVENDOR.V_CODE

New style:New style: SELECT P_PRODUCT, V_VENDORSELECT P_PRODUCT, V_VENDOR

FROM PRODUCT NATURAL JOIN VENDORFROM PRODUCT NATURAL JOIN VENDOR

Page 12: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Updatable ViewsUpdatable Views

Views that can be updated which will Views that can be updated which will update their corresponding tables.update their corresponding tables.

Views can be updatable if the primary key Views can be updatable if the primary key of the base table is a column in the view of the base table is a column in the view that also has unique valuesthat also has unique values

Complete Lab #6 – Functions, Complex Queries, Views, Joining Tables

Page 13: Advanced SQL Advanced SQL Complex Queries, Joining Tables

SequencesSequences

Sequences are independent objects in the Sequences are independent objects in the databasedatabase

They are considered “Auto-numbers”They are considered “Auto-numbers”

They are created and used as primary They are created and used as primary keys in tables where the key is a keys in tables where the key is a sequential numbersequential numberCREATE SEQUENCE Part_Num_Seq START WITH 100 CREATE SEQUENCE Part_Num_Seq START WITH 100

Page 14: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Sequences on InsertSequences on Insert

Refer to the sequence (auto-number) Refer to the sequence (auto-number) object in place of the value needed for the object in place of the value needed for the key when inserting data into a tablekey when inserting data into a tableCan be used with NEXTVAL (Can be used with NEXTVAL (sequence is sequence is

incrementedincremented) or CURRVAL () or CURRVAL (current value of current value of

sequence is usedsequence is used))

INSERT INTO PARTS VALUES ( PART_ID_SEQ.NEXTVAL, INSERT INTO PARTS VALUES ( PART_ID_SEQ.NEXTVAL, ‘PART_NAME, ect……..)‘PART_NAME, ect……..)

Page 15: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Procedural SQLProcedural SQLProcedural SQLProcedural SQL

Shortcomings of SQLShortcomings of SQL

– SQL doesn’t support execution of a stored set of SQL doesn’t support execution of a stored set of procedures based on some logical condition.procedures based on some logical condition.

– SQL fails to support the looping operations.SQL fails to support the looping operations.

SolutionsSolutions

– Embedded SQLEmbedded SQL

Embedded SQL can be called from within the Embedded SQL can be called from within the procedural programming languageprocedural programming language

– Shared CodeShared Code

Critical code is isolated and shared by all application Critical code is isolated and shared by all application programs.programs.

Page 16: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Procedural SQL Procedural SQL

– Procedural SQL allows the use of Procedural SQL allows the use of procedural code and SQL statements that procedural code and SQL statements that are stored within the database.are stored within the database.

– The procedural code is executed by the The procedural code is executed by the DBMS when it is invoked by the end user.DBMS when it is invoked by the end user.

– End users can use procedural SQL End users can use procedural SQL (PL/SQL) to create:(PL/SQL) to create:

TriggersTriggers

Stored proceduresStored procedures

PL/SQL functionsPL/SQL functions

Procedural SQLProcedural SQLProcedural SQLProcedural SQL

Page 17: Advanced SQL Advanced SQL Complex Queries, Joining Tables

TriggersTriggers

– A A triggertrigger is procedural SQL code that is is procedural SQL code that is automatically invoked by the RDBMS upon the automatically invoked by the RDBMS upon the occurrence of a data manipulation event.occurrence of a data manipulation event.

A trigger is always invoked before or after a A trigger is always invoked before or after a data row is selected, inserted, or updated.data row is selected, inserted, or updated.

A trigger is always associated with a database A trigger is always associated with a database table.table.

Each database table may have one or more Each database table may have one or more triggers.triggers.

A trigger is executed as part of the transaction A trigger is executed as part of the transaction that triggered it.that triggered it.

Procedural SQLProcedural SQLProcedural SQLProcedural SQL

Page 18: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Procedural SQLProcedural SQLProcedural SQLProcedural SQL

– Role of triggersRole of triggers

Triggers can be used to enforce constraints Triggers can be used to enforce constraints that cannot be enforced at the design and that cannot be enforced at the design and implementation levels.implementation levels.

Triggers add functionality by automating Triggers add functionality by automating critical actions and providing appropriate critical actions and providing appropriate warnings and suggestions for remedial action.warnings and suggestions for remedial action.

Triggers can be used to update table values, Triggers can be used to update table values, insert records in tables, and call other stored insert records in tables, and call other stored procedures.procedures.

Triggers add processing power to the RDBMS Triggers add processing power to the RDBMS and to the database system.and to the database system.

Page 19: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Procedural SQLProcedural SQLProcedural SQLProcedural SQL

Stored ProceduresStored Procedures

– A A stored procedurestored procedure is a named collection of procedural and SQL is a named collection of procedural and SQL statements.statements.

– Stored procedures are stored in the database and invoked by Stored procedures are stored in the database and invoked by name.name.

– Stored procedures are executed as a unit.Stored procedures are executed as a unit.

– The use of stored procedures reduces network traffic, thus The use of stored procedures reduces network traffic, thus improving performance.improving performance.

Page 20: Advanced SQL Advanced SQL Complex Queries, Joining Tables

Stored FunctionsStored Functions

– is a named group of procedural and SQL statements that returns a is a named group of procedural and SQL statements that returns a value.value.

– Invoked from within stored procedures or triggersInvoked from within stored procedures or triggers– Cannot be invoked from within SQL statementsCannot be invoked from within SQL statements

PL/SQL Stored FunctionsPL/SQL Stored FunctionsPL/SQL Stored FunctionsPL/SQL Stored Functions