Review of SQL
-
Upload
information-technology -
Category
Technology
-
view
2.756 -
download
4
description
Transcript of Review of SQL
11
Review of SQLReview of SQL
ICS 031 – Jaweed YazdaniICS 031 – Jaweed Yazdani
ICS 031 Database Administration 22
SQL OverviewSQL Overview Structured Query LanguageStructured Query Language The standard for relational database The standard for relational database
management systems (RDBMS) management systems (RDBMS) SQL-92 and SQL-99 Standards – Purpose:SQL-92 and SQL-99 Standards – Purpose:
Specify syntax/semantics for data definition and Specify syntax/semantics for data definition and manipulationmanipulation
Define data structuresDefine data structures Enable portabilityEnable portability Specify minimal (level 1) and complete (level 2) Specify minimal (level 1) and complete (level 2)
standardsstandards Allow for later growth/enhancement to standardAllow for later growth/enhancement to standard
ICS 031 Database Administration 33
Benefits of a Standardized Benefits of a Standardized Relational LanguageRelational Language
Reduced training costsReduced training costs ProductivityProductivity Application portabilityApplication portability Application longevityApplication longevity Reduced dependence on a single Reduced dependence on a single
vendorvendor Cross-system communicationCross-system communication
ICS 031 Database Administration 44
SQL EnvironmentSQL Environment CatalogCatalog
A set of schemas that constitute the description of a databaseA set of schemas that constitute the description of a database SchemaSchema
The structure that contains descriptions of objects created by a The structure that contains descriptions of objects created by a user (base tables, views, constraints)user (base tables, views, constraints)
Data Definition Language (DDL)Data Definition Language (DDL) Commands that define a database, including creating, altering, Commands that define a database, including creating, altering,
and dropping tables and establishing constraintsand dropping tables and establishing constraints Data Manipulation Language (DML)Data Manipulation Language (DML)
Commands that maintain and query a databaseCommands that maintain and query a database Data Control Language (DCL)Data Control Language (DCL)
Commands that control a database, including administering Commands that control a database, including administering privileges and committing dataprivileges and committing data
ICS 031 Database Administration 55
Figure 7-1:A simplified schematic of a typical SQL environment, as described by the SQL-92 standard
ICS 031 Database Administration 66
Some SQL Data types Some SQL Data types (from Oracle 9i)(from Oracle 9i)
String typesString types CHAR(n) – fixed-length character data, n characters long CHAR(n) – fixed-length character data, n characters long
Maximum length = 2000 bytesMaximum length = 2000 bytes VARCHAR2(n) – variable length character data, maximum 4000 VARCHAR2(n) – variable length character data, maximum 4000
bytesbytes LONG – variable-length character data, up to 4GB. Maximum 1 LONG – variable-length character data, up to 4GB. Maximum 1
per tableper table Numeric typesNumeric types
NUMBER(p,q) – general purpose numeric data typeNUMBER(p,q) – general purpose numeric data type INTEGER(p) – signed integer, p digits wideINTEGER(p) – signed integer, p digits wide FLOAT(p) – floating point in scientific notation with p binary FLOAT(p) – floating point in scientific notation with p binary
digits precisiondigits precision Date/time typeDate/time type
DATE – fixed-length date/time in dd-mm-yy formDATE – fixed-length date/time in dd-mm-yy form
ICS 031 Database Administration 77
Figure 7-4: DDL, DML, DCL, and the database development process
ICS 031 Database Administration 88
SQL Database DefinitionSQL Database Definition Data Definition Language (DDL)Data Definition Language (DDL) Major CREATE statements:Major CREATE statements:
CREATE SCHEMA – defines a portion of the CREATE SCHEMA – defines a portion of the database owned by a particular userdatabase owned by a particular user
CREATE TABLE – defines a table and its CREATE TABLE – defines a table and its columnscolumns
CREATE VIEW – defines a logical table from CREATE VIEW – defines a logical table from one or more viewsone or more views
Other CREATE statements: CHARACTER Other CREATE statements: CHARACTER SET, COLLATION, TRANSLATION, SET, COLLATION, TRANSLATION, ASSERTION, DOMAINASSERTION, DOMAIN
ICS 031 Database Administration 99
Table CreationTable CreationFigure 7-5: General syntax for CREATE TABLE
Steps in table creation:
1. Identify data types for attributes
2. Identify columns that can and cannot be null
3. Identify columns that must be unique (candidate keys)
4. Identify primary key-foreign key mates
5. Determine default values
6. Identify constraints on columns (domain specifications)
7. Create the table and associated indexes
ICS 031 Database Administration 1010
The following slides create tables The following slides create tables for this enterprise data modelfor this enterprise data model
ICS 031 Database Administration 1111
Figure 7-6: SQL database definition commands for Pine Valley Furniture
Overall table definitions
ICS 031 Database Administration 1212
Defining attributes and their data types
ICS 031 Database Administration 1313
Non-nullable specification
Identifying primary key
Primary keys can never have NULL values
ICS 031 Database Administration 1414
Non-nullable specifications
Primary key
Some primary keys are composite – composed of multiple attributes
ICS 031 Database Administration 1515
Default value
Domain constraint
Controlling the values in attributes
ICS 031 Database Administration 1616
Primary key of parent table
Identifying foreign keys and establishing relationships
Foreign key of dependent table
ICS 031 Database Administration 1717
Data Integrity ControlsData Integrity Controls Referential integrity – constraint Referential integrity – constraint
that ensures that foreign key that ensures that foreign key values of a table must match values of a table must match primary key values of a related primary key values of a related table in 1:M relationshipstable in 1:M relationships
Restricting:Restricting: Deletes of primary recordsDeletes of primary records Updates of primary recordsUpdates of primary records Inserts of dependent recordsInserts of dependent records
ICS 031 Database Administration 1818
Relational integrity is enforced via the primary-key to foreign-key match
ICS 031 Database Administration 1919
Changing and Removing Changing and Removing TablesTables
ALTER TABLE statement allows you ALTER TABLE statement allows you to change column specifications:to change column specifications: ALTER TABLE CUSTOMER_T ADD (TYPE ALTER TABLE CUSTOMER_T ADD (TYPE
VARCHAR(2))VARCHAR(2)) DROP TABLE statement allows you to DROP TABLE statement allows you to
remove tables from your schema:remove tables from your schema: DROP TABLE CUSTOMER_TDROP TABLE CUSTOMER_T
ICS 031 Database Administration 2020
Schema DefinitionSchema Definition Control processing/storage efficiency:Control processing/storage efficiency:
Choice of indexesChoice of indexes File organizations for base tablesFile organizations for base tables File organizations for indexesFile organizations for indexes Data clusteringData clustering Statistics maintenanceStatistics maintenance
Creating indexesCreating indexes Speed up random/sequential access to base table dataSpeed up random/sequential access to base table data ExampleExample
CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMER_NAME)CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMER_NAME) This makes an index for the CUSTOMER_NAME field of the This makes an index for the CUSTOMER_NAME field of the
CUSTOMER_T tableCUSTOMER_T table
ICS 031 Database Administration 2121
Insert StatementInsert Statement Adds data to a tableAdds data to a table Inserting into a tableInserting into a table
INSERT INTO CUSTOMER_T VALUES (001, INSERT INTO CUSTOMER_T VALUES (001, ‘Contemporary Casuals’, 1355 S. Himes Blvd.’, ‘Contemporary Casuals’, 1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);‘Gainesville’, ‘FL’, 32601);
Inserting a record that has some null attributes Inserting a record that has some null attributes requires identifying the fields that actually get requires identifying the fields that actually get datadata INSERT INTO PRODUCT_T (PRODUCT_ID, INSERT INTO PRODUCT_T (PRODUCT_ID,
PRODUCT_DESCRIPTION,PRODUCT_FINISH, STANDARD_PRICE, PRODUCT_DESCRIPTION,PRODUCT_FINISH, STANDARD_PRICE, PRODUCT_ON_HAND) VALUES (1, ‘End Table’, ‘Cherry’, 175, 8);PRODUCT_ON_HAND) VALUES (1, ‘End Table’, ‘Cherry’, 175, 8);
Inserting from another tableInserting from another table INSERT INTO CA_CUSTOMER_T SELECT * FROM CUSTOMER_T INSERT INTO CA_CUSTOMER_T SELECT * FROM CUSTOMER_T
WHERE STATE = ‘CA’;WHERE STATE = ‘CA’;
ICS 031 Database Administration 2222
Delete StatementDelete Statement
Removes rows from a tableRemoves rows from a table Delete certain rowsDelete certain rows
DELETE FROM CUSTOMER_T WHERE DELETE FROM CUSTOMER_T WHERE STATE = ‘HI’;STATE = ‘HI’;
Delete all rowsDelete all rows DELETE FROM CUSTOMER_T;DELETE FROM CUSTOMER_T;
ICS 031 Database Administration 2323
Update StatementUpdate Statement
Modifies data in existing rowsModifies data in existing rows
UPDATE PRODUCT_T SET UNIT_PRICE = UPDATE PRODUCT_T SET UNIT_PRICE = 775 WHERE PRODUCT_ID = 7;775 WHERE PRODUCT_ID = 7;
ICS 031 Database Administration 2424
SELECT StatementSELECT Statement Used for queries on single or multiple tablesUsed for queries on single or multiple tables Clauses of the SELECT statement:Clauses of the SELECT statement:
SELECTSELECT List the columns (and expressions) that should be returned from the queryList the columns (and expressions) that should be returned from the query
FROMFROM Indicate the table(s) or view(s) from which data will be obtainedIndicate the table(s) or view(s) from which data will be obtained
WHEREWHERE Indicate the conditions under which a row will be included in the resultIndicate the conditions under which a row will be included in the result
GROUP BYGROUP BY Indicate categorization of results Indicate categorization of results
HAVINGHAVING Indicate the conditions under which a category (group) will be includedIndicate the conditions under which a category (group) will be included
ORDER BYORDER BY Sorts the result according to specified criteriaSorts the result according to specified criteria
ICS 031 Database Administration 2525
Figure 7-8: SQL statement processing order (adapted from van der Lans, p.100)
ICS 031 Database Administration 2626
SELECT ExampleSELECT Example
Find products with standard price less Find products with standard price less than $275than $275
SELECTSELECT PRODUCT_NAME, STANDARD_PRICE PRODUCT_NAME, STANDARD_PRICE
FROMFROM PRODUCT_V PRODUCT_V
WHEREWHERE STANDARD_PRICE < 275; STANDARD_PRICE < 275;
Table 7-3: Comparison Operators in SQL
ICS 031 Database Administration 2727
SELECT Example using AliasSELECT Example using Alias
Alias is an alternative column or table Alias is an alternative column or table namename
SELECT SELECT CUSTCUST.CUSTOMER AS .CUSTOMER AS NAMENAME, , CUST.CUSTOMER_ADDRESS CUST.CUSTOMER_ADDRESS
FROM CUSTOMER_V FROM CUSTOMER_V CUSTCUST
WHERE WHERE NAMENAME = ‘Home Furnishings’; = ‘Home Furnishings’;
ICS 031 Database Administration 2828
SELECT Example SELECT Example Using a FunctionUsing a Function
Using the COUNT Using the COUNT aggregate functionaggregate function to find totalsto find totals
SELECT SELECT COUNT(*)COUNT(*) FROM ORDER_LINE_V FROM ORDER_LINE_VWHERE ORDER_ID = 1004;WHERE ORDER_ID = 1004;
Note: with aggregate functions you can’t Note: with aggregate functions you can’t have single-valued columns included in the have single-valued columns included in the SELECT clauseSELECT clause
ICS 031 Database Administration 2929
SELECT Example – Boolean SELECT Example – Boolean OperatorsOperators
ANDAND, , OROR, and , and NOTNOT Operators for customizing Operators for customizing conditions in WHERE clauseconditions in WHERE clause
SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICESTANDARD_PRICE
FROM PRODUCT_VFROM PRODUCT_V
WHERE (PRODUCT_DESCRIPTION WHERE (PRODUCT_DESCRIPTION LIKELIKE ‘ ‘%%Desk’Desk’
OROR PRODUCT_DESCRIPTION PRODUCT_DESCRIPTION LIKELIKE ‘ ‘%%Table’) Table’)
ANDAND UNIT_PRICE > 300; UNIT_PRICE > 300;
Note: the LIKE operator allows you to compare strings using wildcards. For example, the % wildcard in ‘%Desk’ indicates that all strings that have any number of characters preceding the word “Desk” will be allowed
ICS 031 Database Administration 3030
SELECT Example – SELECT Example – Sorting Results with the ORDER BY Sorting Results with the ORDER BY
ClauseClause Sort the results first by STATE, and Sort the results first by STATE, and within a state by CUSTOMER_NAMEwithin a state by CUSTOMER_NAME
SELECT CUSTOMER_NAME, CITY, STATESELECT CUSTOMER_NAME, CITY, STATE
FROM CUSTOMER_VFROM CUSTOMER_V
WHERE STATE WHERE STATE ININ (‘FL’, ‘TX’, ‘CA’, ‘HI’) (‘FL’, ‘TX’, ‘CA’, ‘HI’)
ORDER BY STATE, CUSTOMER_NAME;ORDER BY STATE, CUSTOMER_NAME;
Note: the IN operator in this example allows you to include rows whose STATE value is either FL, TX, CA, or HI. It is more efficient than separate OR conditions
ICS 031 Database Administration 3131
SELECT Example – SELECT Example – Categorizing Results Using the GROUP BY Categorizing Results Using the GROUP BY
ClauseClause For use with aggregate functionsFor use with aggregate functions
Scalar aggregateScalar aggregate: single value returned from SQL query : single value returned from SQL query with aggregate functionwith aggregate function
Vector aggregateVector aggregate: multiple values returned from SQL : multiple values returned from SQL query with aggregate function (via GROUP BY)query with aggregate function (via GROUP BY)
SELECT STATE, COUNT(STATE) SELECT STATE, COUNT(STATE)
FROM CUSTOMER_VFROM CUSTOMER_V
GROUP BYGROUP BY STATE; STATE;
Note: you can use single-value fields with aggregate Note: you can use single-value fields with aggregate functions if they are included in the GROUP BY functions if they are included in the GROUP BY clauseclause
ICS 031 Database Administration 3232
SELECT Example – SELECT Example – Qualifying Results by Categories Qualifying Results by Categories
Using the HAVING ClauseUsing the HAVING Clause For use with GROUP BYFor use with GROUP BY
SELECT STATE, COUNT(STATE) SELECT STATE, COUNT(STATE)
FROM CUSTOMER_VFROM CUSTOMER_V
GROUP BY STATEGROUP BY STATE
HAVINGHAVING COUNT(STATE) > 1; COUNT(STATE) > 1;
Like a WHERE clause, but it operates on groups Like a WHERE clause, but it operates on groups (categories), not on individual rows. Here, only those (categories), not on individual rows. Here, only those groups with total numbers greater than 1 will be groups with total numbers greater than 1 will be included in final resultincluded in final result
ICS 031 Database Administration 3333
Figure 7-8: SQL statement processing order (adapted from van der Lans, p.100)
ICS 031 Database Administration 3434
Using and Defining ViewsUsing and Defining Views Views provide users controlled access to tablesViews provide users controlled access to tables Base Table – table containing the raw dataBase Table – table containing the raw data Dynamic ViewDynamic View
A “virtual table” created dynamically upon request by a user A “virtual table” created dynamically upon request by a user No data actually stored; instead data from base table made No data actually stored; instead data from base table made
available to useravailable to user Based on SQL SELECT statement on base tables or other viewsBased on SQL SELECT statement on base tables or other views
Materialized ViewMaterialized View Copy or replication of dataCopy or replication of data Data actually storedData actually stored Must be refreshed periodically to match the corresponding Must be refreshed periodically to match the corresponding
base tablesbase tables
ICS 031 Database Administration 3535
Sample CREATE VIEWSample CREATE VIEWCREATE VIEW EXPENSIVE_STUFF_V ASCREATE VIEW EXPENSIVE_STUFF_V AS
SELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICESELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICE
FROM PRODUCT_TFROM PRODUCT_T
WHERE UNIT_PRICE >300WHERE UNIT_PRICE >300
WITH CHECK_OPTION;WITH CHECK_OPTION;
View has a nameView is based on a SELECT statementCHECK_OPTION works only for updateable views and prevents updates that would create rows not included in the view
ICS 031 Database Administration 3636
Advantages of ViewsAdvantages of Views Simplify query commandsSimplify query commands Assist with data security (but don't rely on Assist with data security (but don't rely on
views for security, there are more views for security, there are more important security measures)important security measures)
Enhance programming productivityEnhance programming productivity Contain most current base table dataContain most current base table data Use little storage spaceUse little storage space Provide customized view for userProvide customized view for user Establish physical data independenceEstablish physical data independence
ICS 031 Database Administration 3737
Disadvantages of ViewsDisadvantages of Views Use processing time each time view Use processing time each time view
is referencedis referenced May or may not be directly May or may not be directly
updateableupdateable