The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Siti Izani, 2023-07-03 04:42:49

Database Design (1)

Database Design (1)

STRUCTURED QUERY LANGUAGE (SQL) AND DATABASE TRANSACTION MANAGEMENT FARIHAN ELYANA BINTI ZAHARI MIME AZRINA BINTI JAAFAR RUZIANA BINTI MOHAMAD RASLI 2021 JABATAN TEKNOLOGI MAKLUMAT DAN KOMUNIKASI ©All rights reserved. No part of this work covered by copyright may be produced or copied in any form or by any means(graphic, electronic or mechanical, including photocopying recording, recording taping, or information retrieval systems) without the written permission of the author. i


First Publishing 2021 All rights reserved. No part of this publication may be produced, distributed or transmitted in any form of by any means, including photocopying, recording or other electronic or mechanical methods, without the prior written permission of publisher. Published By: Department of Information Technology and Communication, Polytechnic Tuanku Syed Sirajuddin, 02600 Pauh Putra, Perlis No. Tel : 04-988 6200 No. Fax : 04-988 6300 www.ptss.edu.my eISBN : STRUCTED QUERY LANGUAGE (SQL) AND DATABASE TRANSACTION MANAGEMENT Edition 2021 Farihan Elyana Binti Zahari Mime Azrina Binti Jaafar Ruziana Binti Mohamad Rasli ii


A C K N OWL E D G E M E N T In the name of ALLAH, the Most Gracious and Most Merciful. Praise be to Allah SWT, whose blessing and guidance have helped us in completing this E-book Structured Query Language (SQL) and Database Transaction Management. Peace be upon Prophet Muhammad (PBUH), who was a blessing to mankind. Our sincere appreciation to the numerous parties who have participated directly or indirectly in the production of this E-book. Such appreciation goes to the Head of Department and colleague in Department of Information Technology and Communication who had given us the opportunity to develop this E-book. The assistance, guidance, and constant support during the publication of this E-book have helped us a lot in completing this E-book. We would also like to thank our family members who provided encouragement, patience, and support. Finally, we would wish the readers of this E-book to enjoy reading this Ebook and we do apologize for any omissions and errors. We hope that this module will be beneficial to all, especially Polytechnics students so that they can have a clearer view of the database development process using SQL. Farihan Elyana Binti Zahari Mime Azrina Binti Jaafar Ruziana Binti Mohamad Rasli iii


P R E F A C E This E-book is designed to provide a frame of reference for Polytechnic diploma courses in information technology or students majoring in related courses. The E-book is alternatively helpful to those who wish to keep enhancing their knowledge on Structured Query Language (SQL) and Database Transaction Management. This E-book consists of two main topics, which cover the topic of SQL and Database Transaction Management addressed by the Database Design course syllabus adapted by the Malaysian Polytechnics. Students are guided to implement the database design by creating a physical database using SQL. In the first part of the E-book, basic SQL syntax and the rules for constructing valid SQL statements are reviewed. The second part focuses on Transaction control technique which is important in Database Administration task. These two topics are important for student to know the process of constructing SQL, managing the tables in the database and also manage transaction that happens in the database. Finally, this E-book can also be beneficial to other students and readers who would like to learn on the basics of database. Hopefully, this E-book be beneficial in helping all in achieving a better knowledge and understanding which can provide readers with a better result. iv


Acknowledgement iii Preface iv TOPIC 1: STRUCTURED QUERY LANGUAGE (SQL) 1.1 Introduction to SQL 1 1.2 Data type 2 1.3 Data Definition Language (DDL) 8 1.4 Data Manipulation Language (DML) 16 1.5 SQL advanced commands and Aggregate Function 22 Exercise 44 TOPIC 2: DATABASE TRANSACTION MANAGEMENT 2.1 Transaction 45 2.2 Locking 50 2.3 Deadlock 53 2.4 Recovery Facilities 54 2.5 Transactional Control Language (TCL) 56 Exercise 60 References 61 T A BL E O F C O N T E N TS TOPIC PAGE v


•SQL is a command that allow users to create database and table structures, perform various types of data manipulation and data administration, and query the database to extract useful information. •It is relatively east to learn. •It is portable where the commands can be used in different types of Relational Database Management System (RDBMS). INTRODUCTION TO SQL STRUCTURED QUERY LANGUAGE (SQL) LEARNING OUTCOMES State the use of Structured Query Language (SQL). Explain the SQL data types Identify the types of SQL statements SQL CATEGORIES 1


There are three main types of data which are string, numeric, and date times as described by www.w3schools.com. STRING DATA TYPES 2


Difference Between CHAR and VARCHAR Name: ALI Name CHAR [5] ===> SIZE: 5 Name VARCHAR (5) ===> SIZE:5 Name VARCHAR (5) ===> SIZE:3 Name VARCHAR (5) ===> SIZE:4 CHAR VS VARCHAR 3


NUMERIC DATA TYPES 4


NUMERIC (Cont.) DATA TYPES 5


DATE & TIMES DATA TYPES 6


B_PRICE clearly requires some kind of numeric data type; defining it as a character field is not acceptable. Just as clearly, a B_TITLE is an obvious candidate for a character data type. For example, VARCHAR(50) fits well because book titles are “variable-length” character strings, and in this case, such strings may be up to 50 characters long. At first glance, it might seem logical to select a numeric data type for PUB_POSTCODE because it contains only digits. However, adding and subtracting area codes does not yield meaningful results. Therefore, selecting a character data type is more appropriate. This is true for many common attributes found in business data models. Selecting PUB_DATE to be a (Julian) DATE field rather than a character field is desirable because the Julian dates allow you to make simple date comparisons and to perform date arithmetic. For instance, if you have used DATE fields, you can determine how many days there are between them. Data-type selection is usually dictated by the nature of the data and by the intended use. For example: DATA TYPES EXAMPLE BOOK 7


DATA DEFINITION LANGUAGE (DDL) This command is used to develop, remove and manipulate structure of database, table and other database objects (view, index and others) LEARNING OUTCOMES DATA DEFINITION LANGUAGE (DDL) Identify the DDL statements in defining the table structure Identify the types of constraints in DDL statements: column constraints and table constraints Use the functions of the basic DDL commands STRUCTURED QUERY LANGUAGE (SQL) 8


CREATE COMMANDS 1 CREATE DATABASE To create a database, please follow the syntax below: Once the database had been created, the next steps is to create table. Table is used to store all the related information or data in the database. Table is a combination or rows and columns which have a set of data elements (values). Figure 1 shows an example of Customer table 1. 1. CREATE DATABASE database_name; Example: CREATE DATABASE Customer; Figure 1: Customer table DDL 9


TABLE STRUCTURE: Based on Figure 1, it can be seen that there are three attributes which are CustomerID, CustomerName, and Status. Each of these attributes has several values in it. 1.2 CREATE TABLE To create the table in the database, the following syntax must be used: CREATE TABLE Customer ( CustomerID Int(1) Unique, CustomerName Varchar(200) Not Null, Status Varchar(15) Not Null, PRIMARY KEY(CustomerID)); Based on the above example, it follows the basic rules for creating a table command which is: CREATE TABLE tablename ( Attribute1 Datatype1(size) Contraint1, Attribute2 Datatype2(size) Contraint2, .................. PRIMARY KEY((Attribute) FOREIGN KEY Attributes REFERENCE tablename); DDL 10


2. ALTER TABLE Alter table is used to add, delete, or modify columns in an existing table. It can also be used to add and drop various constraints on an existing table 2.1 Add new column or attribute in a table In order to add another column in an existing table, use the following syntax: ALTER TABLE table_name ADD newcol_name datatype(size) constraint ; Example: ALTER TABLE Customer ADD Email VARCHAR(50) NOT NULL ; New Customer table: 2.2 Modify size column or attributes from a table ALTER TABLE tbl_name MODIFY col_name datatype(size) constraint; Example: expend CustomerName saiz to 50 ALTER TABLE customer MODIFY CustomerName VARCHAR(50) NOT NULL; DDL 11


2.3 Remove column from a table The command to remove a column from an existing table is as follows: ALTER TABLE tbl_name DROP col_name; Example: Remove column Status from customer table ALTER TABLE customer DROP Status; Result: 3. DROP TABLE AND DATABASE 3.1 Remove/Delete Table from database The command to remove or delete a table from the database is as follows: DROP TABLE tbl_name; Example: Remove table customer DROP TABLE customer; DDL 12


3.2 DROP DATABASE To remove or delete a database, the use must ensure that the table is not being used anymore because once the user deleted the database, the tables that are in the database will be deleted together. The command to remove a database is as follows: DROP DATABASE db_name; Example: Remove database ptss DROP DATABASE ptss; DDL 13


CREATE TABLE VENDOR ( V_CODE INTEGER NOT NULL UNIQUE, V_NAME VARCHAR(35) NOT NULL, V_CONTACT VARCHAR(15) NOT NULL, V_AREACODE CHAR(3) NOT NULL, V_PHONE CHAR(8) NOT NULL, V_STATE CHAR(2) NOT NULL, V_ORDER CHAR(1) NOT NULL, PRIMARY KEY (V_CODE)); CREATE TABLE PRODUCT ( P_CODE VARCHAR(10) NOT NULL UNIQUE, P_DESCRIPT VARCHAR(35) NOT NULL, P_INDATE DATE NOT NULL, P_QOH SMALLINT NOT NULL, P_MIN SMALLINT NOT NULL, P_PRICE NUMBER(8,2) NOT NULL, P_DISCOUNT NUMBER(5,2) NOT NULL, V_CODE INTEGER, PRIMARY KEY (P_CODE), FOREIGN KEY (V_CODE) REFERENCES VENDOR (V_CODE) ON UPDATE CASCADE); EXAMPLE DDL SQL Constraint 14


The NOT NULL constraint ensures that a column does not accept nulls. The UNIQUE constraint ensures that all values in a column are unique. The DEFAULT constraint assigns a value to an attribute when a new row is added to a table. The end user may, of course, enter a value other than the default value. The CHECK constraint is used to validate data when an attribute value is entered. The CHECK constraint does precisely what its name suggests: it checks to see that a specified condition exists. Examples of such constraints include the following: PRIMARY KEY (V_CODE) In the PRODUCT table’s CREATE TABLE sequence, note that referential integrity has been enforced by specifying in the PRODUCT table: FOREIGN KEY (V_CODE) REFERENCES VENDOR ON UPDATE CASCADE Besides the PRIMARY KEY and FOREIGN KEY constraints, the ANSI SQL standard also defines the following Constraints: * The minimum order value must be at least 10. * The date must be after April 15, 2010. SQL CONSTRAINTS 15


Data Manipulation Language (DML) is used to add, display, update or modify and remove data or row or instance in a table. There are four main DML commands which are: LEARNING OUTCOMES DATA MANIPULATION LANGUAGE (DML) Identify the uses of DML statements. Use the functions of the following DML commands. STRUCTURED QUERY LANGUAGE (SQL) 16


The row contents are entered between parentheses. Note that the first character after VALUES is a parenthesis and that the last character in the command sequence is also a parenthesis. Character (string) and date values must be entered between apostrophes ('). Numerical entries are not enclosed in apostrophes. Attribute entries are separated by commas. A value is required for each column in the table. 1.INSERT Command SQL requires the use of the INSERT command to enter data into a table. 1.1 Add row into a table Option1 : Can be used to add data to all columns or specific column only. INSERT INTO tbl_name (att1, att2, att3, …) VALUES (val1, val2, val3, …); Example: INSERT INTO customer (CustomerID, CustomerName, Status) VALUES (1, ‘Google’, ‘Active’); Option2 : Can be used to add data to all columns only. INSERT INTO tbl_name VALUES (val1, val2, val3, …); Example: INSERT INTO customer VALUES (1, ‘Google’, ‘Active’); In the preceding data entry lines, observe that: DML - INSERT 17


1.2 Inserting Rows with Null Attributes In order to insert data will null attributes, the NULL keywords in needed as in the example below: Example: INSERT INTO PRODUCT VALUES ('BRT-345','Titanium drill bit', '18-Oct-09', 75, 10, 4.50, 0.06, NULL); Incidentally, note that the NULL entry is accepted only because the V_CODE attribute is optional—the NOT NULL declaration was not used in the CREATE TABLE statement for this attribute. 1.3 Inserting Rows with Optional Attributes There might be occasions when more than one attribute is optional. Rather than declaring each attribute as NULL in the INSERT command, you can indicate just the attributes that have required values. You do that by listing the attribute names inside parentheses after the table name. The value will be inserted based on the attribute accordingly. For the purpose of this example, assume that the only required attributes for the PRODUCT table are P_CODE and P_DESCRIPT: INSERT INTO PRODUCT(P_CODE, P_DESCRIPT) VALUES ('BRT-345','Titanium drill bit'); DML - INSERT 18


Use the UPDATE command is to modify data in a table. The UPDATE command is a set-oriented operator. Therefore, if you don’t specify a WHERE condition, the UPDATE command will apply the changes to all rows in the specified table. 2. UPDATE command 2.1 To update one data only in a column UPDATE tbl_name SET col_name=new_value WHERE condition; Example: If you want to change P_INDATE from December 13, 2009, to January 18, 2010, using the primary key (13-Q2/P2). UPDATE PRODUCT SET P_INDATE = '18-JAN-2010' WHERE P_CODE = '13-Q2/P2'; DML - UPDATE 19


2.3 To update all value in specific column in the table In order to update all values in specific columns in the table, follow the command structure below: UPDATE tbl_name SET col_name=new_value; Example: UPDATE customer SET Status=’Inactive’; 2.2 To update multiple data Multiple column, To update multiple columns, a comma (,) is used to separate between each columns that need to be updated such as in the command structure below: UPDATE tbl_name SET col1_name=new_value, col2_name=new_value, … WHERE condition; Example: UPDATE customer SET CustomerName=’Apple Inc’, Status=’Active WHERE CustomerID=3; DML - UPDATE 20


is used to remove data from the table. 3. DELETE command 3.1 Remove specific rows DELETE FROM tbl_name WHERE condition; Example 1: If you want to delete from the PRODUCT table the product that you added earlier whose code (P_CODE) is 'BRT-345', use: DELETE FROM PRODUCT WHERE P_CODE = 'BRT-345'; In that example, the primary key value lets SQL find the exact record to be deleted. However, deletions are not limited to a primary key match; any attribute may be used. Example 2: in your PRODUCT table, you will see that there are several products for which the P_MIN attribute is equal to 5. Use the following command to delete all rows from the PRODUCT table for which the P_MIN is equal to 5: DELETE FROM PRODUCT WHERE P_MIN = 5; 3.2 Remove all rows in a table DELETE FROM tbl_name; Example: DELETE FROM customer; DML - DELETE 21


Once the data had been updated, in order to view the data, the SELECT command is used to check the PRODUCT table’s listing: You can select partial table contents by placing restrictions on the rows to be included in the output. This is done by using the WHERE clause to add conditional restrictions to the SELECT statement. The following syntax enables you to specify which rows to select: SELECT * FROM PRODUCT; SELECT columnlist FROM tablelist [WHERE conditionlist ]; LEARNING OUTCOMES SELECTING ROWS Use the functions SQL advanced commands. Use the functions SQL Aggregate Functions. STRUCTURED QUERY LANGUAGE (SQL) 22


SELECTING ROWS The SELECT statement retrieves all rows that match the specified condition(s) —also known as the conditional criteria—you specified in the WHERE clause. The conditionlist in the WHERE clause of the SELECT statement is represented by one or more conditional expressions, separated by logical operators. The WHERE clause is optional. Comparison table TRUE FALSE 23


The following example uses the “not equal to” operator: The output will lists all of the rows for which the vendor code is not 21344. The command sequence: Date procedures are often more software-specific than other SQL procedures. For example, the query to list all of the rows in which the inventory stock dates occur on or after January 20, 2010 will look like this: A. Not equal Operator <> or != SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE <> 21344; SELECT P_DESCRIPT, P_QOH, P_MIN, P_PRICE FROM PRODUCT WHERE P_PRICE <= 10; B.Using Comparison Operators on Dates SELECT P_DESCRIPT, P_QOH, P_MIN, P_PRICE, P_INDATE FROM PRODUCT WHERE P_INDATE >= '20-Jan-2010'; COMPARISON 24


Suppose that you want to determine the total value of each of the products currently held in inventory. Logically, that determination requires the multiplication of each product’s quantity on hand by its current price. You can accomplish this task with the following command: To make the output more readable, the SQL standard permits the use of aliases for any column in a SELECT statement. An alias is an alternative name given to a column or table in any SQL statement. For example, you can rewrite the previous SQL statement as: C. Using Computed Columns and Column Aliases SELECT P_DESCRIPT, P_QOH, P_PRICE, P_QOH * P_PRICE FROM PRODUCT; SELECT P_DESCRIPT, P_QOH, P_PRICE, P_QOH * P_PRICE AS TOTVALUE FROM PRODUCT; COMPARISON 25


The rules of precedence are the rules that establish the order in which computations are completed. For example, note the order of the following computational sequence: The application of the rules of precedence will tell you that In the real world, a search of data normally involves multiple conditions. For example, when you are buying a new house, you look for a certain area, a certain number of bedrooms, bathrooms, stories, and so on. In the same way, SQL allows you to include multiple conditions in a query through the use of logical operators. Arithmetic Operators: The Rule 1. Perform operations within parentheses. 2. Perform power operations. 3. Perform multiplications and divisions. 4. Perform additions and subtractions. 8 + 2 * 5 = 8 + 10 = 18, but (8 + 2) * 5 = 10 * 5 = 50. D. Logical Operators: OR The logical operators are AND, OR, and NOT. For example, if you want a list of the table contents for either the V_CODE = 21344 or the V_CODE = 24288, you can use the OR operator, as in the following command sequence: SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE = 21344 OR V_CODE = 24288; COMPARISON 26


The logical AND has the same SQL syntax requirement. The following command generates a list of all rows for which P_PRICE is less than $50 and for which P_INDATE is a date occurring after January 15, 2010: You can combine the logical OR with the logical AND to place further restrictions on the output. For example, suppose that you want a table listing for the following conditions: The required listing can be produced by using: E. Logical Operators: AND SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE P_PRICE < 50 AND P_INDATE > '15-Jan-2010'; F. Logical Operators: AND and OR The P_INDATE is after January 15, 2010, and the P_PRICE is less than $50. Or the V_CODE is 24288. SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE (P_PRICE < 50 AND P_INDATE > '15-Jan-2010') OR V_CODE = 24288; COMPARISON 27


The logical operator NOT is used to negate the result of a conditional expression. That is, in SQL, all conditional expressions evaluate to true or false. If an expression is true, the row is selected; if an expression is false, the row is not selected. The NOT logical operator is typically used to find the rows that do not match a certain condition. For example, if you want to see a listing of all rows for which the vendor code is not 21344, use the command sequence: ANSI-standard SQL allows the use of special operators in conjunction with the WHERE clause. These special operators include: If you use software that implements a standard SQL, the operator BETWEEN may be used to check whether an attribute value is within a range of values. G. Logical Operators: NOT SELECT * FROM PRODUCT WHERE NOT (V_CODE = 21344); H. Special Operators * BETWEEN: Used to check whether an attribute value is within a range * IS NULL: Used to check whether an attribute value is null * LIKE: Used to check whether an attribute value matches a given string pattern * IN: Used to check whether an attribute value matches any value within a value list * EXISTS: Used to check whether a subquery returns any rows COMPARISON 28


For example, if you want to see a listing for all products whose prices are between $50 and $100, use the following command sequence: If your DBMS does not support BETWEEN, you can use: Standard SQL allows the use of IS NULL to check for a null attribute value. For example, suppose that you want to list all products that do not have a vendor assigned (V_CODE is null). Such a null entry could be found by using the command sequence: The LIKE special operator is used in conjunction with wildcards to find patterns within string attributes. Standard SQL allows you to use the percent sign (%) and underscore (_) wildcard characters to make matches when the entire string is not known: SELECT * FROM PRODUCT WHERE P_PRICE BETWEEN 50.00 AND 100.00; SELECT * FROM PRODUCT WHERE P_PRICE > 50.00 AND P_PRICE < 100.00; I. The IS NULL Special Operator SELECT P_CODE, P_DESCRIPT, V_CODE FROM PRODUCT WHERE V_CODE IS NULL; J. The LIKE Special Operator • % means any and all following or preceding characters are eligible. • For example: •'J%' includes Johnson, Jones, Jernigan, July, and J-231Q. •'Jo%' includes Johnson and Jones. COMPARISON 29


For example, the following query would find all VENDOR rows for contacts whose last names begin with Smith. The output can be Smith, Smiths, and Smithson. Many queries that would require the use of the logical OR can be more easily handled with the help of the special operator IN. For example, the query: can be handled more efficiently with: Note that the IN operator uses a value list. All of the values in the list must be of the same data type. Each of the values in the value list is compared to the attribute—in this case, V_CODE. If the V_CODE value matches any of the values in the list, the row is selected. In this example, the rows selected will be only those in which the V_CODE is either 21344 or 24288. •'%n' includes Johnson and Jernigan. • _ means any one character may be substituted for the underscore. For example: •'_23-456-6789' includes 123-456-6789, 223-456-6789, and 323-456-6789. •'_23-_56-678_' includes 123-156-6781, 123-256-6782, and 823-956-6788. •'_o_es' includes Jones, Cones, Cokes, totes, and roles. SELECT V_NAME, V_CONTACT, V_AREACODE, V_PHONE FROM VENDOR WHERE V_CONTACT LIKE 'Smith%'; K. The IN Special Operator SELECT * FROM PRODUCT WHERE V_CODE = 21344 OR V_CODE = 24288; SELECT * FROM PRODUCT WHERE V_CODE IN (21344, 24288); COMPARISON 30


The EXISTS special operator can be used whenever there is a requirement to execute a command based on the result of another query. That is, if a subquery returns any rows, run the main query; otherwise, don’t. For example, the following query will list all vendors, but only if there are products to order: L. The EXISTS Special Operator SELECT * FROM VENDOR WHERE EXISTS (SELECT * FROM PRODUCT WHERE P_QOH <= P_MIN); COMPARISON 31


The ORDER BY clause is especially useful when the listing order is important to you. The syntax is: Although you have the option of declaring the order type—ascending or descending—the default order is ascending. For example, if you want the contents of the PRODUCT table listed by P_PRICE in ascending order, use: Additional Select Query Keyword 1)Order By 2)Distinct 3)Count 4)Max 5)Min 6)Sum 7)Avg 8)Group By 9)Having A. Ordering a list using Order By Command SELECT columnlist FROM tablelist [WHERE conditionlist ] [ORDER BY columnlist [ASC | DESC] ] ; SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE FROM PRODUCT ORDER BY P_PRICE; SELECT QUERY KEYWORD 32


SQL’s DISTINCT clause produces a list of only those values that are different from one another. For example, the command: It will yields only the different (distinct) vendor codes (V_CODE) that are encountered in the PRODUCT table B. Listing Unique Values using Distinct Command SELECT DISTINCT V_CODE FROM PRODUCT; SELECT QUERY KEYWORD 33


SQL can perform various mathematical summaries for you, such as counting the number of rows that contain a specified condition, finding the minimum or maximum values for some specified attribute, summing the values in a specified column, and averaging the values in a specified column. The COUNT function is used to tally the number of non-null values of an attribute. COUNT can be used in conjunction with the DISTINCT clause. The following SQL statement counts the total number of product in the Product table which price less and equal to 10.00. The following SQL statement counts the total number of V_CODE and eliminate duplicate value in the Product table which price less and equal to 10.00. A. Count SELECT COUNT (*) FROM PRODUCT WHERE P_PRICE < = 10.00 ; SELECT COUNT (DISTINCT V_CODE) FROM PRODUCT WHERE P_PRICE < = 10.00 ; AGGREGATE FUNCTIONS 34


The MAX and MIN functions help you find answers to problems such as the: The highest price, $256.99, is supplied by the first SQL command set in Figure below. The second SQL command set shown the minimum price of $4.99. The SUM function computes the total sum for any specified attribute, using whatever condition(s) you have imposed. For example, if you want to compute the total amount owed by your customers, you could use the following command: You could also compute the sum total of an expression. For example, if you want to find the total value of all items carried in inventory, you could use: B. MAX and MIN * Highest (maximum) price in the PRODUCT table. * Lowest (minimum) price in the PRODUCT table. SELECT MAX(P_PRICE) FROM PRODUCT; OUTPUT : SELECT MIN(P_PRICE) FROM PRODUCT; OUTPUT: C. Sum SELECT SUM(CUS_BALANCE) AS TOTBALANCE FROM CUSTOMER; SELECT SUM(P_QOH * P_PRICE) AS TOTVALUE FROM PRODUCT; AGGREGATE FUNCTIONS 35


Because the total value is the sum of the product of the quantity on hand and the price for all items. The AVG function format is similar to those of MIN and MAX and is subject to the same operating restrictions. Frequency distributions can be created quickly and easily using the GROUP BY clause within the SELECT statement. The syntax is: D. AVG SELECT P_CODE,P_PRICE, V_CODE FROM PRODUCT WHERE P_PRICE > ( SELECT AVG(P_PRICE) FROM PRODUCT) ORDER BY P_PRICE DESC; OUTPUT : E. Grouping Data Using Group By SELECT columnlist FROM tablelist [WHERE conditionlist ] [GROUP BY columnlist ] [HAVING conditionlist ] [ORDER BY columnlist [ASC | DESC] ] ; AGGREGATE FUNCTIONS 36


The GROUP BY clause is generally used when you have attribute columns combined with aggregate functions in the SELECT statement. The GROUP BY clause is valid only when used in conjunction with one of the SQL aggregate functions, such as COUNT, MIN, MAX, AVG, and SUM. A particularly useful extension of the GROUP BY feature is the HAVING clause. The HAVING clause operates very much like the WHERE clause in the SELECT statement. However, the WHERE clause applies to columns and expressions for individual rows, while the HAVING clause is applied to the output of a GROUP BY operation. SELECT P_SALECODE, AVG(P_PRICE) FROM PRODUCT GROUP BY P_SALECODE; OUTPUT: The Group By Feature’s Having Clause AGGREGATE FUNCTIONS 37


For example, suppose that you want to generate a listing of the number of products in the inventory supplied by each vendor. However, this time you want to limit the listing to products whose prices average below $10. You can also combine multiple clauses and aggregate functions. For example, consider the following SQL statement: This statement will do the following: Aggregate the total cost of products grouped by V_CODE. SELECT V_CODE, COUNT(DISTINCT (P_CODE)), AVG(P_PRICE) FROM PRODUCT GROUP BY V_CODE HAVING AVG(P_PRICE ) < 10; OUTPUT: SELECT V_CODE, SUM(P_QOH * P_PRICE) AS TOTCOST FROM PRODUCT GROUP BY V_CODE HAVING (SUM(P_QOH * P_PRICE) > 500) ORDER BY SUM(P_QOH * P_PRICE) DESC; * Select only the rows having totals that exceed $500. * List the results in descending order by the total cost. AGGREGATE FUNCTIONS 38


The ability to combine (join) tables on common attributes is perhaps the most important distinction between a relational database and other databases. A join is performed when data are retrieved from more than one table at a time. To join tables, you simply list the tables in the FROM clause of the SELECT statement. The DBMS will create the Cartesian product of every table in the FROM clause. However, to get the correct result—that is, a natural join—you must select only the rows in which the common attribute values match. To do this, use the WHERE clause to indicate the common attributes used to link the tables (this WHERE clause is sometimes referred to as the join condition). When the same attribute name appears in more than one of the joined tables, the source table of the attributes listed in the SELECT command sequence must be defined. SELECT P_DESCRIPT, P_PRICE, V_NAME, V_CONTACT, V_AREACODE, V_PHONE FROM PRODUCT, VENDOR WHERE PRODUCT.V_CODE = VENDOR.V_CODE; JOINING DATABASE 39


RELATIONAL SET OPERATORS In this section, you will learn how to use three SQL commands (UNION, INTERSECT, and MINUS) to implement the union, intersection, and difference relational operators. In previous chapters, you learned that SQL data manipulation commands are set-oriented; that is, they operate over entire sets of rows and columns (tables) at once. Using sets, you can combine two or more sets to create new sets (or relations). UNION, INTERSECT, and MINUS work properly only if relations are unioncompatible, which means that the number of attributes must be the same and their corresponding data types must be alike. In practice, some RDBMS vendors require the data types to be “compatible” but not necessarily “exactly the same.” For example, compatible data types are VARCHAR (35) and CHAR (15). In that case, both attributes store character (string) values; the only difference is the string size. Another example of compatible data types is NUMBER and SMALLINT. Both data types are used to store numeric values. The UNION statement combines rows from two or more queries without including duplicate rows. The syntax of the UNION statement is: In other words, the UNION statement combines the output of two SELECT queries. Remember that the SELECT statements must be union-compatible. That is, they must return the same number of attributes and similar data types. Union query UNION query 40


The CUSTOMER table contains 10 rows, while the CUSTOMER_2 table contains 7 rows. Customers Dunne and Olovski are included in the CUSTOMER table as well as in the CUSTOMER_2 table. The UNION query yields 15 records because the duplicate records of customers Dunne and Olovski are not included. In short, the UNION query yields a unique set of records. Union Query SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, CUS_PHONE FROM CUSTOMER UNION SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, CUS_PHONE FROM CUSTOMER_2; Customer table Customer2 table Result of Union RELATIONAL SET OPERATORS 41


The INTERSECT statement can be used to combine rows from two queries, returning only the rows that appear in both sets. The syntax for the INTERSECT statement is: To generate the list of duplicate customer records, you can use: Intersect query INTERSECT query SELECT CUS_LNAME, CUS_FNAME, CUS_PHONE FROM CUSTOMER INTERSECT SELECT CUS_LNAME, CUS_FNAME, CUS_PHONE FROM CUSTOMER_2; OUTPUT : RELATIONAL SET OPERATORS 42


The MINUS statement in SQL combines rows from two queries and returns only the rows that appear in the first set but not in the second. The syntax for the MINUS statement is: For example, if the SaleCo managers want to know what customers in the CUSTOMER table are not found in the CUSTOMER_2 table, they can use: Minus query MINUS query SELECT CUS_LNAME, CUS_FNAME, CUS_PHONE FROM CUSTOMER MINUS SELECT CUS_LNAME, CUS_FNAME, CUS_PHONE FROM CUSTOMER_2; OUTPUT: RELATIONAL SET OPERATORS 43


CREATE a database named B2CTRAVEL. CREATE table EMPLOYEE and DEPARTMENT. INSERT all rows in the EMPLOYEE and DEPARTMENT tables. SELECT list of EMPLOYEE with a salary greater than 3000. SELECT EMPLOYEE id and name whose name ends with the keyword 'han'. SELECT EMPLOYEE records with undefined department code. Calculate minimum, maximum, and average value for EMPLOYEE salary. Display average salary's value for every department code. SELECT EMPLOYEE id, name, and their DEPARTMENT name. JOIN table EMPLOYEE and DEPARTMENT to display a list of EMPLOYEE records from Accounting DEPARTMENT. Based on the EMPLOYEE and DEPARTMENT tables, answer all the following questions: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. EXERCISE EMPLOYEE Instruction: DEPARTMENT 44


Click to View FlipBook Version