This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
ObjectivesObjectives Define termsDefine terms Interpret history and role of SQL Interpret history and role of SQL Define a database using SQL data Define a database using SQL data
definition languagedefinition language Write single table queries using SQLWrite single table queries using SQL Establish referential integrity using SQLEstablish referential integrity using SQL Discuss SQL:1999 and SQL:200n Discuss SQL:1999 and SQL:200n
SQL OverviewSQL Overview Structured Query LanguageStructured Query Language
The standard for relational database The standard for relational database management systems (RDBMS) management systems (RDBMS)
RDBMS: A database management RDBMS: A database management system that manages data as a system that manages data as a collection of tables in which all collection of tables in which all relationships are represented by relationships are represented by common values in related tablescommon values in related tables
History of SQLHistory of SQL 1970–E. Codd develops relational database 1970–E. Codd develops relational database
conceptconcept 1974-1979–System R with Sequel (later SQL) 1974-1979–System R with Sequel (later SQL)
created at IBM Research Labcreated at IBM Research Lab 1979–Oracle markets first relational DB with SQL1979–Oracle markets first relational DB with SQL 1986–ANSI SQL standard released1986–ANSI SQL standard released 1989, 1992, 1999, 2003–Major ANSI standard 1989, 1992, 1999, 2003–Major ANSI standard
updatesupdates Current–SQL is supported by most major Current–SQL is supported by most major
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
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
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 new table and its CREATE TABLE–defines a new table and its columnscolumns
CREATE VIEW–defines a logical table from CREATE VIEW–defines a logical table from one or more tables or viewsone or more tables or views
Other CREATE statements: CHARACTER Other CREATE statements: CHARACTER SET, COLLATION, TRANSLATION, SET, COLLATION, TRANSLATION, ASSERTION, DOMAINASSERTION, DOMAIN
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
Changing TablesChanging Tables ALTER TABLE statement allows you to change column specifications:ALTER TABLE statement allows you to change column specifications:
Table Actions:Table Actions:
Example Example (adding a new column with a default value)(adding a new column with a default value)::
Insert StatementInsert Statement Adds one or more rows to a tableAdds one or more rows to a table Inserting into a tableInserting into a table
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
Inserting from another tableInserting from another table
Creating Tables with Identity Creating Tables with Identity ColumnsColumns
Inserting into a table does not require explicit customer ID Inserting into a table does not require explicit customer ID entry or field listentry or field list
INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);
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 Speed up random/sequential access to base table
datadata ExampleExample
CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMERNAME)CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMERNAME) This makes an index for the CUSTOMERNAME field of the This makes an index for the CUSTOMERNAME field of the
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
SELECT Example SELECT Example Using a FunctionUsing a Function
Using the COUNT Using the COUNT aggregate functionaggregate function to to find totalsfind totals
SELECT SELECT COUNT(*)COUNT(*) FROM ORDERLINE_T FROM ORDERLINE_TWHERE ORDERID = 1004;WHERE ORDERID = 1004;
Note: with aggregate functions you can’t have Note: with aggregate functions you can’t have single-valued columns included in the SELECT single-valued columns included in the SELECT clause, unless they are included in the GROUP clause, unless they are included in the GROUP BY clauseBY clause
ANDAND, , OROR, and , and NOTNOT Operators for customizing Operators for customizing conditions in WHERE clauseconditions in WHERE clause
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.
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 the CUSTOMER NAMEwithin a state by the CUSTOMER NAME
Note: the IN operator in this example allows you to include rows whose CustomerState value is either FL, TX, CA, or HI. It is more efficient than separate OR conditions.
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)
Note: you can use single-value fields with Note: you can use single-value fields with aggregate functions if they are included in the aggregate functions if they are included in the GROUP BY clauseGROUP BY clause
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
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 included groups with total numbers greater than 1 will be included in final result.in final result.
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 “virtual table” created dynamically upon request by a user a user
No data actually stored; instead data from base table No data actually stored; instead data from base table made available to usermade available to user
Based on SQL SELECT statement on base tables or Based on SQL SELECT statement on base tables or other viewsother 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 Must be refreshed periodically to match the
corresponding base tablescorresponding base tables
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
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
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic,
mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America.