340 likes | 424 Views
Chapter 1. Structured Query Language(SQL). Outlines. Data Definition Language (DDL) Creating Tables Altering Tables Dropping Tables Data Manipulation Language (DML) INSERT, UPDATE, DELETE SELECT Statements Union, Intersect, Minus Operations Joins (Simple, Natural)
E N D
Chapter 1 Structured Query Language(SQL)
Outlines • Data Definition Language (DDL) • Creating Tables • Altering Tables • Dropping Tables • Data Manipulation Language (DML) • INSERT, UPDATE, DELETE SELECT Statements • Union, Intersect, Minus Operations • Joins (Simple, Natural) • Outer Joins (Left, Right, Full)
Creating tables • Syntax: • CREATETABLE table-name • ( • column-name-1 data-type-1 [constraint], • column-name-2 data-type-2 [constraint], • … • column-name-n data-type-n [constraint] • ); • constraint will be one of the following: • PRIMARY KEY (PK) • FOREIGN KEY (FK) • NOT NULL (NN) • UNIQUE (U) • CHECK
Example of Table Creation CREATETABLE Sailors (sidNUMBER(4)PRIMARYKEY, snameCHAR(30), rating NUMBER(2), age NUMBER(2)); CREATETABLE Boats (bid NUMBER(2)PRIMARYKEY, bnameCHAR(30), color CHAR(30) CHECK(COLORIN(‘Red‘, ‘Green’, ‘Blue’, ‘Yellow’))); CREATETABLE Reserves (sidNUMBER(4), bid NUMBER(2), day DATEDEFAULTSYSDATE, CONSTRAINTreserves_pkPRIMARYKEY(sid, bid), CONSTRAINTreserves_sid_fkFOREIGNKEY(sid)REFERENCES Sailors, CONSTRAINTreserves_bid_fkFOREIGNKEY(bid)REFERENCES Boats);
Cascading/Restricting tables • SQL allows to create a table with CASCADE and RESTRICT options. • CASCADE option deletes or updates the row from the parent table (containing PRIMARY KEYs), and automatically delete or update the matching rows in the child table (containing FOREIGN KEYs). • RESTRICT option bars the removal (i.e. using delete) or modification (i..e using update) of rows from the parent table. Examples: ON UPDATE CASCADE (or RESTRICT) ON DELETE CASCADE ON UPDATE SET DEFAULT ON UPDATE SET NULL
Renaming a table To rename a table, the SQL ALTER TABLE syntax is: ALTERTABLEtable_nameRENAMETOnew_table_name; Example: ALTERTABLE suppliers RENAMETO vendors;
Adding Constraints Constraints: • NOT NULL • UNIQUE • PRIMARY KEY • FOREIGN KEY • CHECK • DEFAULT Examples: ALTERTABLE Supplier ADDCONSTRAINTSupplier_PKPRIMARYKEY (Supplier_id); ALTERTABLE Product ADDCONSTRAINTProduct_FKFOREIGNKEY (Supplier_id) REFERENCES Supplier(Supplier_id);
Adding column(s) to a table Syntax: ALTERTABLEtable_nameADD( column_1 column-definition, column_2 column-definition, ... column_ncolumn_definition); Example: ALTERTABLE Employees ADDsalary NUMBER(6);
Modifying column(s) in a table Syntax: ALTERTABLEtable_nameMODIFY( column_1 column_type, column_2 column_type, ... column_ncolumn_type); Examples: ALTERTABLE supplier MODIFYsupplier_nameVARCHAR2 (100)NOTNULL; ALTERTABLE supplier MODIFY (supplier_nameVARCHAR2 (100)NOTNULL, city VARCHAR2 (75));
Drop column(s) in a table Syntax: ALTERTABLEtable_nameDROPCOLUMNcolumn_name; Example: ALTERTABLE supplier DROPCOLUMNsupplier_name;
Rename column(s) in a table Syntax: ALTERTABLEtable_nameRENAMECOLUMNold_name to new_name; Example: ALTERTABLE supplier RENAMECOLUMNsupplier_name to sname;
Removing Tables DROPTABLEtable-name [CASCADE | RESTRICT] DROPTABLE statement allows you to remove tables from your schema: DROPTABLEtable_name; DROPTABLEtable_nameCASCADECONSTRAINTS; Cascade constraints Specify CASCADECONSTRAINTS to drop all referential integrity constraints that refer to primary and unique keys in the dropped table.
Creating indexes Speed up random/sequential access to base table data Example: CREATEINDEX NAME_IDX ONCUSTOMER_T(CUSTOMER_NAME) This makes an index for the CUSTOMER_NAME field of the CUSTOMER_T table
Insert Statement • Adds data to a table INSERTINTO CUSTOMER_T VALUES (001, ‘Contemporary Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601); • Inserting a record that has some null attributes requires identifying the fields that actually get data INSERTINTO PRODUCT_T (PRODUCT_ID, PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICE, PRODUCT_ON_HAND) VALUES (1, ‘End Table’, ‘Cherry’, 175, 8); • Inserting from another table • INSERTINTO CA_CUSTOMER_T SELECT*FROM CUSTOMER_T WHERE STATE = ‘CA’;
Delete Statement • Removes rows from a table • Delete certain rows DELETEFROM CUSTOMER_T WHERE STATE = ‘HI’; • Delete all rows DELETEFROM CUSTOMER_T;
Update Statement It modifies data in existing rows. Syntax: UPDATEtable_nameSETcolumn1 = value1, column2 = value2,... WHEREsome_column = some_value; Example: UPDATE PRODUCT_T SET UNIT_PRICE = 775 WHERE PRODUCT_ID = 7; UPDATEPersons SETAddress=‘UAE', City=‘Abu Dhabi‘ WHERELastName=‘Al Ameri' ANDFirstName=‘Jasim‘;
SELECT Statement • Used for queries on single or multiple tables • Clauses of the SELECT statement: • SELECT • List the columns (and expressions) that should 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
SELECT Example Find products with standard price less than $275 SELECTPRODUCT_NAME, STANDARD_PRICE FROMPRODUCT_V WHERESTANDARD_PRICE < 275; Comparison Operators in SQL
SELECT Example Using Alias Alias is an alternative column or table name Example: SELECTCUST.CUSTOMER ASNAME, CUST.CUSTOMER_ADDRESS FROMCUSTOMER_V CUSTWHERENAME = ‘Home Furnishings’;
SELECT Example Using a Function Using the COUNT aggregate function to find totals SELECTCOUNT(*) FROMORDER_LINE_V WHEREORDER_ID = 1004; • Note: with aggregate functions you can’t have single-valued columns included in the SELECT clause
SELECT Example–Boolean Operators AND, OR, and NOT Operators for customizing conditions in WHERE clause SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICE FROMPRODUCT_V WHERE(PRODUCT_DESCRIPTION LIKE ‘%Desk’ ORPRODUCT_DESCRIPTION LIKE ‘%Table’) AND 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
Sorting Results with the ORDER BY Clause Sort the results first by STATE, and within a state by CUSTOMER_NAME SELECTCUSTOMER_NAME, CITY, STATE FROM CUSTOMER_V WHERESTATE IN (‘FL’, ‘TX’, ‘CA’, ‘HI’) ORDERBY STATE, CUSTOMER_NAME;
Aggregate Functions The five SQL functions include: COUNT: return number of values in specified column SUM: return sum of values in specified column AVG: return average of values in specified column MIN: return smallest value in specified column MAX: return largest value in specified column COUNT, MIN, MAX apply to numeric and non numeric fields SUM and AVG can only be applied to numeric fields Example: SELECTCUSTOMER_STATE, COUNT (CUSTOMER_STATE) FROMCUSTOMER_V GROUPBY CUSTOMER_STATE;
Qualifying Results by Categories Using the HAVING Clause For use with GROUP BY SELECTCUSTOMER_STATE, COUNT(CUSTOMER_STATE) FROM CUSTOMER_V GROUPBYCUSTOMER_STATE HAVINGCOUNT(CUSTOMER_STATE) > 1;
SQL: UNION Query • Given two relations R and S, the union of these two relations, denoted by R ᴜ S, is the set of all tuples that are currently present in R or are currently present in S or present in both relations. • Each SQL SELECT statement within the UNION query must have the same number of fields in the result sets with similar data types. Syntax: SELECT field1, field2, ... fieldnFROM table_name1 UNION SELECT field1, field2, ... fieldnFROM Table_name2; Example: SELECTsupplier_id, supplier_nameFROM suppliers WHEREsupplier_id > 2000 UNION SELECTcompany_id, company_nameFROM companies WHEREcompany_id > 1000 ORDERBY 2;
SQL: INTERSECT Query • Given two relations R and S, the intersection of these two relations, denoted by R ∩ S, is the set of tuples currently present in both relations. • Each SQL statement within the SQL INTERSECT query must have the same number of fields in the result sets with similar data types. Syntax: SELECT field1, field2, ... fieldnFROM table_name1 INTERSECT SELECT field1, field2, ... fieldnFROM Table_name2; Example: SELECTsupplier_id, supplier_nameFROM suppliers WHERE supplier_id > 2000 INTERSECT SELECT company_id, company_nameFROM companies WHERE company_id > 1000 ORDERBY 2;
SQL: MINUS Query • Given two relations R and S, the difference of these two relations, denoted by R - S, is the set of all tuples that are currently present in relation R and are not currently present in relation S. • This operation is NOT commutative: R – S ≠ S – R Syntax: SELECT field1, field2, ... fieldnFROM table_name1 MINUS SELECT field1, field2, ... fieldnFROM Table_name2; Example: SELECT supplier_id, supplier_nameFROM suppliers WHERE supplier_id> 2000 MINUS SELECT company_id, company_nameFROM companies WHERE company_id> 1000 ORDERBYSupplier_id;
Examples C_Programmer Java_Programmer C_Programmer ᴜ Java_Programmer = ? C_Programmer ∩ Java_Programmer = ? C_Programmer – Java_Programmer = ?
SQL Inner Join (simple join) • It is the most common type of SQL join. • SQL inner joins return all rows from multiple tables where the join condition is met. Example: SELECTsuppliers.supplier_id, suppliers.supplier_name, orders.order_dateFROM suppliers, orders WHEREsuppliers.supplier_id = orders.supplier_id; • This SQL inner join example would return all rows from the suppliers and orders tables where there is a matching supplier_id value in both the suppliers and orders tables.
Natural join The SQL NATURAL JOIN is a type of equi-join and is structured in such a way that, columns with same name of associate tables will appear once only. Example: SELECT*FROM Dept NATURALJOINEmp;
Outer Joins LEFT OUTER JOIN: All tuples in the left relation are preserved, even if they have no matching tuples in the right relation. RIGHT OUTER JOIN: All tuples in the right relation are preserved, even if they have no matching tuples in the left relation. FULL OUTER JOIN: This operation keeps all tuples in both the left and the right relations when no matching tuples are found, padding them with null values as needed.
Left Outer Join SELECT * FROM Dept LEFTOUTERJOINEmp ON Dept.ID = Emp.Dept_ID; Or SELECT * FROM Dept D, Emp E WHERE D.ID = E.Dept_ID(+);
Right Outer Join SELECT * FROM Dept RIGHTOUTERJOINEmp ON Dept.ID = Emp.Dept_ID;; Or SELECT* FROM Dept D, Emp E WHERE D.ID (+) = E.Dept_ID;
Full Outer Join SELECT * FROM Dept FULLOUTERJOINEmpON Dept.ID = Emp.Dept_ID; Or SELECT * FROM Dept D, Emp E WHERE D.ID = E.Dept_ID(+) UNION SELECT * FROM Dept D, Emp E WHERE D.ID(+) = E.Dept_ID;