+ All Categories
Home > Documents > [8] 5-SQL-part2-new

[8] 5-SQL-part2-new

Date post: 03-Sep-2015
Category:
Upload: izza-nasir
View: 222 times
Download: 0 times
Share this document with a friend
Description:
database
55
STRUCTURED QUERY LANGUAGE (SQL) Chapter 5: Part 2: DML
Transcript

Slide 1

STRUCTURED QUERY LANGUAGE (SQL)Chapter 5:Part 2:DML

Objectives2To be able to apply SQL command.How to use DML in SQL

2 major components:Data Definition Language (DDL)defining database structure.allows database objects such as schemas, domains, tables, views and indexes to be created and destroyed. Data Manipulation Language (DML)retrieving and updating data.used to populate and query the tables.data manipulation.

2Data Manipulation LanguageManipulate dataDML3Data Manipulation Language(DML)4Data Manipulation in SQL is an ability for manipulating the data to provide information needs by users.

Manipulating the data referees to process of:selecting the datado some operation at the datauser view it or save it in the database

SELECT * FROM printerWHERE color = red OR color = blue;DML: Queries: SELECT Statement5SELECT StatementThe SELECT statement allows you to find, retrieve, and display data.

To execute the SELECT statement on a table, you must be the table owner, have DBA or SYSADM security privileges, or have the SELECT privilege for that table.

The result of SELECT statement is a set of rows known as the result set, which meets the conditions specified in the SELECT statement

SQL SELECT Syntax

NoteSQL is not case sensitive { SELECT is the same as select }

SELECT column_name(s)FROM table_name;SELECT *FROM table_name;DML: Queries: SELECT Statement6printerNOdescriptioncolorpriceP123Dot-matrixRed249.56HP874Laser JetBlue559.99Select all data from table printer.

Select printerNO and price from table printer.

SELECT *FROM printer;SELECT printerNO, priceFROM printer;printerNOpriceP123249.56HP874559.99DML: Queries: SELECT DISTINCT Statement7SELECT DISTINCT StatementIn a table, some of the columns may contain duplicate values. The DISTINCT keyword can be used to return only distinct (different) values.

SQL SELECT DISTINCT Syntax

SELECT DISTINCT column_name(s)FROM table_name;DML: Queries: SELECT DISTINCT Statement8The following statement only will select the distinct values from the column named city from table staff.

SELECT DISTINCT cityFROM staff;staffNOstaffNAMEcityABC987NadzKuala LumpurABC988AinaJerantutABC999HalimatonJerantutcityKuala LumpurJerantutSQL LIKE Operator9The LIKE operator is used in a WHERE statement to search for a specified pattern in a column.

SQL LIKE Syntax

NoteThe LIKE operator is commonly used with SQL Wildcards

SELECT column_name(s)FROM table_nameWHERE column_name LIKE patern;SQL LIKE Operator10staffNOstaffNAMEcityABC987NadzKuala LumpurSELECT *FROM staffWHERE city LIKE K%;The following select staffs living in a city start with K from table staff.SQL Wildcards11SQL wildcards can be used when searching for data in a database.SQL wildcards can substitute for one or more characters when searching for data in a database.SQL wildcards must be used with the SQL LIKE operator.With SQL, the following wildcards can be used:WildcardDescription%A substitute for zero or more characters _A substitute for exactly one character[charlist]Any single character in charlist[^charlist] or[!charlist]Any single character not in charlistWildcards: Using The % Wildcard12Select staff living in the city that start with La from staff table.

Select staff living in the city that contain pattern wi from staff table.

SELECT *FROM staffWHERE city LIKE "La%";SELECT *FROM staffWHERE city LIKE "%wi%";Wildcards: Using The _ Wildcard13Select staff with a name that starts with any character, followed by da from staff table.

Select staff with a name that starts with "S", followed by any character, followed by "ar", followed by any character, followed by "s" from staff table.

SELECT *FROM staffWHERE staffNAME LIKE "_da";SELECT *FROM staffWHERE staffNAME LIKE "S_ar_s";Wildcards: Using The [charlist] Wildcard14Select staff with a name that starts with "a" or "s" or "p" from staff table.

Select staff name that do not starts with "a" or "s" or "p" from staff table.

SELECT *FROM staffWHERE staffNAME LIKE "[asp]%";SELECT *FROM staffWHERE staffNAME LIKE "[!asp]%";DML: Data Entry15The INSERT INTO command inserts new rows into a table.

When you insert data into a child table that has a foreign key linking it to a parent table, you must obey referential integrity rules.

This means you cannot insert a value into a child key that does not exist in the parent key unless it is a NULL value.

You must insert a new row into the parent key first.

To insert a string that contains a single quote, you must replace the single quote in the string with two consecutive single quotes. DML: Data Entry16SQL INSERT INTO SyntaxIt is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values:

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_nameVALUES (value1, value2,);INSERT INTO table_name (column1,column2,)VALUES (value1, value2,);DML: Data Entry17staffNOstaffNAMEcityABC123NorainIpohThe following insert values into table staff.

INSERT INTO staff VALUES (ABC123, Norain', Ipoh);DML: Data Entry18Insert a new customer for the following table.

insert into tblcustomer (customerno, customername, customeremail)values (C001, Alya Qiesya, [email protected]);

DML: Deleting Table Rows19The DELETE command deletes all rows matching the search condition from a table.

You can only delete rows from a single table, and you cannot delete rows from the system tables.

To execute the DELETE command, you must be the table owner, have delete privilege on the table, or have DBA or SYSADM security privileges.

DML: Deleting Table Rows 20SQL DELETE Syntax

NoteNotice the WHERE clause in the DELETE syntax. The WHERE clausespecifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!

DELETE FROM table_nameWHERE some column=some valueDML: Deleting Table Rows21DELETE record as specified in WHERE clause.

The following example deletes all staff whose name begins with Muhammad" from the staff table.

The following example deletes staff number ABC125 from the staff table.DELETE FROM staffWHERE staffNO=ABC123 AND city=Ipoh;DELETE FROM staffWHERE staffNAME LIKE Muhammad%;DELETE FROM staffWHERE staffNO =ABC125;DML: Making Changes to Data Items22The UPDATE command updates existing rows in a table.

When you update a column, the new column values must satisfy the column constraints and referential integrity.

If the column has a DEFAULT value defined, you can use the DEFAULT keyword to set the value of the column to the default value. DML: Making Changes to Data Items23SQL UPDATE Syntax

NoteNotice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

UPDATE table_nameSET column1=value,column2=value2,WHERE some column=some valueDML: Making Changes to Data Items24Shows how to update the staff table and change the city value for staff named Rosliza".

Shows how to give a salary raise of 5% to staff named Wafiy".

Update description for printer with printerNO F380.UPDATE staffSET city=BangiWHERE staffNAME = Rosliza;UPDATE staffSET salary=salary*1.05WHERE staffNAME = Wafiy;UPDATE printerSET description=KOWHERE printerNO = F380;DML: COMMIT25The COMMIT statement terminates the current transaction and makes allchanges under the transaction persistent.

COMMITis used for saving the data that has been changed permanently because whenever you perform any DML like UPDATE, INSERT or DELETE then you are required to write COMMIT at the end of all or every DML operation in order to save it permanently. If you do not write COMMIT and your program crashes then your data will be restored into its previous condition.

The COMMIT statement has the following general format:

UPDATE printer SET indate = 15/01/2007' WHERE printerNO = 'F380'; COMMIT;DML: ROLLBACK26The ROLLBACK statement terminates the current transaction and cancel all changes made under the transaction.

ROLLBACK is used if you want to restore your data into its previous condition.ROLLBACK can be write at any time after the DML queries has been written but remember once COMMIT has been written then you cannot rollback the data. You can only rollback the DML queries that have been written after the last commit statement.

The ROLLBACK statement has the following general format:INSERT INTO staffVALUES (ABC990, Shafiza, Johor) ROLLBACK;DML: COMMIT & ROLLBACK27The concept of COMMIT and ROLLBACK is designed fordata consistencybecause many uses manipulate data of the same table, using the same database so the user must get updated data.That is why COMMIT and ROLLBACK are used for.

COMMIT to save whatever has been done. It is used to permanently store it in memory.

ROLLBACKto undo something. If we use roll-back, the particular changes made are undone.DML: Compound Statement with SELECT 28SymbolMeaning=Equal to=Greater than or equal to

Not equal to**Some SQL version use != ANDto combine two search conditions which must be both true.

ORto combine two search conditions when one or the other (or both) must be true You can combine simple conditions with the logical operators AND, OR, and NOT to form compound conditions.DML: Compound Statement with SELECT 29Select only the staff live in Jengka AND age greater then or equal to 40 years old from table staff.

Select only the staff live in Temerloh OR age greater then or equal to 40 years old from table staff.

SELECT *FROM staffWHERE city=Jengka AND age >= 40;SELECT *FROM staffWHERE city=Temerloh AND age >= 40;DML: Compound Statement with SELECT 30Select only the staff live in Jengka OR Temerloh AND age greater then or equal to 40 years old from table staff.

SELECT *FROM staffWHERE (city=Jengka OR city=Temerloh) AND age >= 40;Do it!31Delete all biscuits with chocolate flavor from tblbiscuit.

Delete all order from customerC001 that have status cancel from tblorder.delete from tblbiscuitwhere bisFLAVOUR = chocolate;

delete from tblorderwhere custNO = C001 and status = cancel;

tblcustomer(custNO, custNAME, custEMAIL)tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE)tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status)32 Change all status to confirm for biscuit BIS101 for customer C135.

Increase biscuit price 10% for biscuit with strawberry flavor.update tblorderset status = confirmwhere custNO = C135;

update tblbiscuitset bisPRICE=bisPRICE*1.01where bisFLAVOUR = strawberry;

tblcustomer(custNO, custNAME, custEMAIL)tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE)tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status)33 List down all customer name and email who order biscuit cornflakes.

List down all biscuit details being order by customer C010.select c.custNAME, c.custEMAILfrom tblcustomer c, tblorder o, tblbiscuit bwhere c.custNO=o.custNo and o.bisNO=b.bisNo and b.bisNAME = cornflakes;

select b.bisNO, b.bisNAME, b.bisFLAVOUR, b.bisPRICEfrom tblbiscuit b, tblorder owhere b.bisNO=o.bisNO and o.custNO=C010;

tblcustomer(custNO, custNAME, custEMAIL)tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE)tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status)SQL Alias34You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names.An alias name could be anything, but usually it is short.Usually it is used in multiple table joint.

SQL Alias Syntax For Tables

SQL Alias Syntax For Columns

SELECT column_name(s)FROM table_nameAS alias_nameSELECT column_name AS alias_nameFROM table_nameSQL Alias35The following statement list all the staff name that work at IT department.staffNOstaffNAMEcitysalarydepartNOABC987NadzKuala Lumpur23000001ABC988AinaJerantut25000002ABC989HalimatonJerantut22000001ABC990NorainJohor20000003departNOdepartNAME0001IT0002Network0003ManagementstaffdepartmentSELECT s.staffNAMEFROM staff AS s, department AS dWHERE (d.departNO=s.departNO) AND d.departNAME=IT;staffNAMENadzHalimatonSQL JOINs36The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.

Tables in a database are often related to each other with keys.

A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.

SQL JOINs37Different SQL JOINs

JOIN / INNER JOINReturn rows when there is at least one match in both tablesLEFT JOINReturn all rows from the left table, even if there are no matches in the right tableRIGHT JOINReturn all rows from the right table, even if there are no matches in the left tableFULL JOINReturn rows when there is a match in one of the tables

SQL INNER JOIN38SQL INNER JOIN Syntax

NOTEINNER JOIN is the same as JOIN.

SELECT column_name(s)FROM table_name1INNER JOIN table_name2ON table_name1.column_name = table_name2.column_name SQL INNER JOIN39The following statement list all the staff name that work at IT department.staffNOstaffNAMEcitysalarydepartNOABC987NadzKuala Lumpur23000001ABC988AinaJerantut25000002ABC989HalimatonJerantut22000001ABC990NorainJohor20000003departNOdepartNAME0001IT0002Network0003ManagementstaffdepartmentSELECT staff.staffNAME,depart.departNAMEFROM staffINNER JOIN departmentON department.departNO=staff.departNO; staffNAMENadzHalimatonDML: Two-Table Joins40Besides INNER JOIN, you can also use the following statements to combines two tables with join conditions.

staff(staffNO, staffNAME, city, salary, departmentNO*)department(departNO, departNAME)SELECT s.staffNAMEFROM staff AS s, department AS dWHERE (d.departNO=s.departNO) AND d.departNAME=IT;SELECT staff.staffNAME,department.departNAMEFROM staffINNER JOIN departmentON department.departNO=staff.departNO; DML: Multiple-Table Joins41A multiple table join is a join of more than two tables with join conditions for pairs of table. A join condition is a comparison (relational operators) on two columns from each table.

Following is a three table joins which selects all the customer name that order biscuit Tart Nenas Gunting.

customer(custNO, custNAME, custEMAIL)biscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE)order(orderNO,*custNO,*bisNO, orderadate, qty, status)SELECT custNAMEFROM customer AS c, biscuit AS b, order AS o WHERE c.custNO=o.custNO AND o.bisNO=b.bisNO AND b.bisNAME=Tart Nenas Gunting;DML: Multiple-Table Joins42List down all customer name, biscuit name and order quantity that customer had order with confirm status.

select c.custNAME,b.bisNAME,o.qtyfrom tblcustomer c, tblbiscuit b, tblorder owhere c.custNO=o.custNO and b.bisNO=o.bisNO and o.status=Confirm;

tblcustomer(custNO, custNAME, custEMAIL)tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE)tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status)DML: GROUP BY Statement43GROUP BY statementproduce summary data within a group. a group is a set of rows that have the same values of group by columns. a single row of aggregate results is produced for each group. the column you want to group results by is identified by its column name.

restrict what you can enter in the SELECT statement. SELECT statement in GROUP BY statement must be one of the following: An aggregate function, which produces a single value summarizing the rows in the group. A grouping column which is listed in the GROUP BY statement. A constant. An expression involving a combination of the above.

DML: GROUP BY Statement44SQL GROUP BY Syntax

SELECT column_name(s), aggregate_function(column_name)FROM table_nameGROUP BY column_name;DML: GROUP BY Statement45The following statement will output staff average salary group by city.staffNOstaffNAMEcitysalarygenderdepartNOABC987NadzKuala Lumpur2300Male0001ABC988AinaJerantut2500Female0002ABC989HalimatonJerantut2200Female0001ABC990NorainJohor2000Female0003staffSELECT city, MIN(salary) AS minSALARYFROM staffGROUP BY city;cityminSALARYKuala Lumpur2300Jerantut2200Johor2000DML: ORDER BY Keyword46The ORDER BY keyword is used to sort the result-set by a specified column.sort the records in ascending order by default.By default the records are in ascending order or you can used ASC keyword If you want to sort the records in a descending order, you can use DESC keyword.The default order is ascending. NULL values are treated as larger that non-null values for sorting purposes.

SQL ORDER BY Syntax

SELECT column_name(s)FROM table_nameORDER BY column_name(s) ASC|DESCDML: ORDER BY Keyword47The following statement will output staff average salary group by city.staffNOstaffNAMEcitysalarygenderdepartNOABC987NadzKuala Lumpur2300Male0001ABC988AinaJerantut2500Female0002ABC989HalimatonJerantut2200Female0001ABC990NorainJohor2000Female0003staffSELECT city, MIN(salary) AS minSALARYFROM staffGROUP BY cityORDER BY city DESC;cityminSALARYJerantut2200Johor2000Kuala Lumpur2300DML: HAVING Statement48HAVING statement is used to select or reject a group.

The following example shows the average salary for staff based on city where the total staff salary exceeds RM 2000.staffNOstaffNAMEcitysalarygenderdepartNOABC987NadzKuala Lumpur2300Male0001ABC988AinaJerantut2500Female0002ABC989HalimatonJerantut2200Female0001ABC990NorainJohor2000Female0003SELECT city, AVG(salary) AS avgSALARYFROM staffGROUP BY cityHAVING SUM(salary)> 2000 ;cityavgSALARYKuala Lumpur2300Jerantut2350SQL Aggregate Functions49SQL aggregate functions return a single value, calculated from values in a column

COUNT( )returns the number of rowsSUM( ) returns the sumAVG( )returns the average valueMIN( )returns the smallest valueMAX( )returns the largest valueFIRST( )returns the first valueLAST( )returns the last valueSQL Aggregate Functions50Each operates on a single column of a table and returns a single value. COUNT, MIN, and MAX apply to numeric and non-numeric fieldsSUM and AVG may be used on numeric fields only.Apart from COUNT(*), each function eliminates nulls first and operates only on remaining non-null values. COUNT(*) counts all rows of a table, regardless of whether nulls or duplicate values occur.Can use DISTINCT before column name to eliminate duplicates. DISTINCT has no effect with MIN/MAX, but may have with SUM/AVG.

MIN/MAX/AVG51penNOdescrcolorqty1001Xtra-FineRed121002FineBlue321003MediumPink4penSELECT MIN(qty)AS minQTY, MAX(qty) AS maxQTY, AVG(qty) AS avgQTYFROM pen;minQTYmaxQTYavgQTY43216SUM/COUNT52penNOdescrcolorqty1001Xtra-FineRed121002FineBlue321003MediumPink4penSELECT SUM(qty)AS totalQTYFROM pen;totalQTY48SELECT COUNT(penNO)AS penNUMBERFROM pen;penNUMBER3FIRST/LAST53penNOdescrcolorqty1001Xtra-FineRed121002FineBlue321003MediumPink4penSELECT FIRST(color)AS firstCOLORFROM pen;firstCOLORRedSELECT LAST(color)AS lastCOLORFROM pen;lastCOLORPink54Find biscuit name that have the highest price.

List down all the biscuit order quantity for each biscuit type.

List down all the biscuit order quantity for each customer and sort according to the customer name.

List down how many customer order being made for each biscuit.

List down all customer name and email who order more then 5 biscuits.

List down biscuit information that never being order yet.

tblcustomer(custNO, custNAME, custEMAIL)tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE)tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status)55Find biscuit name that have the highest price.

SELECT bisNAMEFROM tblbiscuitWHERE bisPRICE = (SELECT MAX(bisPRICE) FROM tblbiscuit);


Recommended