Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: Introduction to SQL

Similar presentations


Presentation on theme: "Chapter 6: Introduction to SQL"— Presentation transcript:

1 Chapter 6: Introduction to SQL
Important summary/in-depth discussions: 43~47; 55~57; 59~61; 62~64 9,10; 32,33; 37,38; (Not “initial delivery” but remarks) Chapter 6: Introduction to SQL Modern Database Management 12th Edition Jeff Hoffer, Ramesh Venkataraman, Heikki Topi Greatly improved 2017 FA In order to prepare you for HW 4, begin from slide #36, proceed to slide #64

2 Focus: Syntax Objectives Define terms
Interpret history and role of SQL Define a database using SQL data definition language Write single table queries using SQL Establish referential integrity using SQL Discuss SQL:1999 and SQL:2011 standards Focus: Syntax

3 SQL Overview Structured Query Language – often pronounced “Sequel”
The standard for relational database management systems (RDBMS) RDBMS: A database management system that manages data as a collection of tables in which all relationships are represented by common values in related tables

4 History of SQL 1970–E. F. Codd develops relational database concept
–System R with Sequel (later SQL) created at IBM Research Lab 1979–Oracle markets first relational DB with SQL 1981 – SQL/DS first available RDBMS system on DOS/VSE Others followed: INGRES (1981), IDM (1982), DG/SGL (1984), Sybase (1986) 1986–ANSI SQL standard released 1989, 1992, 1999, 2003, 2006, 2008, 2011–Major ANSI standard updates Current–SQL is supported by most major database vendors The concepts of relational database technology were first articulated in 1970, in E. F. Codd’s classic paper “A Relational Model of Data for Large Shared Data Banks.” System R was project at IBM Research Laboratory in San Jose, California, which demonstrated the feasibility of implementing the relational model in a database management system. They used a language they called “sequel”. It’s later been named SQL, but “sequel” is still often how it is pronounced. SQL-92 was a major revision and was structured into three levels: Entry, Intermediate, and Full. SQL:1999 established the core-level conformance, which must be met before any other level of conformance can be achieved; core-level conformance requirements are unchanged in SQL:2011. In addition to fixes and enhancements of SQL:1999, SQL:2003 introduced a new set of SQL/XML standards, three new data types, various new built-in functions, and improved methods for generating values automatically. SQL:2006 refined these additions and made them more compatible with XQuery, the XML query language published by the World Wide Web Consortium (W3C). SQL:2008 improved analytics query capabilities and enchanged MERGE for combining tables. The most important new additions to SQL:2011 are related to temporal databases, that is, databases that are able to capture the change in the data values over time. At the time of this writing, most database management systems claim SQL-92 compliance and partial compliance with SQL:1999 and SQL:2011.

5 Purpose of SQL Standard
Specify syntax/semantics for data definition and manipulation Define data structures and basic operations Enable portability of database definition and application modules Specify minimal (level 1) and complete (level 2) standards Allow for later growth/enhancement to standard (referential integrity, transaction management, user-defined functions, extended join operations, national character sets)

6 SQL Environment Data Definition Language (DDL)
Course priority: 2, 1, 3 Catalog A set of schemas that constitute the description of a database Schema The structure that contains descriptions of objects created by a user (base tables, views, constraints) Data Definition Language (DDL) Commands that define a database, including creating, altering, and dropping tables and establishing constraints Data Manipulation Language (DML) Commands that maintain and query a database Data Control Language (DCL) Commands that control a database, including administering privileges and committing data

7 Figure 6-1 A simplified schematic of a typical SQL environment, as described by the SQL: 2011 standard A database instance, also called a database server, is a set of memory structure and software processes that manage the access to a set of database files. Each instance maintains one or more databases, organized into catalogs consisting of schemas. Here we see an instance of a DBMS along with two databases (PROD and DEV). The Production database contains its own data indexed by the catalog PROD_C. It is the actual database being used for business operations. The Development database is used for making application changes and testing. Usually, organizations have two separate databases, one for production and one for development.

8 No comma between clauses; semi-colon at the end
Display order of columns specified here Fig 6-2 Query syntax 1 2 3 4 5 6 SELECT Major, AVERAGE(GPA) , ExpGraduateYr FROM STUDENT WHERE ExpGraduateYr = “2018” GROUP BY Major HAVING AVERAGE(GPA) >=3.0 ORDER BY Major; Sequence! No comma between clauses; semi-colon at the end Just a quick example to show sequence of clauses

9 Note: Necessity; Roles More than 85% of usage of SELECT-clause is here
Fig 6-2 Query syntax Clause Role Note: Necessity; Roles Fields to display Must have; can be queries (Subquery) Table(s) to get fields Must have: data source; can be Subquery Condi to get rows 1-Get rows; 2-join table; 3-pass parameters Field Can work w WHERE&HAVING but diffrnt Condi for groups MUST have Grp By to use Sorting Last clause; primary & secondary sorts SELECT Major, AVG(GPA) , AVG(YrGrad-YrAdm) AS Duration, AdvsrName FROM STUDENT, FACULTY AS FAC WHERE Major=“ACCT” AND FAC.FacID = STUDENT.FacID GROUP BY Major, AdvsrName HAVING AVG(GPA) >=3.0 ORDER BY AVG(GPA) DESC, AdvsrName; More than 85% of usage of SELECT-clause is here

10 HAVING vs where; group by and having
HAVING and WHERE are both condition-clause: states conditions/criteria for selection WHERE states cri for INDIVIDUAL rows HAVING states cri for GROUPS Because HAVING states cri for groups, It must be preceded by GROUP BY: No GROUP BY, no HAVING “A lower-level bullet w big fonts” Remem-ber slide 6-10 >1/4 made this mistake

11 SQL Data Types One of the purposes of DDL is to specify data types of each of the attributes (columns, fields) of a table. This table shows some of the common data types, but there are many others.

12 DDL, DML, DCL, and the database development process
Figure 6-4 DDL, DML, DCL, and the database development process SQL is composed of three sub-languages, DDL, DML, and DCL. DDL is Data Definition Language. This is used to actually create the metadata of the database, including all tables, attributes and their data types, indexes, primary and foreign keys, etc. The DDL implements the logical design into actual physical databases. This is the language that database designers will use to create the database. DML is Data Manipulation Language. This includes all query, update, insert, and delete statements. This is the language that allows users and applications interact with and manipulate the data in the database. DCL is Data Control Language. This is used by database administrators to specify who can access the data and the types of data and operations these users are authorized to do.

13 SQL Database Definition
Data Definition Language (DDL) Major CREATE statements: CREATE SCHEMA–defines a portion of the database owned by a particular user CREATE TABLE–defines a new table and its columns CREATE VIEW–defines a logical table from one or more tables or views Other CREATE statements: CHARACTER SET, COLLATION, TRANSLATION, ASSERTION, DOMAIN

14 Steps in Table Creation
Identify data types for attributes Identify columns that can and cannot be null Identify columns that must be unique (candidate keys) Identify primary key–foreign key mates Determine default values Identify constraints on columns (domain specifications) Create the table and associated indexes DDL is used for table creation. It allows you to implement all of the items listed here.

15 Figure 6-5 General syntax for CREATE TABLE statement used in data definition language
This shows the overall structure of a CREATE TABLE statement. This shows that the table will have a name, and some number of column definitions and table constraints. In the following slides, we see several examples, related to the Pine Valley Furniture database.

16 The following slides create tables for this enterprise data model
(from Chapter 1, Figure 1-3) This is the E-R diagram from chapter 1. Each of these entities, including the associative entity, is implemented as a table in the database.

17 Figure 6-3: sample PVFC data
17

18 Figure 6-6 SQL database definition commands for PVF Company
(Oracle 12c) Overall table definitions Here we see the SQL DDL commands for creating four tables, one each for customer, order, product, and order line. Note that for each of these, there is some number of column definitions, and some number of constraints.

19 Defining attributes and their data types
Each column has a data type. In this case, some are numeric, and some are character (text). You can also specify column sizes. For numeric columns, you can specify whether they will be integer (which ProductID is) or allow decimal values (such as ProductStandardPrice.

20 Primary keys can never have NULL values
Non-nullable specification Primary keys can never have NULL values The constraint above specifies the primary key. There are other ways of doing this as well. Note that primary keys must have a value; they can never be null. Identifying primary key Constraint name Cnstr Type Field

21 Non-nullable specifications
Composite key For this table, we see a composite primary key. Remember that OrderLine is an associative entity, between Product and Order. Therefore it has two foreign keys, one to each of these tables. Some primary keys are composite– composed of multiple attributes

22 Controlling the values in attributes
Default value Here we see a domain constraint that limits the number of allowable values for the ProductFinish column. The CHECK operator always ensures that update and insert attampts to this table will only allow the values listed. However, because ProductFinish does not prohibit null values, it is possible to insert a record while leaving ProductFinish without a value at all. Domain constraint validation rule

23 Identifying foreign keys and establishing relationships
Primary key of parent table Foreign key of dependent table Here we see that the Order table has a foreign key. This CONSTRAINT statement creates a foreign key constraint, referencing the Customer table’s primary key. Constraint name Cnstrnt Type Field REFERENCES Tbl(Key)

24 Data Integrity Controls
Referential integrity–constraint that ensures that foreign key values of a table must match primary key values of a related table in 1:M relationships Restricting: Deletes of primary records Updates of primary records Inserts of dependent records

25 Figure 6-7 Ensuring data integrity through updates
Relational integrity is enforced via the primary-key to foreign-key match The CREATE TABLE statement includes a clause to specify how updates and deletes are processed when there are dependent tables. If a DELETE request comes for a record with dependent records in another table, The DBMS could restrict the delete, which means to disallow it. Or, it could cascade the delete, so that dependent records with matching foreign keys will also be deleted. Or it could set null, which means that deleting the primary key record will result in setting all corresponding foreign keys to be set to null (this would imply an optional one cardinality in the relationship).

26 Changing Tables - Alter table-clause
ALTER TABLE statement allows you to change column specifications: Table Actions: Example (adding a new column with a default value): The ALTER command will be done after tables have already been created. For example, if you have an existing database, even one with actual data in it, you can modify tables by adding or changing columns, removing columns adding constraints, etc. If data in the tables violate the constraints, you will be prevented from setting these constraints until after changing the data. So, whereas CREATE TABLE is mostly a process that takes place during implementation, ALTER TABLE often takes place during maintenance. ADD COLUMN Name Type Value Default Value

27 DROP TABLE statement allows you to remove tables from your schema:
Removing Tables DROP TABLE statement allows you to remove tables from your schema: DROP TABLE CUSTOMER_T Tables will not be dropped if there are other tables that depend on them. This means that if any table has a foreign key to the table being dropped, the drop will fail. Therefore, it makes a difference which order you drop the tables in.

28 A SUBSET from another table
Insert Statement Adds one or more rows to a table Inserting into a table Inserting a record that has some null attributes requires identifying the fields that actually get data Inserting from another table INSERT INTO Table VALUES (value-list) (field-list) VALUES (value-list) As the last statement shows, it is possible to insert data into one table based on a query from another table. We’ll talk more about the SELECT statement shortly. A SUBSET from another table

29 Creating Tables with Identity Columns
Introduced with SQL:2008 Identity columns are columns whose value automatically increment with each new INSERT. So, an INSERT statement does not explicitly give a value for an identity column; this is handled automatically. Often primary keys are identity columns, but not always. Inserting into a table does not require explicit customer ID entry or field list INSERT INTO CUSTOMER_T VALUES ( 'Contemporary Casuals', '1355 S. Himes Blvd.', 'Gainesville', 'FL', 32601);

30 Removes rows from a table Delete certain rows
Delete Statement Removes rows from a table Delete certain rows DELETE FROM CUSTOMER_T WHERE CUSTOMERSTATE = 'HI'; Delete all rows DELETE FROM CUSTOMER_T; Careful!!! Remember, referential integrity rules will control whether a delete actually happens. The RESTRICT, CASCADE, and SET NULL constraints will determine how to handle the orders for a deleted customer.

31 Modifies data in existing rows
Update Statement Modifies data in existing rows Note: the WHERE clause may be a subquery (Chap 7) UPDATE Table-name SET Attribute = Value WHERE Criteria-to-apply-the-update For this UPDATE, we know that it will affect only one record in the table. How do we know this? Answer: Because ProductID is the primary key, which must be unique. So, there can be only one product with ProductID = 7. However, many times updates and deletes affect many records. For example, DELETE FROM CUSTOMER_T WHERE CUSTOMERSTATE = 'HI'; affects all customers from Hawaii.

32 Comparison of ALTER, INSERT, and UPDATE
ALTER TABLE: change the columns [structure] of the table ALTER TABLE CUSTOMER_T ADD column… INSERT: add records based on the existing table [did not change/alter table] INSERT INTO CUSTOME_T VALUES (… ) UPDATE: change the values of some fields in existing records [did not add a record] UPDATE CUSTOMER_T SET field = value …WHERE…

33 Comparison of ALTER, INSERT, and UPDATE (Cont)
Degree of impact: ALTER TABLE – wide (whole table); deep (nature/structure) INSERT – local (add rows; only make a table longer) UPDATE – very minor (only change values of some fields of some rows) Decrease Common confusion

34 Merge Statement Interpretation?
Makes it easier to update a table…allows combination of Insert and Update in one statement Useful for updating master tables with new data

35 Schema Definition Control processing/storage efficiency:
Choice of indexes File organizations for base tables File organizations for indexes Data clustering Statistics maintenance Creating indexes Speed up random/sequential access to base table data Example CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMERNAME) This makes an index for the CUSTOMERNAME field of the CUSTOMER_T table All of this has to do with physical database design.

36 Query: select statement
Data manipulation Query: select statement This is the CENTER section of the chapter, and the CENTER of this course Many slides contain multiple points of concepts/skills – do NOT miss the text, and pay attention to color code

37 SELECT Statement Used for queries on single or multiple tables
Clauses of the SELECT statement: SELECT List the columns (& expressions) to be returned from the query FROM Indicate the table(s) or view(s) from which data will be obtained WHERE Indicate the conditions under which a row will be included in the result GROUP BY Indicate categorization of results HAVING Indicate the conditions under which a category (group) will be included ORDER BY Sorts the result according to specified criteria on named fields The SELECT statement includes many features that allow you to perform sophisticated queries. You can specify the conditions for rows to be included in the results, and you can choose which columns from these rows should be included. You can either get detailed data, or get aggregate results such as sums and averages. You also have many options in how to sort and format the results. “No GROUP BY, no HAVING!!!!”

38 Fig 6-2 Query syntax [Revisit]
Clause Role Note: Necessity; Roles Fields to display Must have; can be queries (Subquery) Table(s) to get fields Must have: data source; can be Subquery Condi to get rows 1-Get rows; 2-join table; 3-pass parameters Field Can work w WHERE&HAVING but diffrnt Condi for groups MUST have Grp By to use Sorting Last clause; primary & secondary sorts SELECT Major, AVG(GPA) , AVG(YrGrad-YrAdm) AS Duration, AdvsrName FROM STUDENT, FACULTY AS FAC WHERE Major=“ACCT” AND FAC.FacID = STUDENT.FacID GROUP BY Major, AdvsrName HAVING AVG(GPA) >=3.0 ORDER BY AVG(GPA) DESC, AdvsrName; More than 85% of usage of SELECT-clause is here

39 General syntax of the SELECT statement used in DML
Figure 6-2 General syntax of the SELECT statement used in DML The SELECT clause specifies which columns to return. The FROM clause specifies which tables these come from. The WHERE clause specifies conditions that determine whether a row is returned in the results. GROUP BY and HAVING are used for aggregate queries and ORDER BY determines sorting. Note that queries can also include subqueries, so you may see a SELECT inside another SELECT. Figure 6-10 SQL statement processing order (based on van der Lans, 2006 p.100)

40 Find products with standard price less than $275
SELECT Example Find products with standard price less than $275 Every SESLECT statement returns a result table - Can be used as part of another query - subquery SELECT DISTINCT: no duplicate rows SELECT * : all columns selected

41 SELECT Example Using Alias
Table alias Column alias Alias is an alternative table or column name SELECT CUST.CUSTOMER_NAME AS NAME, CUST.CUSTOMER_ADDRESS FROM CUSTOMER_V [AS] CUST WHERE NAME = ‘Home Furnishings’; Note1: Specifying source table, P. 262 Note2: Use of alias, P Column alias is used as display heading ONLY Used in SELECT while defined in FROM Avoid !**

42 Using expressions Example:
ProductStandardPrice*1.1 AS Plus10Percent Which contents does it look like that we learned in Access (in IS 312)? YearInBiz:(NOW()-DateOpened)/365 Observe the result on P. 264

43 SELECT Example Using a Function
More functions: P. 265 SELECT Example Using a Function Using the COUNT aggregate function to find totals SELECT COUNT(*) FROM ORDERLINE_T WHERE ORDERID = 1004; Note: COUNT (*) and COUNT – different COUNT(*) counts num rows COUNT(field) counts rows that have not-null val for the field What is average standard price for each [examine!!] product in inventory? SELECT AVG (STANDARD_PRICE) AS AVERAGE FROM PROCUCT_V GROUP BY Product_ID; Meaning *IF* w/o GROUP BY clause? Functions that can ONLY be used w numeric columns? The most common aggregate functions are COUNT, SUM, and AVERAGE. What the above query gives is a number indicating the total number of order line records associated with order number 1004. Can be w or w/o GROUP BY, but w different meanings

44 Using a Function (Cont)
SELECT COUNT(*) Output: COUNT(*) FROM OoderLine_T WHERE OrderID = 1004; Note: With aggregate functions (“set values”) you can’t have single-valued columns (“row values”) included in the SELECT clause SELECT PRODUCT_ID, COUNT(*) FROM ORDER_LINE_V WHERE ORDER_ID = 1004; *** Examine the error message on P. 266 Error; P. 266 top

45 Using a Function (Cont)
With aggregate functions (“set values” – AVG, SUM, COUNT, MIN/MAX, etc) you can’t have single-valued columns (“row values”) included in the SELECT clause More example (error): SELECT ProductStandardPrice – AVG(ProductStandardPrice) FROM Product_T; *** !!! “Row values and set values do NOT belong to the same SELECT clause” If both really need to be in the same SELECT statement, use subquery (P. 266 bottom) Row value Set value

46 Issues about row value and aggregates
Middle of P. 266: SQL cannot return both a row value (such as Product_ID) and a set value (such as COUNT/AVG/SUM of a group); users must run two separate queries, one that returns row info and one that returns set info SELECT S_ID FROM STUDENT SELECT AVG(GPA) FROM STUDENT SELECT S_ID, AVG(GPA) FROM STUDENT

47 row value and aggregates (cont)
SELECT S_ID, MAJOR, GPA FROM STUDENT SELECT S_ID, MAJOR, AVG(GPA) FROM STUDENT SELECT S_ID, MAJOR, AVG(GPA) FROM STUDENT GROUP BY MAJOR SELECT COUNT(S_ID), MAJOR, AVG(GPA) FROM STUDENT GROUP BY MAJOR See middle of P. 266, SQL Server error message

48 Wildcards; comparison operators; null values
Wildcards: P. 267 LIKE ‘%Desk’ LIKE ‘*Desk’ Comparison operators: NULL values: IS NULL IS NOT NULL

49 IS NULL IS NULL: the field has a null value – not 0, not space (_), but no value Useful in scenarios as follows: Sold_date in a real estate property table Paid_date in a student registration table Transaction_amount in a auction table Syntax: WHERE field_name IS NULL The opposite is: WHERE field_name IS NOT NULL

50 SELECT Example–Boolean Operators
AND, OR, and NOT Operators for customizing conditions in WHERE clause Must be very, very, very, VERY careful about Boolean operations The WHERE clause in this query has tests for three conditions. It lists product name, finish, and standard price for all desks, and all tables that cost more than $300 in the Product table. 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. In MS Access wildcard is “*”

51 Figure 6-8 Boolean query A without use of parentheses
By default, processing order of Boolean operators is NOT, then AND, then OR By default, the AND operation takes place before the OR. So, only tables over $3000 are included (via the AND). These are then combined with all desks (no matter what price) via the OR.

52 SELECT Example–Boolean Operators
With parentheses…these override the normal precedence of Boolean operators With parentheses, you can override normal precedence rules. In this case parentheses make the OR take place before the AND.

53 Figure 6-9 Boolean query B with use of parentheses
Precaution: Do NOT try to “translate” the logical requirements – IMPLEMENT the logic EXACTLY The parentheses cause the OR to take place before the AND. Therefore, first desks and tables are combined (via the OR), and then this entire set is subjected to the $300 price limit via the AND.

54 Using distinct values Compare: SELECT ORDER_ID FROM ORDER_LINE_V;
and – SELECT DISTINCT ORDER_ID But: SELECT DISTINCT ORDER_ID, ORDER_QUANTITY Compare three figures on 272 & 273

55 Using IN and NOT IN with lists
WHERE field IN (value list) 1 value use =, many values use IN Sets the condition that the value of the field Can be of any value that is in the list in the parentheses WHERE Major IN (‘ACCT’, ‘CIT’, ‘IS’) Means the major can be either ACCT, or CIT, or IS It is more efficient than separate OR conditions. There is NEVER such code as follows: WHERE Major = (‘ACCT’, ‘CIT’, ‘IS’)

56 Using IN and NOT IN with lists (2)
When there is ONE value in the comparison: WHERE Field = value WHERE Field > value WHERE Field <= value WHERE Field <> value (<> -- “not equal”) When there are M values in comparison: WHERE field IN (Value1, Value2, Value3, …)

57 IN means “among the values of”, “can be one of the values in the list
Comparison of in and = IN means “among the values of”, “can be one of the values in the list = means “exactly that value”, “exactly the value of that variable”. So, IN (list of values) = one_value, = one_variable NEVER = (list of variables) IN (‘CA’, ‘OR’, ‘WA’) = ‘CA’ = (‘CA’, ‘OR’, ‘WA’)

58 Sorting Results with ORDER BY Clause
Sort the results first by STATE, and within a state by the CUSTOMER NAME Primary; secondary Can also use column positions You can order by any number of fields from the originating table. Question: How would you have done the WHERE clause if you used OR conditions instead of the IN operator? Answer: WHERE CustomerState = ‘FL’ OR CustomerState = ‘TX’ OR CustomerState = ‘CA’ OR CustomerState = ‘HI’ Note: The IN operator in this example allows you to include rows whose CustomerState value is either FL, TX, CA, or HI. IN; NOT IN

59 Categorizing Results Using GROUP BY Clause
For use with aggregate functions Scalar aggregate: single value returned from SQL query with aggregate function (“aggregate of the whole table”) Vector aggregate: multiple values returned from SQL query with aggregate function (via GROUP BY) (“agg. of the groups”) You can use single-value fields with aggregate functions if they (the fields) are included in the GROUP BY clause This is an example of vector aggregate. It will return the number of customers from each state. This query will return the name and count of customers from all states that actually have customers. If all we wanted was the total number of customers (across all states), we could do this scalar aggregate query” SELECT COUNT(*) from Customer_T This query will return a single value, which is the total number of customers. That would be the sum of all the individual numbers returned from the aggregate query displayed in this slide.

60 row value and aggregates (w group)
SELECT S_ID, MAJOR, GPA FROM STUDENT SELECT MAJOR, AVG(GPA) FROM STUDENT GROUP BY MAJOR SELECT T S_ID, MAJOR, AVG(GPA) FROM STUDENT GROUP BY MAJOR SELECT COUNT(S_ID), MAJOR, AVG(GPA) FROM STUDENT GROUP BY MAJOR What? How many rows? What? How many rows? Discuss Discuss Example: DNC students

61 Aggregate function w and w/o group by
Without GROUP BY, the aggregate functions (SUM, AVG, COUNT etc) are sum/avg/count of the WHOLE TABLE With GROUP BY, … It is important to know the differences between the two, so one can correctly and properly Interpret the query outcomes Design the query Example: STUDENT table; GROUP BY Major PRODUCT table; GROUP BY ProductLine

62 Qualifying Results by Categories Using the HAVING Clause
For use with GROUP BY Like a WHERE clause, but it operates on groups (categories), not on individual rows. Here, only those groups with total numbers greater than 1 will be included in final result. The HAVING clause restricts which groups will be returned in an vector aggregate query. It’s like a WHERE clause, but operates on groups, not individual rows.

63 A Query with both WHERE and HAVING
Discussion: Switch? First, the WHERE clause restricts us to only products with certain types of Product Finish. Then, after that they are grouped by the product finish and average prices calculated for each group. Only the groups with average price less than 750 are included in the final result, via the HAVING clause. After all this is done, they are ORDERed alphabetically by ProductFinish. So, the WHERE clause operated to restrict the number of rows, and then the HAVING was used to restrict the number of groups. Discussions

64 Query with both WHERE & HAVING (2)
WHERE screens rows those products whose finish are among (…) Criteria applied to ALL rows Before the grouping HAVING screens groups those groups whose average price is … Criteria applied to groups After the grouping Observe the SELECT-clause: why ProductFinish can be there? First, the WHERE clause restricts us to only products with certain types of Product Finish. Then, after that they are grouped by the product finish and average prices calculated for each group. Only the groups with average price less than 750 are included in the final result, via the HAVING clause. After all this is done, they are ORDERed alphabetically by ProductFinish. So, the WHERE clause operated to restrict the number of rows, and then the HAVING was used to restrict the number of groups.

65 Using and Defining Views
Views provide users controlled access to tables Base Table–table containing the raw data Dynamic View A “virtual table” created dynamically upon request by a user No data actually stored; instead data from base table made available to user Based on SQL SELECT statement on base tables or other views Materialized View Copy or replication of data Data actually stored Must be refreshed periodically to match corresponding base tables

66 Views Syntax of CREATE VIEW: CREATE VIEW view-name AS
SELECT (that provides the rows and columns of the view) Example: CREATE VIEW ORDER_TOTALS_V AS SELECT PRODUCT_ID PRODUCT, SUM(STANDARD_PRICE*QUANTITY) TOTAL FROM INVOICE_V GROUP BY PRODUCT_ID;

67 Sample CREATE VIEW View has a name.
View is based on a SELECT statement. CHECK_OPTION works only for updateable views and prevents updates that would create rows not included in the view.

68 Advantages of Views Simplify query commands Assist with data security (but don't rely on views for security, there are more important security measures) Enhance programming productivity Contain most current base table data Use little storage space Provide customized view for user Establish physical data independence

69 Disadvantages of Views
Use processing time each time view is referenced May or may not be directly updateable


Download ppt "Chapter 6: Introduction to SQL"

Similar presentations


Ads by Google