SQL Tutorial Ref PL-SQL
SQL Tutorial Ref PL-SQL
What is SQL?
SQL stands for Structured Query Language SQL is pronounced as /s.kjul/ SQL is designed for manipulate data in relational database management system
SQL can retrieve and update data from relational database management system by using data manipulation language. SQL can create and modify database schema and database objects such as tables, views, indexes... via data definition language. SQL can grant or revoke authorization to user through data control language.
2. SQL ALTER TABLE 3. SQL DROP TABLE SQL Tutorial References(for Practical)
__________*****____________________
SQL SELECT
2
Summary: In this tutorial, you will learn how to use SQL SELECT statement to retrieve data from a database table. The SQL SELECT statement allows you to retrieve the data from one or more database table. Here is the common syntax of the SQL SELECT statement:
1 2 3 4 5 6 SELECT column_list FROM table_list WHERE row_conditions GROUP BY column_list HAVING group_conditions ORDER BY sort_list ASC | DESC
First you have to specify the table name that you want to retrieve the data. The table name is followed by the keyword FROM. Second you have to indicate what data in want to retrieve. You can list the specify the column of the database table after the keyword SELECT. Suppose you want to retrieve last name of employees in the employees table, you can perform the following query:
1 SELECT lastname 2 FROM employees
The query fetches the values from the column lastname in all rows in the employees table and returns the result below.
You can also use SQL SELECT statement to retrieve multiple columns from a database table. In order to do so you must provide a comma between columns in the column list. For example, if you want to retrieve first name, last name and title of all employees, you can execute the following query:
1 SELECT lastname, firstname, title 2 FROM employees
To retrieve all information of employee in the employees table, you can list all columns name and separate them by commas. In case a database table having many columns and you do not want to list them all after the keyword SELECT, you can use an asterisk (*) to indicate that you want to retrieve all columns without explicitly specifying them in the column list. For instance, the following query allows you to retrieve all employee's information by using the asterisk (*):
1 SELECT * 2 FROM employees
In this tutorial, youve learned how to use simple SQL SELECT statement to retrieve data from a table. Youve also learned how to select a single column, multiple columns by separating them with a comma, and all columns by using the asterisk (*) from a table.
SQL WHERE
Summary: In this tutorial, you will learn how to use SQL WHERE clause with SQL SELECT statement to filter the data you select from database tables. The SQL WHERE clause is used with other SQL statements such as SQL SELECT, SQL DELETE and SQL UPDATE statements to filter records in the database tables which satisfy specific row conditions. SQL provides you various operators to allow you to construct row conditions. Here are most common operators in SQL.
Operator Description = Equal > Greater than < Less than >= Greater than or equal <= Less than or equal <> Not equal AND Logical operator AND OR Logical operator OR Suppose you want to find all employees who has last name is King, you can perform this query:
SELECT lastname, firstname, title FROM employees WHERE lastname = 'King' lastname firstname title -------- --------- -------------------King Robert Sales Representative
SQL first fetches all rows from employees table which specified in the FROM clause. Next SQL eliminates rows which do not satisfy the row condition, in this case rows which has lastname column is not equal to King. Then SQL eliminates all columns which are not available in the column list (or sometimes refered as selection list). To find all employees who do not live in US, you can use not equal operator (<>) in WHERE clause as follows:
SELECT lastname, firstname, title, country FROM employees WHERE country <> 'USA' lastname firstname title --------- --------- -------------------Buchanan Steven Sales Manager Suyama Michael Sales Representative King Robert Sales Representative Dodsworth Anne Sales Representative
country ------UK UK UK UK
To find all employees who were hired before 1993, you can use less than operator ( < ) like this:
SELECT lastname, firstname, title, country,date(hiredate) FROM employees WHERE hiredate < '1993-01-01' lastname firstname title country date(hiredate) --------- --------- --------------------- ------- -------------Davolio Nancy Sales Representative USA 1992-05-01 Fuller Andrew Vice President, Sales USA 1992-08-14 Leverling Janet Sales Representative USA 1992-04-01
To find all employees who were hired after 1993, you just use the greater than operator ( > ) in WHERE clause.
SELECT lastname, firstname, title, country,date(hiredate) FROM employees WHERE hiredate > '1993-01-01'
title -----------------------Sales Representative Sales Manager Sales Representative Sales Representative Inside Sales Coordinator Sales Representative
The logical operators such as OR and AND are used to combine multiple conditions in WHERE clause.
In this tutorial, youve learned how to filter the records in the result set in the SQL SELECT statement by using the SQL WHERE clause with conditions. Youve also learned how to use various common basic operators to construct a condition and use logical operators to combine condition together. In the next tutorial you will learn how to use other operator such as SQL BETWEEN and SQL IN to retrieve data in a range of values and in a set.
SQL Alias
In this tutorial, you will learn how to use different SQL alias including column alias and table alias with SQL SELECT statement. SQL Alias is used to organize the output and avoid ambiguous table error in SQL statements when multiple tables with the same column names are refered to. SQL supports two types of alias which are known as column alias and table alias.
In the SELECT statement above, we used two column aliases. The first column alias is product which represents for productname and the second alias is the price which represent for unitprice. In case the column name is lengthy and sometimes it is designed as an abbreviation, the column alias enables the output more meaningful and easy to read. 7
Be noted that the AS keyword is optional. You can omit the AS keyword in the column alias. If the column alias contain space but it must be enclosed in quotes. We can rewrite the above SELECT query as follows:
1 SELECT productName product, 2 unitPrice "unit price" 3 FROM products 4 WHERE unitPrice > 50
In above query, we refered to the same table employee. In the FROM clause we use E for employee as table alias and in the INNER JOIN clause we M for manager as table alias. When you use table alias, the column has to be refered as follows to avoid ambiguous column name error.
1 table_alias.column_name
SQL alias is is very useful when using with SQL subqueries, SQL self join and SQL INNER JOIN statements. In this tutorial, you've learned how to use SQL alias including column alias and table alias.
You use column alias to reorganize or reformat the output to make the output more meaningful. You use table alias when you address a table multiple times in a single SQL SELECT statment to make it easier to write and maintain the lengthy query.
SQL DISTINCT
8
In this tutorial, you will learn how to use SQL DISTINCT with SQL SELECT statement to eliminate duplicate records. SQL DISTINCT is used to eliminate the duplicated rows in the result of SELECT statement. For example, to retrieve all the cities which employees live you can use SELECT statement as follows:
1 SELECT city 2 FROM employees city -------Seattle Tacoma Kirkland Redmond London London London Seattle London
As you see, you get the result with the duplicate row which you dont expect. In this case, you can use SQL DISTINCT to eliminate all of duplicate city in the result set by performing the following SQL statement:
1 SELECT DISTINCT city 2 FROM employees city -------Seattle Tacoma Kirkland Redmond London
Youve put DISTINCT keyword before the column name which you want it distinction in value. You can even put more columns after the DISTINCT keyword. At this time, the combination of all columns is used to evaluate the rows are duplicate or not. For instance, you want to know all cities and countries information which employees live in; you can answer this question by performing the following query:
1 SELECT DISTINCT city, country 2 FROM employees city country -------- ------Seattle USA Tacoma USA Kirkland USA Redmond USA London UK
At this time the combination of city and country is used to determine the uniqueness of record in the result set.
Beside DISTINCT keyword, you can use ALL keyword to indicate that you dont want to eliminate duplicated records. Because ALL keyword is default to the SELECT statement so you dont have to explicitly specify it in the SELECT statement.
SQL ORDER BY
In this tutorial, you will learn how to use SQL ORDER BY clause to sort the result set based on criteria. SQL ORDER BY statement allows you to sort the result set based on one or more sort keys in ascending or descending fashion. Here is the syntax of SQL ORDER BY:
1 SELECT column1, column2 2 FROM table_name 3 ORDER BY sort_key1 [ASC | DESC], sort_key2 [ASC | DESC]
SQL ORDER BY can only be used in SQL SELECT statement. The sort_key (sort_key1, sort_key2,...) in SQL ORDER BY must be sortable. It can be character, numeric or date time data type. With SQL ORDER BY you can specify the sort order by using keyword ASC (means sort in ascending order) and DESC (means sort in descending order). If you dont specify the sort order by using ASC and DESC keywords, the default ordering is ascending. You can either sort one or more columns in any sort order you want. Let's take a look at several examples of using SQL ORDER BY: For example, you can sort all employees by their last name by performing the following query. In this case you sort last name in ascending order.
1 SELECT lastname, firstname 2 FROM employees 3 ORDER BY lastname lastname firstname --------- --------Buchanan Steven Callahan Laura Davolio Nancy Dodsworth Anne Fuller Andrew King Robert Leverling Janet Peacock Margaret Suyama Michael
You can also sort the result based on last name in descending order and first name in ascending order by performing the following query. This is known as multi column sorting.
1 SELECT lastname, firstname 2 FROM employees 3 ORDER BY lastname DESC, firstname ASC lastname firstname --------- --------Suyama Michael
10
SQL sorts the result based on the last name in descending order first. And based on this sorted result, it then sorts the first name in ascending order. SQL ORDER BY can also accept any expression. For example, you can use CONCAT function, which allows you concatenate multiple strings in into one, to construct full name of employees and then sort them all by full name. Here is the query example:
1 SELECT CONCAT(lastname,',',firstname) fullname 2 FROM employees 3 ORDER BY fullname fullname ---------------Buchanan,Steven Callahan,Laura Davolio,Nancy Dodsworth,Anne Fuller,Andrew King,Robert Leverling,Janet Peacock,Margaret Suyama,Michael
Almost RDMBS allows you to specify the sort key based on the positional number of column in the selection list. The starting position of column in the selection list is 1 and so on and those positional numbers can be listed in SQL ORDER BY clause. Suppose you want to sort employees by hired date to find out who are the most new hire employees of the company; You can use positional number in ORDER BY clause as follows:
1 SELECT lastname, firstname, date(hiredate) 2 FROM employees 3 ORDER BY 3 DESC lastname firstname date(hiredate) --------- --------- -------------Dodsworth Anne 1994-11-15 Callahan Laura 1994-03-05 King Robert 1994-01-02 Buchanan Steven 1993-10-17 Suyama Michael 1993-10-17 Peacock Margaret 1993-05-03 Fuller Andrew 1992-08-14 Davolio Nancy 1992-05-01 Leverling Janet 1992-04-01
SQL sorts the result by hiredate column which positional number of hiredate column in the selection list is 3. Because the positional number is changed when you add more columns in the selection list so you have to change it also in the SQL ORDER BY clause. This sometimes led you to an 11
unexpected result if you forget to change the positional number. Therefore it is not recommended to use positional number in ORDER BY clause, you only use it if you don't have any option. In this tutorial, youve learnt how to use SQL ORDER BY clause to sort the result in ascending and descending order.
SQL IN
In this tutorial, you will learn how to use SQL IN operator along with SQL WHERE clause to retrieve data in a set of values. SQL IN operator allows you to determine if a value is contained in a set of values. The syntax of using SQL IN operator is as follows:
1 SELECT column_list 2 FROM table_name 3 WHERE column IN (value1, value2, value3)
The set of values must be comma-delimited and enclosed within parentheses. To find all products which have unit price are 18, 19 and 20 you perform the following query:
1 SELECT productName, unitPrice 2 FROM products 3 WHERE unitPrice IN (18, 19, 20) productName unitPrice ---------------- --------Chai 18.0000 Chang 19.0000 Steeleye Stout 18.0000 Inlagd Sill 19.0000 Chartreuse verte 18.0000 Maxilaku 20.0000 Lakkalikri 18.0000
The query above can be rewritten as following by using OR operator to combine multiple conditions.
1 SELECT productName, unitPrice 2 FROM products 3 WHERE unitPrice = 18 OR unitPrice = 19 OR unitPrice = 20
As you can see, SQL IN operator helps you to reduce the complexity of combining multiple OR conditions therefore it make SQL statement easier to understand and maintain. To find all records which has a column value are not in a set you can use NOT IN. for instance, you can find all products which have unit price not 18 and not 19 and not 20 by performing the following query:
1 SELECT productName, unitPrice 2 FROM products 3 WHERE unitPrice NOT IN (18, 19, 20)
12
Beside these above usages, SQL IN operator is also used in subquery which you will learn later in SQL subquery tutorial. In this tutorial, youve learn how to use SQL IN operator to find records which has value in a set. Furthermore, youve also learnt how to combine NOT operator with SQL IN operator to find all records which has value not in a set.
SQL BETWEEN
In this tutorial, you will learn how to use SQL BETWEEN operator with SQL WHERE clause to select the records which have the value in a range of values. SQL BETWEEN operator allows you to retrieve records which has value in a range of values. The syntax of SQL BETWEEN is as follows:
1 SELECT column_list 2 FROM table_name 3 WHERE column BETWEEN lower_value AND upper_value
Be noted that SQL BETWEEN operator gets all records which have column value is lower_value and upper_value. For example you want to retrieve products which have unit price from 18$ to 19$, you can use SQL BETWEEN operator like the following query:
1 SELECT productName, unitPrice 2 FROM products 3 WHERE unitPrice BETWEEN 18 AND 19 productName unitPrice ---------------- --------Chai 18.0000 Chang 19.0000 Steeleye Stout 18.0000 Inlagd Sill 19.0000 Chartreuse verte 18.0000 Boston Crab Meat 18.4000
13
Lakkalikri
18.0000
You can also reconstruct SQL BETWEEN by using less than or equal and greater than or equal operators like the following query:
1 SELECT productName, unitPrice 2 FROM products 3 WHERE unitPrice >= 18 AND unitPrice <= 19
To find all products which does not have unit price between that ranges of prices, you can combine SQL NOT operator with SQL BETWEEN operator. Here is the query:
productName ------------------------------Mishi Kobe Niku Konbu Teatime Chocolate Biscuits Sir Rodney's Marmalade Tunnbrd Guaran Fantstica Thringer Rostbratwurst Geitost Cte de Blaye Jack's New England Clam Chowder Rogede sild Zaanse koeken Filo Mix Tourtire Rhnbru Klosterbier unitPrice --------97.0000 6.0000 9.2000 81.0000 9.0000 4.5000 123.7900 2.5000 263.5000 9.6500 9.5000 9.5000 7.0000 7.4500 7.7500
In this tutorial youve learned how to use SQL BETWEEN operator to find values which are in a range of values. In addition youve also learned how to combine SQL NOT operator and SQL BETWEEN operator to find all records which have value is not in a range of values.
14
The data type of column must be alphanumeric in order to use SQL LIKE statement. It could be CHAR, VARCHAR, NVARCHAR data type. Lets take a look at several examples of using SQL LIKE statement and constructing patterns. Suppose you want to find all employees with the last name starting with D character, you can use perform the following query.
1 SELECT lastname, firstname 2 FROM employees 3 WHERE lastname LIKE 'D%' lastname firstname --------- --------Davolio Nancy Dodsworth Anne
The expression D% means find all string starting with character D and followed by any characters. To find all employees which have the first name ending with character t, you can execute the following query.
1 SELECT lastname, firstname 2 FROM employees 3 WHERE firstname LIKE '%t' lastname firstname --------- --------Leverling Janet Peacock Margaret King Robert
The expression %t means any string with any characters in any length and ending with character t. You can put the wildcard % at the beginning and the end of a string to find any string which contains string within those wildcards. For example to find all employees which have last name contain string ll, you can execute the following query as follows:
1 SELECT lastname, firstname 2 FROM employees 3 WHERE lastname LIKE '%ll%' lastname firstname -------- --------Fuller Andrew Callahan Laura
Two wildcard characters % and _ can combine together to construct a pattern. For example you can find all employees which have last name starting with any single characters, followed by character a and followed by any characters. You can use the combination of both wildcard characters. Here is the query to do so: 15
SQL LIKE statement can also combine with the SQL NOT operator to find all string which does not match the pattern. For example if you want to find all employees which first name is not starting with character D, you can perform the following query:
1 SELECT lastname,firstname 2 FROM employees 3 WHERE lastname NOT LIKE 'D%' lastname firstname --------- --------Fuller Andrew Leverling Janet Peacock Margaret Buchanan Steven Suyama Michael King Robert Callahan Laura
In this tutorial, youve learned how to use SQL LIKE statement to find string of text which matches a pattern. Youve learned how to use two wildcard characters: percentage (%) and underscore (_) to construct a pattern for using in SQL LIKE statement.
SQL GROUP BY
In this tutorial, you will learn how to SQL GROUP BY clause to group a set of result set based on group columns. SQL GROUP BY is used to divide a database table into groups based on group columns. For each group you can apply aggregate functions such as SUM, AVG, MIN, MAX and COUNT to output the summary information. SQL GROUP BY is very useful when you want to analyze data in analytical way such as how many sale orders was ordered by a customer and sold by a sale person. The common syntax of SQL GROUP BY is as follows:
1 2 3 4 5 SELECT c1,c2,... cn, aggregate_function(expression) FROM tables WHERE where_conditions GROUP BY c1, c2, ... cn ORDER BY order_columns
Lets take a look at several examples of using SQL GROUP BY to see how it works. Suppose you want to find the total money of every sale order you have in order details table. You can use SQL GROUP BY and SUM function to do so. Here is the query:
1 SELECT orderID, SUM(unitPrice * quantity) 2 FROM order_details 3 GROUP BY orderID
orderID ------10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260
SUM(unitPrice * quantity) ------------------------440.0000 1863.4000 1813.0000 670.8000 3730.0000 1444.8000 625.2000 2490.5000 517.8000 1119.9000 2018.6000 100.8000 1746.2000
SQL engine first looks at the GROUP BY clause and groups the table into groups based on the order identity. Then SQL engine computes the sum of unitPrice column multiple with quantity column for each group. You can use SQL GROUP BY without the aggregate functions. At this time SQL GROUP BY acts like SELECT DISTINCT to distinguish all records based on group columns. Here is the query:
1 SELECT orderID, SUM(unitPrice * quantity) 2 FROM order_details 3 GROUP BY orderID
You can use SQL GROUP BY clause together with SQL ORDER BY clause to sort the output result. For example you can sort the total sale of all sale orders in descending order as the following query:
1 2 3 4 SELECT OrderID, SUM(unitPrice * quantity) total FROM Order_details GROUP BY OrderID ORDER BY total DESC
17
10865 11030 10981 10372 10424 10817 10889 10417 10897 10353
17250.0000 16321.9000 15810.0000 12281.2000 11493.2000 11490.7000 11380.0000 11283.2000 10835.2400 10741.6000
In this tutorial, youve learned how to use SQL GROUP BY to divide records in a database table into groups and apply aggregate function for each group to produce summarization output. In the next tutorial, you will learn HAVING clause which is related to GROUP BY, lets move on.
SQL Having
18
SQL HAVING clause is used together with SQL GROUP BY clause to filter group of records based on conditions. SQL HAVING clause is similar to WHERE clause in functionality manner but filter group of records not records. SQL Tutorial SQL HAVING
SQL Having
SQL HAVING clause is used together with SQL GROUP BY clause to filter group of records based on conditions. SQL HAVING clause is similar to WHERE clause in functionality manner but filter group of records not records. Lets take a look at several examples of using SQL HAVING. If you want to find all sale orders which have total sale greater than $120000, you can use HAVING together with the GROUP BY clause.
1 SELECT OrderID, SUM(unitPrice * quantity) total 2 FROM Order_details 3 GROUP BY OrderID 4 HAVING total > 12000 OrderID total ------- ---------10372 12281.2000 10865 17250.0000 10981 15810.0000 11030 16321.9000
Suppose you want to find all orders which have a number of products greater than 5 , you can use COUNT function with HAVING and GROUP BY together. Her e is the query:
1 SELECT orderID, COUNT(productID) prd_count 2 FROM order_details 3 GROUP BY orderID 4 HAVING prd_count > 5 orderID prd_count ------- --------10657 6 10847 6 10979 6 11077 25
Sample tables
We have two tables: categories and products in the sample database to demonstrate how the SQL JOIN works. Here is the database diagram of them: 19
1. One category can have multiple products. 2. One product belongs to only one category.
Table_A and table_B are sometimes called joined-tables. SQL INNER JOIN returns records from both tables where a match is found based on join conditions (join_condition). SQL INNER JOIN gets all the records from the table_A and finds the matching records in the table_B according to the join condition. The join condition determines whether both records are matched or not. If there is no match found, no records is returned. Suppose you need the following information: productId, productName, and category name of each product from both tables products and categories. In this case, you can use SQL INNER JOIN to combine the records in both tables as follows:
1 SELECT productID,productName,categoryName 2 FROM products 3 INNER JOIN categories ON products.categoryID = categories.categoryID
20
For each product in the products table, SQL finds a corresponding category in the categories table which has the same categoryID; If there is a match found, SQL returns records otherwise no record is returned. Most of the time you use foreign keys to form the join condition. In this case categoryID is the foreign key of two tables. There is another form of SQL INNER JOIN which called implicit inner join. Here is the implicit SQL INNER JOIN syntax:
1 SELECT selection_list 2 FROM table_A, table_B 3 WHERE join_condition.
In this form you list all joined-tables after the FROM clause and put join condition in WHERE clause of the SQL SELECT statement. As our above example, we can rewrite the example query as follows:
1 SELECT productID,productName,categoryName 2 FROM products, categories 3 WHERE products.categoryID = categories.categoryID
There is another way to visualize the SQL INNER JOIN by using the Venn diagrams. In this way you can see that SQL INNER JOIN returns only records that match in both table_A and table_ B.
In this tutorial, you've learned how to use SQL INNER JOIN to retrieve data from two tables. In the next tutorial, you will learn how to use another kind of SQL join called outer join.
22
In this tutorial, youve learned how SQL OUTER JOIN works and all kinds of SQL OUTER JOIN: SQL LEFT OUTER JOIN, SQL RIGHT OUTER JOIN and SQL FULL OUTER JOIN.
SQL Self-join
SQL self-join simply is a normal join which is used to join a table to itself. The SQL self-join can be done by using SQL table aliases to treat one table like a different table and then join them together. SQL self-join can be any form of join such as SQL inner join, SQL outer join so you can apply any join to the SQL self-join. Here is common syntax of SQL self-join:
SELECT column_list FROM table_A AS A INNER JOIN table_A AS B ON A.column_name1 = B.column_name2, ... WHERE row_conditions
SQL self-join is very useful when you want to retrieve related data storing in one table such as organizational structure. In our database sample, we have employees table which stores not only employee data but also organizational structure. The column reportsTo specifies the manager of an employee and is referenced to employeeID column.
23
To list all information of employees and managers we can use SQL self-join as follows.
SELECT concat(e.firstname, e.lastname) employee, concat(m.firstname,m.lastname) manager FROM employees e INNER JOIN employees m ON m.employeeId = e.reportsTo
SQL Subqueries
SQL subquery is a SQL query which is nested in another query. A SQL subquery is usually nested inside a SELECT, INSERT, UPDATE and DELETE statement. A SQL subquery can be used anywhere in a query where an expression is allowed. A SQL subquery is somtimes refered as inner select or inner query. The SQL statement contains a subquery is also called outer select or outer query. 24
Here is an example of using an SQL subquery as an expression in SELECT statement as MaxDiscount column:
1 SELECT orderid, 2 orderdate, 3 (SELECT MAX(discount) 4 FROM order_details 5 WHERE orderid = orderid) AS maxdiscount 6 FROM orders
A SQL subquery nested in an outer SELECT statement has several components as follows:
A selected field in a regular SELECT statement to use as a data source for the outer SELECT statement. 25
A regular FROM clause to specify the table where a selected field is chose from. Optional clauses such as WHERE, GROUP BY or HAVING.
A SELECT statement of a SQL subquery must be enclosed in parenthesises. A SQL subquery can include one or more subquery. A number of subquery can include in a subquery depends on the implementation of each RDBMS. It is not recommended to have a high number of leve of nesting subquery in a SQL statement. The following SQL query is used to find the total quantity product bought by customers from USA.
01 02 03 04 05 06 07 08 09 10 SELECT o.productid, p.productname, SUM(o.quantity) quantity FROM order_details o INNER JOIN products p ON p.productid = o.productid WHERE o.orderid IN ( SELECT orderid FROM orders WHERE customerid IN (SELECT customerid FROM customers WHERE country = 'USA' ) ) GROUP BY productid ORDER BY quantity DESC
The inner most query returns all the customer number from USA. The query at the next higher level is evaluated with these customer numbers and returns all sale orders numbers from those customers. Finally outer query uses the order numbers to find all product number from order details table. Product name is selected by join order details table with product tables. The total of quantity is calculated by using aggregate function SUM and GROUP BY clause.
Subqueries Examples
Subqueries with Aliases
In SQL statements if the subquery and outer query refers to the same table. In this case we have to use SQL Alias for both outer query and subquery. The following query finds all managers of the company by refering table employees twice in outer query and subquery.
1 SELECT e1.employeeid, e1.firstname, e1.lastname 2 FROM employees e1 3 WHERE e1.employeeid IN ( 4 SELECT e2.reportsto 5 FROM employees e2 )
26
Subqueries as expression
A subquery can be used as an expression in anywhere where expression is allowed in the SQL statement. Here is an example of using subquery as an expression to list all product average price and difference between product's price and the average price in product category 1 (Beverages).
1 SELECT productid, productname, 2 (SELECT AVG(unitprice) FROM products) average, 3 unitprice - (SELECT AVG(unitprice) FROM products) 4 FROM products 5 WHERE categoryid = 1
Correlated subquery
Correlated subquery is a special kind of subquery which the subquery uses the values from outerquery in its where clause. The subquery is evaluated for every rows selected by the outerquery. The following query is a typical example of correlated query for finding products which have price greater than average unit price in its category.
1 SELECT productid, productname,unitprice 2 FROM products p1 3 WHERE unitprice > (SELECT AVG(unitprice) 4 FROM products 5 WHERE categoryid = p1.categoryid)
SQL UNION
SQL UNION is used to combine results of two or more SQL SELECT queries into one. The syntax of SQL UNION is as follows:
1 SELECT column_list1 FROM table1 2 UNION (DISTINCT | ALL) 3 SELECT column_list2 FROM table2
Basically the first and the second query can be any SQL SELECT queries with a restriction that the column_list1 and column_list2 have to be compatible. It means both columns lists must have the same number of columns, and each corresponding column must has the same data type or at least convertible data type. 27
By default SQL UNION eliminates all duplicate records, in this case NULL values are considered as a single value. To enable duplication of records, you can use ALL keyword followed after UNION explicitly. Be noted that by default the DISTINCT is used if you dont specify anything after UNION. Lets take a look at several examples of using SQL UNION. Suppose you want to find all the cities of all customers and suppliers. In this case, you can use SQL UNION to combine cities of both customers and suppliers as follows:
1 SELECT city FROM customers 2 UNION 3 SELECT city FROM suppliers
If you use UNION ALL you will see duplicate values in the output by performing the following query:
1 SELECT city FROM customers 2 UNION ALL 3 SELECT city FROM suppliers
In this tutorial, you've learned how to use SQL UNION to combine result of two or more SQL SELECT queries into one.
SQL INSERT
SQL INSERT statement allows you to insert one or more records into a database table. In addition SQL INSERT statement also allows you to copy data from a database tables to another database table. SQL INSERT statement is sometimes referred as SQL INSERT INTO statement.
28
In this form, you specify the name of database table, which you want to insert data into, followed after the INSERT INTO statement. The number of columns (column1, column2,...) and values (value1, value2,..) must be same. If the column is omitted, the default value for column is used. The values inserting to the database table must also satisfy other conditions such as constraints of foreign key, NOT null constraints otherwise the insert action will be failed and new row is not added to the database table. Lets take a look at an example of inserting data into the Shippers table by using SQL INSERT statement.
1 INSERT INTO Shippers (companyName, phone) 2 VALUES ('Alliance Shippers','1-800-222-0451')
Because shipperID is the primary key of the Shippers table and it is automatically increased each time we insert a new row so we dont need to list it there in the column list. Only data we have to provide for INSERT statement are company name and phone. After executing the query, the database server returns number of row affected. Here you get 1 row affect to indicate that one row has been added successfully/
In this form, you provide multiple values which are corresponding to the column list of the database table. Here is an example of inserting multiple records into Shippers table.
1 INSERT INTO shippers(companyName,phone) 2 VALUES ('UPS','1-800-782-7892'), 3 ('DHL','1-800-225-5345')
The selection list must be corresponding to columns of the database table you want to copy data. Suppose you have a temporary table called table_tmp with the structure exactly the same as the shippers table. Now you want to copy data from the shippers table into this temporary 29
table, you can use SQL INSERT INTO SELECT statement. In this case by performing the following query:
1 INSERT INTO shippers_tmp (companyName, phone) 2 SELECT companyName, phone 3 FROM shippers
In this tutorial, youve learned how to use SQL INSERT statement to insert one or more records into a database table. In addition, you also learned how to copy the data from a database table to another database table by using SQL INSERT SELECT INTO statement.
SQL UPDATE
SQL UPDATE statement allows you to modify data in a database table. With SQL UPDATE statement, you can modify data of the whole table or subset of data based on condition in WHERE clause. Here is the typical syntax of SQL UPDATE statement:
1 UPDATE table_name 2 SET column1 = value1, 3 column2 = value2 4 WHERE condition
First you specify a database table where you want to update data after UPDATE keyword. You can update data in one column or more. If you update data in more than one column, the columns has to be separated by commas (,). It is not required to provide the data directly to the SQL UPDATE statement. You can also use data which you retrieve from another table and then use it for SQL UDPATE statement as well. The data you can get from a SELECT statement but be sure that the select query must return a single record which has type compatible with the column you want to update. The WHERE clause is optional. If you omit the WHERE clause, all the records of the database table will be updated. Lets take a look at several examples of using SQL UPDATE. Suppose one of employee in the company get married and need to change her last name, so you have to make the change by using the SQL UPDATE statement. Here is the query to do so:
1 UPDATE employees 2 SET lastname = 'Phan' 3 WHERE employeeID = 3.
Suppose her employee ID is 3. Another example is one of employee of the company change the address so you want to update address information including address, city, region and postal code. In this case you can use SQL UPDATE to change this data. 30
1 2 3 4 5 6
UPDATE employees SET address = '1300 Carter St', city = 'San Jose', postalcode = 95125, region = 'CA' WHERE employeeID = 3
In this tutorial, you've learned how to use SQL UPDATE statement to update data in a database table.
SQL DELETE
In this tutorial, you will learn how to use SQL DELETE statement to remove data from database tables. SQL DELETE statement allows you to delete one or more records in a database table. The syntax of SQL DELETE statement is as follows:
1 DELETE FROM table_name 2 WHERE conditions
If you omit the WHERE clause the SQL DELETE statement, it will delete all records in the database table. It is very time consuming and less efficient to use SQL DELETE statement to do so especially with the table with a big data. If you want to delete all data in a database table, SQL provide you TRUNCATE statement which is more efficiently to delete the whole table./div> Lets take a look at couples of examples using SQL DELETE statement. If you want to remove employee number 3 just execute the following query:
1 DELETE FROM employees 2 WHERE employeeID = 3
If the record which has employeeID with 3 exist, it will be deleted otherwise nothing happens. To delete all employees in the table employees (not recommended, and make a backup before you do this) you just execute the following query:
1 DELETE FROM employees
SQL DELETE statement become complicated when you delete a record in a table which has relationship and link together by a foreign key such as employees and employeeterritories. If you want to delete an employee you have to delete a record which has employeeid in employeeterritories table also. So you have to execute two DELETE statements as follows:
1 DELETE FROM employees 2 WHERE employeeID = 3; 1 DELETE FROM employeeterritories 2 WHERE employeeID = 3
31
Almost RDBMS allows you to create a constraint called referential integrity between two linked tables. Therefore if a record in a table is deleted, other records in the linked table, if exist, are deleted also. Therefore in this case you just only have to execute the first DELETE query to make the data to be integrity. In this tutorial, youve learned how to use SQL DELETE statement to delete one or more records in a database table. Youve also learned about referential integrity constraints between tables to allow you to delete records in linked table automatically by deleting record in other table.
There are four components you need to specify when creating a database table: 1. Database table name. It is suggested that the name should be meaningful and in plural form of a noun. For example products is the name of a table which stores product data. 2. Name of each column in the table: It should be meaningful also and in a noun with singular form. 3. Data type for each column: Choose the correct data type for column is very important in the design phrase. The most common data types are text (varchar, nvarchar), numerical (smallint, int, bigint), date, time datetime, timespan,blobyou can refer it in the specific RDBMS. 4. Maximum length of each column: You have to specify the maximum length of data for each column. For example if you store product name, try to imagine the maximum length a product can have, such as 255 characters. Beside those components above you can have another additions for each column such as the column is mandatory or not (NULL or not NULL), default value of the column and value of the column is unique or not. If a column is unique and not null it can be a primary key of the table. Here is an example of creating products table:
01 CREATE TABLE products ( 02 ProductID int(11) NOT NULL AUTO_INCREMENT, 03 ProductName varchar(40) NOT NULL, 04 SupplierID int(11) DEFAULT NULL, 05 CategoryID int(11) DEFAULT NULL,
32
06 07 08 09 10 11 12 13
QuantityPerUnit varchar(20) DEFAULT NULL, UnitPrice decimal(19,4) DEFAULT NULL, UnitsInStock smallint(6) DEFAULT NULL, UnitsOnOrder smallint(6) DEFAULT NULL, ReorderLevel smallint(6) DEFAULT NULL, Discontinued tinyint(4) NOT NULL, PRIMARY KEY (ProductID) )
In the above example, we've created a products table. The first column is ProductID which is the primary key of the product table which is used to differentiate between data rows or records. PRIMARY KEY keyword is used to specify the primary key of the table. There are also other columns used to describe a product of the products table with different data type, length and default value. Once table is created, you can alter it by using SQL ALTER TABLE or removing it using SQL DROP TABLE.
Add a new column or removing an existing column of the table. Modify of maximum length of a column. Add or remove default value of a column. Add or remove constraints of table.
33
First you specify the table you want to add a new column and then you specify column name, its data type and its maximum length of data. For example to add new column called availableOnline in the products table you can perform the following query:
ALTER TABLE Products ADD COLUMN availableOnline BIT NOT NULL
To remove an existing column in a database table you need to specify the table and column name you want to remove. Here is the syntax:
ALTER TABLE table_name DROP COLUMN existing_column
To drop the column availableOnline in products table we created in the above example we can use ALTER TABLE DROP COLUMN to do so. Here is the query:
ALTER TABLE products DROP COLUMN availableOnline
When you drop a column, all the data in that column is removed. If you drop a key column which is a part of a composite key of the table, not only the data in the column is removed but also all the duplicated records in that table are removed also. The SQL ALTER TABLE statement can be different between database products in its additions such as add or remove constraints, set default value you can check it out to know more in details. In this tutorial, youve learnt how to modifying table by using SQL ALTER TABLE statement. Youve learnt how to add or removing a column from a database table.
In order to remove table, you'll need to have sufficient permission to do so. In the statment you specify the table name you want to remove, the database will remove the table in the current working database. If you want to remove table in a different database you need to use the following syntax:
1 DROP TABLE database_name.table_name
In the above syntax, you specify the database followed by a full stop and table name.
34
To remove table employees in the database tmp, you'll need to execute the following query:
1 DROP TABLE tmp.employees
Before executing the SQL DROP TABLE you need to to consider it seriously. You have to asked yourself whether the table being removed is still used in the future. If this is the case, you have to backup the database first before droping table. You should always find all the foreign key constraints or referencing table that reference to the table being removed. Then you remove all the references first before dropping table. It is safer to specify the database name when you use SQL DROP TABLE statement. Because in the database landscape you may have different database systems and names for development, testing and production systems. Sometimes you have to go to those systems at the same time to do the work. You may confuse the production, testing and development systems and potentially drop table in the production system with the thought that it is development system. If you just want to delete the data use SQL DELETE or SQL TRUNCATE statement instead.
35
MySQL Tutorial MySQL tutorial site provides you useful tutorials of SQL and MySQL. SQL on Wikipedia SQL information on Wikipedia with definition of SQL, SQL history and other languages elements PostgreSQL Guides PostgreSQL is one of the most advanced open source database management system. Postgresqlguide.com gives you basic guides about the PostgreSQL from the start. SQL Tutorial Yet another SQL tutorial website, it mainly focus on SQL standard with practical examples. http://www.coderecipes.net/
Advanced SQL
SQL UNION Tutorial
SQL union allows you to combine the match result sets of two (or more than two) select queries into a single table.
37
INTERSECT operator allows you to combine two table expressions into one and return a result set which consists of rows that appear in the results of both table expressions.
As an example here two tables which we will use to to demonstrate union operator. cost2006 table
CostCenterId -----------1 2 3 Cost -----300000 150000 500000
cost2007 table
CostCenterId -----------1 2 3 Cost -----120000 250000 450000
38
500000
2007
In a good database model one table has one and only one type of elements therefore SQL UNION does not make sense here. It is usually used in a data warehouse application in which the database models are not good nomalized.
The data type of the column_name after the CASE must be the same as the data type of the expression followed by the keyword THEN or ELSE. The ELSE part of the case expression is optional. If the ELSE part is omitted and all the conditions in the WHEN does not meet, the CASE expression will return NULL. The case expression can be used in anywhere scalar expressions are allowed, including in WHERE and HAVING clause of the select statement. It is more intuitive to demonstrate CASE expression through an example. Here is the employees table for demonstration :
1 employee_id 2 ----------3 3 4 2 5 5 6 4 7 1 8 6 name -------newcomer mary Tom anna jack foo department_id ------------(NULL) 2 2 1 1 3 job_id -----0 2 2 1 1 3 salary ------2000.00 2500.00 2700.00 2800.00 3000.00 4700.00
We can use the CASE expression to print out the employee name, his salary and a computed column which is called salary level. Here is the sql query:
1 SELECT name,salary, 2 CASE 3 WHEN salary <= 2000 THEN 'low' 4 WHEN salary > 2000 AND salary <= 3000 THEN 'average' 5 WHEN salary > 3000 THEN 'high' 6 END AS salary_level 7 FROM employees 8 ORDER BY salary ASC
39
The logic is simple if the salary of the employee lower than 2000 the salary level is low; greater than 2000 and less than or equal to 300, the salary level is average; And greater than 3000, the salary level is high (of course just for example). And the output is :
1 2 3 4 5 6 7 8 name -------newcomer mary Tom anna jack foo salary ------2000.00 2500.00 2700.00 2800.00 3000.00 4700.00 salary_level -----------low average average average average high
Be noted that the MINUS operator only returns distinct values from table expression. SQL MINUS or EXCEPT operator is one of the set operators. SQL MINUS or EXCEPT is equivalent of the difference operator from set theory. Some RDBMS uses MINUS and the other uses EXCEPT keyword.
Table expression can be any select statement which has to be union compatible and ORDER BY can be specified only behind the last table expression. 40
Be note that several RDBMS, including MySQL (version < 5.x), does not support INTERSECT operator. This is an example of using INTERSECT operator. Here is the employees sample table
1 employee_id 2 ----------3 1 4 2 5 3 6 4 7 5 8 6 name -------jack mary newcomer anna Tom foo department_id ------------1 2 (NULL) 1 2 3 job_id -----1 2 0 1 2 3 salary ------3000.00 2500.00 2000.00 2800.00 2700.00 4700.00
We can find employee who work in department id 1 and two and have salary greater than 2500$ by using INTERSECT operator. This example using the sample table in both table expressions, you can test it on two different tables.)
1 2 3 4 5 6 7 1 2 3 4 5 SELECT * FROM employees WHERE department_id in (1,2) INTERSECT SELECT * FROM employees WHERE salary > 2500 employee_id name department_id ----------- ------ ------------1 jack 1 4 anna 1 5 Tom 2
job_id -----1 1 2
It is used to increases the performance of application because when we create stored procedures, they are compiled and stored in database catalog. Later when client applications call them, they are generally executed faster than uncompiled SQL statements which are sent from the client applications. The network traffic between application server and database server is also signification reduced because the applications don't have to send such long and uncompiled SQL statements to the server to get the data back. Stored procedures can be used for database security purpose because each store procedure can have its own database privileges. One of the most advantage of stored procedure is code reusability. Once created, a stored procedure can be reused over and over again by multiple applications.
It is the best to illustrate the ability of stored procedure by showing examples. You can follow this tutorial to understand more about stored procedure. We will use Microsoft SQL Server to demonstrate stored procedure, you can also use MySQL with a change a little bit because of specification of each database server is different. Start learning how to write a stored procedure by following the tutorial getting started with stored procedure
A stored procedure must contains at least three parts: stored procedure name, parameter list and its body. The CREATE PROCEDURE is similar to CREATE TABLE or INDEX statement. It is actually a SQL statement. The CREATE PROCEDURE will force the database server add the stored procedure to the its catalog. The name of stored procedure is followed after the CREATE PROCEDURE statement, in this case it is Delete_Employee. It would be the best that the name is meaningful and follows by the naming convention of the database server specification, for example each stored procedure should begin with "sp". In almost relation database product, the name of stored procedure must be unique. The second part of the stored procedure is parameter list. In this case the list contains only one parameter @EmployeeId (the employee identity). Microsoft SQL Server requires prefix @ for every parameters and variables of stored procedure. Followed each parameter is its type, in this case, its type is integer (INT). The main part of a stored procedure is the stored procedure body. It starts with keywords BEGIN and ends with keyword END. In this example the body is very simple; It deletes employee by employee identity. When all syntax statements inside body are correct, the database server will store the stored procedure name and code in its catalog for reusing later by another stored procedure or programs.
The EXEC statement is used to invoke a stored procedure. After the EXEC statement is the stored procedure name followed by parameter list. This is an example to delete an employees with identity is 8 by calling the sample procedure above Delete_Employee:
1 EXEC Delete_Employee(8)
43
If a stored procedure has more than one parameters, the values of them can be passed to it and separated by a comma. As you see writing and calling a stored procedure is very simple and easy. In the following tutorials, we will show you the feature and syntax of a stored procedure along with statement which can be used inside the body so you can empower its power. Next you will learn how to use parameter list to pass and get data in and out of stored procedures parameter list in stored procedure.
The third part of a parameter is its types. This part is optional, by default it is the IN. There are three parameter types: IN, OUT and INOUT. As you guess IN is abbreviation of input, OUT is abbreviation of output and INOUT is combined of both. With input parameter you can pass the value to the stored procedure. As in the previous tutorial example, we pass the employee identity to the storprocedure and delete the employee based on it. Output parameter allows you get the value back from the stored procedure, for example you may write a stored procedure to insert an employee and get its id back to the application to use in another part of the program. The INOUT parameter type as its name suggested can act as both types of parameter. In some SQL database sever product, it does not require parameter has @ sign as prefix so you should be careful that the name of the parameter must not be equal to the name of column otherwise you may face up to the disaster without any warning or error message from the database server. In Microsoft SQL Server 2005/20008, it allows you to specify the default value of the parameter. this is a big plus because you can call a stored procedure without passing parameters, It will use default values. Here is syntax of default value of parameter.
1 @parameter DataType(Size) = Default_Value
In our example we can modify to use default value for stored procedure as follows:
1 CREATE PROCEDURE Delete_Employee 2 (@EmployeeId INT = 0)
44
When you call it without passing parameter value, it will delete the employee with the identity is zero. SQL stored procedure parameter list is simple and easy to grasp? let's move to the body part of the stored procedure.
45
<start -transaction statement> | <UPDATE statement> <procedural statement> ::= <BEGIN-END block> <EXEC statement> <CLOSE statement> <DELCARE condition statement> <DELCARE cursor statement> <DELCARE handler statement> <DELCARE variable statement> <FETCH cursor statement> <flow control statement> <OPEN cursor statement> <SET statement> | | | | | | | | | |
With the BEGIN and END keword you can label the block of code inside the body. You can have one or more blocks, each block can be nested each other. Labeling the block has its own advantages. For example, it makes your code more clean when you have mutilple blocks. Let's get your hand with some source code to demonstrate the stored procedure body. Imagine we have employee table, in one day the table may have many records and it is very costly to get all the data from it to display them in our application. It would be nice if we can provide pagination feature for application to select needed records it needs to reduce the traffic between the database server and application server. Here is stored procedure to make it possible:
CREATE PROCEDURE GetEmployeePaged @PageSize int = 10,-- pagesize @CurrentPage int = 1,-- current page no @ItemCount int output -- total employee found AS BEGIN -- declare local variables for pagination DECLARE @UpperBand INT, @LowerBand INT SET @LowerBand = (@CurrentPage - 1)* @PageSize SET @UpperBand = @CurrentPage* @PageSize + 1 -- assign itemcount output parameter SET @ItemCount = ( SELECT COUNT(employeeId) FROM employees ) -- create temporary table to store paged data CREATE TABLE #ALLROW( RowID INT PRIMAY KEY IDENTITY(1,1), EmployeeId INT, Name VARCHAR(255), salary DECIMAL(7,2) ) -- insert data into the temporary table INSERT INTO #ALLROW SELECT EmployeeId, Name, salary FROM employees -- get paged data SELECT * FROM #ALLROW WHERE RowID > @LowerBand AND RowID < @UpperBand
46
END
First in parameter list we have three parameters and their meanings are exactly what they are. @pagesize specifies number of record per page, @currentpage specifies the current page number and @itemcount specifies total record found. So we can get the employee record in the page 1 with 10 record per page by calling:
1 EXEC GetEmployeePaged(10,1,@itemcount)
The next we declare two local variables. These variables are used inside the stored procedure for determining the start row and end row we will retrive the records. These variables' values are calculated based on the @pagesize and @currentpage. Then we use SET statement to assign output parameter @itemcount to the total records of the employee. Finally we create a temporary table to store the data, insert the data into the temporary table and retrieve the needed records. As you can see the stored procedure is very flexible, you can leverage it to deal with tough situation in database developement. In the next tutorial we will show you how to use local variable and use SET statement as shown in the example above in the stored procedure. Next tutorial: Local variables in stored procedure
DECLARE keywords is used to declare local variables. This source code snippet shows you how to declare a numeric and an alphanumeric variables:
1 DECLARE @Found INT 2 DECLARE @Firstname VARCHAR(255)
Some database server support initial value for local variables and some not. If supported, we can specify the default value for local variable. The expression for the default value of local variables are not limited to literals (like 'name' or 1) but may consist of compound expressions, including scalar subqueries. Local variable has its own scope. It does not exist when the stored procedure finish. Inside each code block local variable only visible it the block it declared. 47
The SET statement can be used to assign value to local variable. Here is the syntax :
1 <set statement> ::= 2 SET <local variable definition> 3 [ {, <local variable definition> }... ] 4 5 <local variable definition> ::= 6 <local variable> { = | := } <scalar expression>
We can use SET statement to assign value or expression to local variable. You can refer to the example in stored procedure body tutorial. Local variable is intermedia storage to store temporary result in stored procedure.In the next tutorial, we will show you how to use flow-control statements in stored procedure.
In complex cases, we can use CASE statement instead of IF-THEN-ELSE statement. CASE statement evaluates a list of boolean expression and returns one of multiple possible result expressions. CASE statement is similar to the swith-case statement in other programming languages such as C/C++, C# or Java. Here is an example of using CASE statement to display salary level of employee. We have employee table data as follows:
1 employee_id 2 ----------name salary -------- -------
48
3 4 5 6 7 8
1 2 3 4 5 6
01 02 03 04 05 06 07 08 09 10 11 12 13
CREATE PROCEDURE Cal_Factorial @inyN INT, @intFactorial BIGINT OUTPUT AS BEGIN SET @intFactorial = 1 WHILE @inyN > 1 BEGIN SET @intFactorial = @intFactorial * @inyN SET @inyN = @inyN - 1 END END
49
In the real world database programming you will need to use the conditional statements to write own your stored procedures. Next we will show you how to modify stored procedure using ALTER and DROP statement
To remove a stored procedure from database catalog, we can use DROP PROCEDURE.
1 DROP PROCEDURE spName
When you remove stored procedure, be noted that some database products have a feature that allows you to remove the dependency database objects like table, view, index or other stored procedures also. Stored procedure is compiled before it executes. Each database server has its own compiling strategy. You can specify the compiling option when you with WITH RECOMPILE statement as follows:
1 CREATE PROCEDURE spName 2 (parameter_list) AS 3 WITH RECOMPILE 4 BEGIN 5 -- stored procedure body here 6 END
The WITH RECOMPILE statement guarantees that each time the stored procedure is invoked, the compiler is called and compile the stored procedure again. With WITH RECOMPILER the stored procedure is recompiled and adjusted to the current situation of the database which brings some advantages to the processing strategy. But be noted that the compilation process takes time and also decreases the performance of the database server. Therefore for each stored procedure ,we can specify which is the best to use WITH RECOMPILE.
SQL Functions
SQL Aggregate Functions
Aggregate SQL functions summarize the results of an expression for the group of rows in database table and returns a single value for that group. 50
51
To find the highest and lowest salary of employees in the list, the following query could be used:
1 SELECT MAX(salary) max_salary, 2 MIN(salary) min_salary 3 FROM employees
For example, the following query could be used to calculate the average salary of all employees in employees table: 52
In order to calculate the total amount of salary the company has to pay each month for all employees, we can use this query:
1 SELECT SUM(salary) AS total_salary 2 FROM employee
SQL PI Function
SQL PI() function maybe the most simplest mathematical SQL function because it returns a constant value of pi
Database Trigger
Introducing to Database Trigger
Trigger is a kind of stored procedure means it can contains declarative or procedural SQL statements except one thing it cannot be invoked explicitly by user or other stored procedures. Triggers are a kind of stored procedure which are invoked automatically by database server when predefined events occurred. Events here can be altering the tables, drop the tables, adding or removing rows on a table. Trigger is a kind of stored procedure means it can contains declarative or procedural SQL statements except one thing it cannot be invoked 54
explicitly by user or other stored procedures. It only can be invoked when a predefined event occurred. Because of this feature, triggers are usually consider as events in the database. Triggers can be applied in some contexts :
Triggers can helps database administrator gather statistic data on table access. Triggers can be used to provide transparent logging service to log data changes and then send notification to the database administrator. Triggers can be used to generate and maintain derived data in derived column such as computed column. Triggers can be used to enforce data integrity when the business rule of data is too complex and prevent invalid transaction. And triggers can be used to enforce complex security authorization context..
Triggers are useful for use in the database but it is suggested that it should be used only when necessary. The triggers can put the burden of interdependency on the database and also burden of maintenance. Triggers was added to SQL3 standard but different database servers implement trigger in different ways. So it is easier to demonstrate trigger in a specified database server. We will use Microsoft SQL Server 2005 for demonstration We surely also try to provide you resources where you can find how other database servers implements trigger.
Database Cursor
Introducing to Database Cursor
In some database management contexts, we need to traverse through a set or records, process each record, move to next record and loop until the final record is reached. This is the reason why database cursors has invented.
3. We must set the position for cursor to a record or set of records that we need to traverse through 4. Data from one or more current records is fetched, then we can make some modification on it. 5. Loop the step 3 and 4 until the cursor reaches the final record in the set of record 6. Finally we have to close and release the cursor resources. In this tutorial, we will use Transact-SQL cursors for demonstration. We also provide you resources if you work with other RDBMS such as MySQL, Oracle... Transact-SQL cursor can be used from stored procedure, functions or triggers. Let's move to the section which we will show you how to use Transact-SQL cursors.
1 DECLARE cursor_name CURSOR 2 FOR select_statement Populate the cursor with Open
statement.
Use the fetch statement to change the current record in the cursor and stores that record into local variables
1 FETCH [[NEXT | PRIOR | FIRST | LAST 2 | ABSOLUTE {n | @NVAR} 3 | RELATIVE {n | @NVAR} 4 ]FROM] 5 {{[GLOBAL] cursor_name }|@cursor_variable_name} 6 [INTO @variable_name[, . . .n] ]
Process the retrieved data Loop the step 3 and 4 until the final record in the result set is reached Close the cursor with close statement
It would be easier to explain how to use transact-SQL cursor work via an example. Let's move to the an example how to use cursor.
56
57