Presentation is loading. Please wait.

Presentation is loading. Please wait.

STRUCTURED QUERY LANGUAGE (SQL)

Similar presentations


Presentation on theme: "STRUCTURED QUERY LANGUAGE (SQL)"— Presentation transcript:

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

2 Objectives To 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.

3 DML Data Manipulation Language Manipulate data

4 Data Manipulation Language(DML)
Data 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 data do some operation at the data user view it or save it in the database SELECT * FROM printer WHERE color = ‘red’ OR color = ‘blue’;

5 DML: Queries: SELECT Statement
The 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 Note SQL is not case sensitive { SELECT is the same as select } SELECT column_name(s) FROM table_name; SELECT * FROM table_name;

6 DML: Queries: SELECT Statement
Select all data from table printer. Select printerNO and price from table printer. SELECT * FROM printer; printerNO description color price P123 Dot-matrix Red 249.56 HP874 Laser Jet Blue 559.99 SELECT printerNO, price FROM printer; printerNO price P123 249.56 HP874 559.99

7 DML: Queries: SELECT DISTINCT Statement
In 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;

8 DML: Queries: SELECT DISTINCT Statement
The following statement only will select the distinct values from the column named city from table staff. staffNO staffNAME city ABC987 Nadz Kuala Lumpur ABC988 Aina Jerantut ABC999 Halimaton SELECT DISTINCT city FROM staff; city Kuala Lumpur Jerantut

9 SQL LIKE Operator The LIKE operator is used in a WHERE statement to search for a specified pattern in a column. SQL LIKE Syntax Note The LIKE operator is commonly used with SQL Wildcards SELECT column_name(s) FROM table_name WHERE column_name LIKE patern;

10 SQL LIKE Operator The following select staffs living in a city start with “K” from table ‘staff’. SELECT * FROM staff WHERE city LIKE “K%”; staffNO staffNAME city ABC987 Nadz Kuala Lumpur

11 SQL Wildcards % _ [charlist] [^charlist] or [!charlist]
SQL 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: Wildcard Description % 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 charlist

12 Wildcards: Using The % Wildcard
Select 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 staff WHERE city LIKE "La%"; SELECT * FROM staff WHERE city LIKE "%wi%";

13 Wildcards: Using The _ Wildcard
Select 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 staff WHERE staffNAME LIKE "_da"; SELECT * FROM staff WHERE staffNAME LIKE "S_ar_s";

14 Wildcards: Using The [charlist] Wildcard
Select 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 staff WHERE staffNAME LIKE "[asp]%"; SELECT * FROM staff WHERE staffNAME LIKE "[!asp]%";

15 DML: Data Entry The 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.

16 DML: Data Entry SQL INSERT INTO Syntax
It 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_name VALUES (value1, value2,…); INSERT INTO table_name (column1,column2,…) VALUES (value1, value2,…);

17 DML: Data Entry The following insert values into table ‘staff’.
INSERT INTO staff VALUES (‘ABC123’, ‘Norain', ‘Ipoh’); staffNO staffNAME city ABC123 Norain Ipoh

18 DML: Data Entry Insert a new customer for the following table.
insert into tblcustomer (customerno, customername, customer ) values (‘C001’, ‘Alya Qiesya’,

19 DML: Deleting Table Rows
The 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.

20 DML: Deleting Table Rows
SQL DELETE Syntax Note Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! DELETE FROM table_name WHERE some column=some value

21 DML: Deleting Table Rows
DELETE 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 staff WHERE staffNO=“ABC123” AND city=“Ipoh”; DELETE FROM staff WHERE staffNAME LIKE “Muhammad%”; DELETE FROM staff WHERE staffNO =“ABC125”;

22 DML: Making Changes to Data Items
The 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.

23 DML: Making Changes to Data Items
SQL UPDATE Syntax Note Notice 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_name SET column1=value,column2=value2,… WHERE some column=some value

24 DML: Making Changes to Data Items
Shows 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 staff SET city=“Bangi” WHERE staffNAME = “Rosliza”; UPDATE staff SET salary=salary*1.05 WHERE staffNAME = “Wafiy”; UPDATE printer SET description=“KO” WHERE printerNO = “F380”;

25 DML: COMMIT The COMMIT statement terminates the current transaction and makes all changes under the transaction persistent. COMMIT  is 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;

26 DML: ROLLBACK The 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 staff VALUES (“ABC990”, “Shafiza”, “Johor”) ROLLBACK;

27 DML: COMMIT & ROLLBACK The concept of COMMIT and ROLLBACK is designed for  data consistency because 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. ROLLBACK to undo something. If we use roll-back, the particular changes made are undone.

28 DML: Compound Statement with SELECT
You can combine simple conditions with the logical operators AND, OR, and NOT to form compound conditions. Symbol Meaning = Equal to < Less than <= Less than or equal to > Greater than >= Greater than or equal to <> Not equal to* *Some SQL version use != AND to combine two search conditions which must be both true. OR to combine two search conditions when one or the other (or both) must be true

29 DML: Compound Statement with SELECT
Select 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 staff WHERE city=“Jengka” AND age >= 40; SELECT * FROM staff WHERE city=“Temerloh” AND age >= 40;

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

31 Do it! Delete all biscuits with chocolate flavor from tblbiscuit.
Delete all order from customerC001 that have status cancel from tblorder. tblcustomer(custNO, custNAME, cust ) tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE) tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status) delete from tblbiscuit where bisFLAVOUR = “chocolate”; delete from tblorder where custNO = “C001” and status = “cancel”;

32 Change all status to confirm for biscuit BIS101 for customer C135.
Increase biscuit price 10% for biscuit with strawberry flavor. tblcustomer(custNO, custNAME, cust ) tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE) tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status) update tblorder set status = “confirm” where custNO = “C135”; update tblbiscuit set bisPRICE=bisPRICE*1.01 where bisFLAVOUR = “strawberry”;

33 List down all customer name and email who order biscuit cornflakes.
List down all biscuit details being order by customer C010. tblcustomer(custNO, custNAME, cust ) tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE) tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status) select c.custNAME, c.cust from tblcustomer c, tblorder o, tblbiscuit b where c.custNO=o.custNo and o.bisNO=b.bisNo and b.bisNAME = “cornflakes”; select b.bisNO, b.bisNAME, b.bisFLAVOUR, b.bisPRICE from tblbiscuit b, tblorder o where b.bisNO=o.bisNO and o.custNO=“C010”;

34 SQL Alias You 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_name AS alias_name SELECT column_name AS alias_name FROM table_name

35 SQL Alias staff department
staffNO staffNAME city salary departNO ABC987 Nadz Kuala Lumpur 2300 0001 ABC988 Aina Jerantut 2500 0002 ABC989 Halimaton 2200 ABC990 Norain Johor 2000 0003 departNO departNAME 0001 IT 0002 Network 0003 Management The following statement list all the staff name that work at IT department. SELECT s.staffNAME FROM staff AS s, department AS d WHERE (d.departNO=s.departNO) AND d.departNAME=“IT”; staffNAME Nadz Halimaton

36 SQL JOINs The 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.

37 SQL JOINs Different SQL JOINs JOIN / INNER JOIN
Return rows when there is at least one match in both tables LEFT JOIN Return all rows from the left table, even if there are no matches in the right table RIGHT JOIN Return all rows from the right table, even if there are no matches in the left table FULL JOIN Return rows when there is a match in one of the tables

38 SQL INNER JOIN SQL INNER JOIN Syntax SELECT column_name(s)
NOTE INNER JOIN is the same as JOIN. SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name = table_name2.column_name

39 SQL INNER JOIN staff department
staffNO staffNAME city salary departNO ABC987 Nadz Kuala Lumpur 2300 0001 ABC988 Aina Jerantut 2500 0002 ABC989 Halimaton 2200 ABC990 Norain Johor 2000 0003 departNO departNAME 0001 IT 0002 Network 0003 Management The following statement list all the staff name that work at IT department. SELECT staff.staffNAME,depart.departNAME FROM staff INNER JOIN department ON department.departNO=staff.departNO; staffNAME Nadz Halimaton

40 DML: Two-Table Joins SELECT s.staffNAME
Besides 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.staffNAME FROM staff AS s, department AS d WHERE (d.departNO=s.departNO) AND d.departNAME=“IT”; SELECT staff.staffNAME,department.departNAME FROM staff INNER JOIN department ON department.departNO=staff.departNO;

41 DML: Multiple-Table Joins
A 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, cust ) biscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE) order(orderNO,*custNO,*bisNO, orderadate, qty, status) SELECT custNAME FROM 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“;

42 DML: Multiple-Table Joins
List down all customer name, biscuit name and order quantity that customer had order with confirm status. tblcustomer(custNO, custNAME, cust ) tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE) tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status) select c.custNAME,b.bisNAME,o.qty from tblcustomer c, tblbiscuit b, tblorder o where c.custNO=o.custNO and b.bisNO=o.bisNO and o.status=“Confirm”;

43 DML: GROUP BY Statement
produce 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.

44 DML: GROUP BY Statement
SQL GROUP BY Syntax SELECT column_name(s), aggregate_function(column_name) FROM table_name GROUP BY column_name;

45 DML: GROUP BY Statement
staff staffNO staffNAME city salary gender departNO ABC987 Nadz Kuala Lumpur 2300 Male 0001 ABC988 Aina Jerantut 2500 Female 0002 ABC989 Halimaton 2200 ABC990 Norain Johor 2000 0003 The following statement will output staff average salary group by city. SELECT city, MIN(salary) AS minSALARY FROM staff GROUP BY city; city minSALARY Kuala Lumpur 2300 Jerantut 2200 Johor 2000

46 DML: ORDER BY Keyword The 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_name ORDER BY column_name(s) ASC|DESC

47 DML: ORDER BY Keyword staff
staffNO staffNAME city salary gender departNO ABC987 Nadz Kuala Lumpur 2300 Male 0001 ABC988 Aina Jerantut 2500 Female 0002 ABC989 Halimaton 2200 ABC990 Norain Johor 2000 0003 The following statement will output staff average salary group by city. SELECT city, MIN(salary) AS minSALARY FROM staff GROUP BY city ORDER BY city DESC; city minSALARY Jerantut 2200 Johor 2000 Kuala Lumpur 2300

48 DML: HAVING Statement HAVING 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. staffNO staffNAME city salary gender departNO ABC987 Nadz Kuala Lumpur 2300 Male 0001 ABC988 Aina Jerantut 2500 Female 0002 ABC989 Halimaton 2200 ABC990 Norain Johor 2000 0003 SELECT city, AVG(salary) AS avgSALARY FROM staff GROUP BY city HAVING SUM(salary)> 2000 ; city avgSALARY Kuala Lumpur 2300 Jerantut 2350

49 SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column COUNT( ) returns the number of rows SUM( ) returns the sum AVG( ) returns the average value MIN( ) returns the smallest value MAX( ) returns the largest value FIRST( ) returns the first value LAST( ) returns the last value

50 SQL Aggregate Functions
Each operates on a single column of a table and returns a single value. COUNT, MIN, and MAX apply to numeric and non-numeric fields SUM 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.

51 MIN/MAX/AVG pen penNO descr color qty 1001 Xtra-Fine Red 12 1002 Fine Blue 32 1003 Medium Pink 4 SELECT MIN(qty)AS minQTY, MAX(qty) AS maxQTY, AVG(qty) AS avgQTY FROM pen; minQTY maxQTY avgQTY 4 32 16

52 SUM/COUNT pen SELECT SUM(qty)AS totalQTY FROM pen;
penNO descr color qty 1001 Xtra-Fine Red 12 1002 Fine Blue 32 1003 Medium Pink 4 SELECT SUM(qty)AS totalQTY FROM pen; totalQTY 48 SELECT COUNT(penNO)AS penNUMBER FROM pen; penNUMBER 3

53 FIRST/LAST pen SELECT FIRST(color)AS firstCOLOR FROM pen;
penNO descr color qty 1001 Xtra-Fine Red 12 1002 Fine Blue 32 1003 Medium Pink 4 SELECT FIRST(color)AS firstCOLOR FROM pen; firstCOLOR Red SELECT LAST(color)AS lastCOLOR FROM pen; lastCOLOR Pink

54 Find 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 who order more then 5 biscuits. List down biscuit information that never being order yet. tblcustomer(custNO, custNAME, cust ) tblbiscuit(bisNO, bisNAME, bisFLAVOUR, bisPRICE) tblorder(orderNO,*custNO,*bisNO, orderadate, qty, status)

55 Find biscuit name that have the highest price.
SELECT bisNAME FROM tblbiscuit WHERE bisPRICE = (SELECT MAX(bisPRICE) FROM tblbiscuit);


Download ppt "STRUCTURED QUERY LANGUAGE (SQL)"

Similar presentations


Ads by Google