You are on page 1of 57

SQL Tutorial

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

What can you do with SQL?


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.

SQL Data Manipulation Language (DML)


SQL data manipulation language (DML) is a main part of SQL statements. SQL DML allows you to retrieve data from the database tables in relational database management system (RDBMS). In addition, SQL DML allows you change or delete data from the database tables by using UPDATE and DELETE statements. Here are all the SQL statements related to the SQL data manipulation language: 1. SQL SELECT 2. SQL WHERE 3. SQL ALIAS 4. SQL DISTINCT 5. SQL ORDER BY 6. SQL IN 7. SQL BETWEEN 8. SQL LIKE 9. SQL GROUP BY 10. SQL HAVING 11. SQL INNER JOIN 12. SQL OUTER JOIN 13. SQL SELF-JOIN 14. SQL SUBQUERIES 15. SQL UNION 16. SQL INSERT 17. SQL UPDATE 18. SQL DELETE

SQL Data Definition Language (DDL)


SQL Data definition language is a subset of SQL statements. SQL Database definition language allows yout to create, alter or remove different kind database objects such as tables, views, indexes.

SQL CREATE TABLE


1

2. SQL ALTER TABLE 3. SQL DROP TABLE SQL Tutorial References(for Practical)

SQL Sample Database


We use Northwind database as the sample database through all SQL tutorials in our website. The Northwind sample database provides you a good database structure and sample data to allow you to experiment with SQL statements you learn in each tutorial. We also try to make the tutorial as common as possible so you can practice with various Relational Database Management Systems (RDBMS). The sample database is also available in almost common RDBMSs such as MS Access, MS SQL Server, MySQL. Here is the database diagram of the Northwind sample database:

__________*****____________________

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'

lastname --------Peacock Buchanan Suyama King Callahan Dodsworth

firstname --------Margaret Steven Michael Robert Laura Anne

title -----------------------Sales Representative Sales Manager Sales Representative Sales Representative Inside Sales Coordinator Sales Representative

country ------USA UK UK UK USA UK

date(hiredate) -------------1993-05-03 1993-10-17 1993-10-17 1994-01-02 1994-03-05 1994-11-15

The logical operators such as OR and AND are used to combine multiple conditions in WHERE clause.

SQL WHERE with AND operator


Multiple conditions are joined by AND operator must be TRUE for entire condition evaluate to TRUE. If one of condition is false, the entire condition evaluates to FALSE as well. If one of condition is unknown or NULL the entire condition evaluates to UNKNOWN. (You will learn how to deal with NULL in the next tutorials later). TRUE FALSE UNKNOWN TRUE TRUE FALSE UNKNOWN FALSE FALSE FALSE FALSE UNKNOWN UNKNOWN FALSE UNKNOWN Suppose you want to find all employees who were hired after 1993 and lived in UK, you can use AND operator to combine both conditions like the following query:
SELECT lastname, firstname, title, country, date(hiredate) FROM employees WHERE hiredate > '1993-01-01' AND country = 'USA' lastname firstname title country date(hiredate) -------- --------- ------------------------ ------- -------------Peacock Margaret Sales Representative USA 1993-05-03 Callahan Laura Inside Sales Coordinator USA 1994-03-05

SQL WHERE with OR operator


Multiple conditions joined by OR operator must be FALSE for entire condition is evaluated to FALSE. If one of condition is TRUE, the entire condition is evaluated to TRUE. If one of condition is UNKNOWN or NULL the entire condition is evaluated to UNKNOWN or NULL. TRUE FALSE UNKNOWN TRUE TRUE TRUE UNKNOWN FALSE TRUE FALSE UNKNOWN UNKNOWN TRUE UNKNOWN UNKNOWN For example you can find all employees who live in London or Seattle city, you can use OR operator in this case.
SELECT firstname, lastname, city FROM employees WHERE city = 'London' OR city = 'Seattle' firstname lastname city --------- --------- -------

Nancy Steven Michael Robert Laura Anne

Davolio Buchanan Suyama King Callahan Dodsworth

Seattle London London London Seattle London

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.

SQL Column Alias


Basically when you select data from a database table, the column headings of the output are the same as columns name. However, the column's name heading is too technical that does not bring you any information therefore you want to change it in the output. SQL provides you SQL alias to allow you to do so. You can assign a column alias in the column list of the SELECT statement by using AS keyword. Lets take a look at several examples of using SQL column alias.
1 SELECT productName AS product, 2 unitPrice AS price 3 FROM products 4 WHERE unitPrice >50 product price ------------------------ -------Mishi Kobe Niku 97.0000 Carnarvon Tigers 62.5000 Sir Rodney's Marmalade 81.0000 Thringer Rostbratwurst 123.7900 Cte de Blaye 263.5000 Manjimup Dried Apples 53.0000 Raclette Courdavault 55.0000

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

SQL Table Alias


SQL table alias is another name which you put after the table name of FROM clause of SELECT statement followed after table's name. SQL table alias is used when you refer a table multiple times in a SELECT statement with JOIN clause or when the table name is too long that you do want to make it easier to read and maintain. For example you can select organization structure to find out who is manager of whom by using SQL JOIN with table alias as follows:
1 SELECT E.lastname "Employee name", 2 M.lastname "Manager name" 3 FROM employees E 4 INNER JOIN employees M ON M.employeeID = E.ReportsTo Employee name Manager name ------------- -----------Davolio Fuller Leverling Fuller Peacock Fuller Buchanan Fuller Suyama Buchanan King Buchanan Callahan Fuller Dodsworth Buchanan

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

Peacock Leverling King Fuller Dodsworth Davolio Callahan Buchanan

Margaret Janet Robert Andrew Anne Nancy Laura Steven

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

Here is the excerpt of the result


productName --------------------------------Aniseed Syrup Chef Anton's Cajun Seasoning Chef Anton's Gumbo Mix Grandma's Boysenberry Spread Uncle Bob's Organic Dried Pears Northwoods Cranberry Sauce Mishi Kobe Niku Ikura Queso Cabrales Queso Manchego La Pastora Konbu Tofu ... unitPrice --------10.0000 22.0000 21.3500 25.0000 30.0000 40.0000 97.0000 31.0000 21.0000 38.0000 6.0000 23.2500

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.

SQL LIKE Statement


In this tutorial, you will learn how to use SQL LIKE to select data based on pattern matching SQL LIKE statement allows you to perform search string of text based on patterns. SQL LIKE statement is used in the WHERE clause of any valid SQL statements such as SELECT, INSERT, UPDATE and DELETE. SQL provides you two wildcard characters to construct a pattern. They are percentage (%) and underscore (_). 1. Percentage (% ) wildcard allows you to match a sequence of any characters including space. 2. Underscore ( _ ) wildcard allows you to match any single character. The syntax of SQL LIKE statement is as follows:
1 SELECT column1, column2 2 FROM table_name

14

3 WHERE column LIKE pattern

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

1 SELECT lastname, firstname 2 FROM employees 3 WHERE lastname LIKE '_a%'

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

Here is the excerpt of the result 16

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

Here is the excerpt of the result


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

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

Here is the excerpt of the result


OrderID ------total ----------

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

SQL GROUP BY with multiple columns


You can use SQL GROUP by with multiple columns in GROUP BY clause. For example, if you want to know how many sale orders were booked by a customer and sold by a employee, you can count sale order number and group by customer and employee. Here is the SQL statement to do so:
1 2 3 4 5 6 7 8 9 SELECT b.customerid, a.employeeid , COUNT(a.orderid) AS cnt FROM orders a INNER JOIN customers b ON a.customerid = b.customerid GROUP BY b.customerid ,a.employeeid ORDER BY b.customerid, cnt DESC

Here is the excerpt returned data from the query above:


+------------+------------+-----+ | customerid | employeeid | cnt | +------------+------------+-----+ | ALFKI | 4 | 2 | | ALFKI | 1 | 2 | | ALFKI | 6 | 1 | | ALFKI | 3 | 1 | | ANATR | 3 | 2 | | ANATR | 7 | 1 | | ANATR | 4 | 1 | | ANTON | 3 | 3 | | ANTON | 7 | 2 | | ANTON | 4 | 1 | | ANTON | 1 | 1 | | AROUT | 4 | 4 | | AROUT | 1 | 3 | | AROUT | 3 | 2 | | AROUT | 9 | 2 | +------------+------------+-----+

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

SQL INNER JOIN


SQL JOIN allows you to combine records from two or more tables into a temporary table called join-table. SQL provides five types of join: inner join, outer join, right join, left join and self-join.

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.

SQL INNER JOIN


The syntax of SQL INNER JOIN is as follows:
1 2 3 4 SELECT selection_list FROM table_A INNER JOIN table_B ON join_condition WHERE row_conditions.

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

Here is the excerpt output result from the query above:


productID --------1 2 3 4 5 6 7 8 9 10 .... productName --------------------------------Chai Chang Aniseed Syrup Chef Anton's Cajun Seasoning Chef Anton's Gumbo Mix Grandma's Boysenberry Spread Uncle Bob's Organic Dried Pears Northwoods Cranberry Sauce Mishi Kobe Niku Ikura categoryName -------------Beverages Beverages Condiments Condiments Condiments Condiments Produce Condiments Meat/Poultry Seafood

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.

SQL OUTER JOIN


Different from the SQL INNER JOIN, SQL OUTER JOIN returns all records from both joined tables even there is no matching record found. There are three types of SQL OUTER JOIN: FULL OUTER JOIN, LEFT OUTER JOIN and RIGHT OUTER.

SQL LEFT OUTER JOIN


Suppose we join two tables A and B. Left outer join returns all records from the table A (left table) plus matching records in the table B (right table). It means the result of the SQL LEFT OUTER JOIN always contains the records in the table A (table in the left side) even no matching record found in the table B plus matching records in the table B. Here is the Venn diagram to visualize how SQL LEFT OUTER JOIN works. 21

The syntax of left outer join is as follows:


1 SELECT * FROM table_A 2 LEFT OUTER JOIN table_B ON join_conditions 3 WHERE row_conditions

SQL RIGHT OUTER JOIN


SQL RIGHT OUTER JOIN returns all records from the table B (table in the right side), even no matching record found in the table A, plus matching records in the table A. Venn diagram to visualize how SQL RIGHT OUTER JOIN works:

The syntax of SQL RIGHT OUTER JOIN is as follows:


1 2 3 4 SELECT column_list FROM table_A RIGHT OUTER JOIN table_B ON join_conditions WHERE row_conditions

SQL FULL OUTER JOIN


SQL FULL OUTER JOIN combines results of both left outer join and right outer join therefore it returns all records from both tables. Venn diagram to visualize how SQL Full Outer Join works:

22

The syntax of SQL Full outer join is as follows:


1 2 3 4 SELECT column_list FROM table_A FULL OUTER JOIN table_B ON join_conditions WHERE row_conditions

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

Here is the output of the sql self-join query above:


employee -------Nancy Janet Margaret Steven Michael Robert Laura Anne manager ------Andrew Andrew Andrew Andrew Steven Steven Andrew Steven

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 )

Subqueries with Comparison Operators


A subquery can be used with comparison operators such as (=, < >, >, > =, <, ! >, ! <, or < =). For example, we can use subquery with comparison operator to find all products which has prices greater than average prices as follows:
1 SELECT productName 2 FROM products 3 WHERE unitprice > (SELECT AVG(unitprice) 4 FROM products)

26

Subqueries with UPDATE, DELETE and INSERT statements.


A subquery can nested in the DML statements such as UPDATE, DELETE and INSERT statement. Here is a subquery to update the unit price of all products supplied by vendor number 15.
1 UPDATE products 2 SET unitprice = unitprice * 0.5 3 WHERE productid IN (SELECT productid 4 FROM suppliers 5 WHERE supplierid = 15)

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

Here is the excerpt output:


city --------------Aachen Albuquerque Anchorage Barcelona Barquisimeto Bergamo Berlin Bern Boise Brandenburg Bruxelles

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.

Insert one record into a database table.


Here is the syntax of SQL INSERT statement which allows you to insert one record at a time into a database table.
1 INSERT INTO table_name (column1, column2) 2 VALUES (value1, value2,).

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/

Insert multiple records into a database table


SQL INSERT statement also allows you to insert multiple records into a database table at a time. Here is the syntax:
1 INSERT INTO table_name(column1,column2) 2 VALUES (value1,value2,), 3 (value1,value2,), 4

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')

Copy data from another database table


Sometime you need to copy data from one table into another table for backing up for example. SQL INSERT statement allows you to copy data from another database tables to a database table. Here is the syntax:
1 2 3 4 INSERT INTO table_name(column1, column2,) SELECT value1, value2 FROM table_name2

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.

SQL CREATE TABLE


In this tutorial, you will learn how to use SQL CREATE TABLE statement to create database table. Database table is a basic element of the database. Before storing data in a table you have to create it. SQL provides CREATE TABLE statement to allow you to do so. Here is the common syntax of SQL CREATE TABLE statement:
1 2 3 4 5 CREATE TABLE table_name( Column_name1 data_type(data_length ), Column_name2 data_type(data_length ), .. )

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.

SQL ALTER TABLE


In this tutorial, you will learn how to use SQL ALTER TABLE to modify database table schema. You can not only create and remove a database table but also modify an existing database table. SQL provides you ALTER TABLE statement to allow you to do so. With SQL ALTER TABLE statement you can do the following things on the database 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.

To add new column in a table you use the following syntax:


ALTER TABLE table_name ADD COLUMN new_column datatype(datalength)

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.

SQL DROP TABLE


In this tutorial, you will learn how to use SQL DROP TABLE statement to completely delete database table structure and data from a database. SQL DROP TABLE is used to remove the whole database table in term of table structure and data. When you use SQL DROP TABLE, the database engine removes all objects related to that table including data, table definition, indexes, table constraints, trigger and permission spec of that table. The syntax of SQL DROP TABLE is as follows:
1 DROP TABLE table_name

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

SQL DROP TABLE examples


Here is an example of removing table employees in the current working database:
1 DROP TABLE employees

To remove table employees in the database tmp, you'll need to execute the following query:
1 DROP TABLE tmp.employees

Remarks on SQL DROP TABLE

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.

SQL Cheat Sheet


The SQL cheat sheet is designed to provide a quick reference for the most common SQL statements you use. It is one-page A4 printable document in both PDF and JPEG format. You can print it out and stick it to your desk.

SQL Statements Cheat Sheet


SQL statements cheat sheet gives you the most common usage SQL query. You can find the most basic SQL statements from basic SQL statement to advanced SQL Join. In addition you can find the SQL statements for creating database objects such as tables, views and indexes.

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/

SQL Data Definition


CREATE TABLE Statement
Table is a basic element of relational database and create table is very important before you are working with data which you want to store.

ALTER TABLE Statement


with SQL ALTER TABLE statement you can add, drop one or more columns from a table. 36

DROP Table Statement


DROP TABLE statement allows you drop an existing table in database which is useful in some programming situations.

How to Create SQL View


SQL View is a virtual table which is used to encapsulate a complex queries.Click here to see how to create SQL view

SQL ALTER VIEW Statement


SQL view is a virual table so it can be changed using ALTER VIEW statement.

SQL DROP VIEW Statement


SQL DROP VIEW statement removes view definition from the system catalog and the dependent objects of that view will become invalid.

Creating Database Index


A database index is similar to the book's index which helps you to find a topic faster by looking up on it.

SQL DROP INDEX statement


SQL DROP INDEX statement frees allocated memory and removes the index definition from the database information schema

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.

SQL CASE Expression Tutorial


SQL CASE expression is used as a kind of IF-THEN-ELSE statement.

SQL MINUS or EXCEPT Operator


SQL MINUS or EXCEPT operator work on two table expressions. The result set takes records from the first table expression, and then subtract out the ones that appear in the second table expression. If the second table expression includes the records which are not appear in the first table expression, these records will be ignored.

SQL INTERSECT Opertor Tutorial

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.

SQL UNION Operator


SQL UNION operator is one of the basic set operations in the relational database. SQL UNION operator allows you to combine the match result sets of two (or more than two) select queries into a single table. Two result sets of the select queries must be made up of same kind elements such as same number of column, and same data type (or automatically cast to each other) in all columns. In most implementations, the data type conversion will be occurred but it is very dependent-implementations. You can check it out your RDBMS to find out. The duplicated records of two result sets are eliminate except theUNION ALL is used. The common syntax of SQL union is very simple as follows:
query1 UNION (ALL) query2

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

This is the query to union two table data


SELECT * , 2006 AS year FROM cost2007 UNION SELECT * ,2007 AS year FROM cost2006

Here is the result which is sorted by cost centers:


CostCenterId -----------1 1 2 2 3 Cost -----120000 300000 250000 150000 450000 year -----2006 2007 2006 2007 2006

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.

SQL CASE Expression


A special scalar expression in SQL language is CASE expression. SQL CASE expression is used as a kind of IF-THEN-ELSE statement. It is similar to switch statement in modern programming language such as Java or C#. The syntax of the CASE statement is simple as follows :
1 CASE column_name 2 WHEN condition1 THEN result1 3 WHEN condition2 THEN result2 4 ... 5 ELSE result 6 END

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

SQL MINUS or EXCEPT Operator


SQL MINUS or EXCEPT operator work on two table expressions. The result set takes records from the first table expression, and then subtract out the ones that appear in the second table expression. If the second table expression includes the records which are not appear in the first table expression, these records will be ignored. The syntax of using SQL MINUS is simple as follows :
1 2 3 1 2 3 table_expression1 MINUS table_expression2 table_expression1 EXCEPT table_expression2

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.

SQL INTERSECT Operator


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. INTERSECT operator, like UNION operator, removes all duplicated row from the result sets. Unlike the UNION operator, INTERSECT operator operates as AND operator on tables expression. It means data row appears in both table expression will be combined in the result set while UNION operator operates as OR operator (data row appear in one table expression or both will be combined into the result set). The syntax of using INTERSECT operator is like UNION as follows:
1 table_expression1 2 INTERSECT 3 table_expression2

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

salary ------3000.00 2800.00 2700.00

SQL Stored Procedure Tutorial


Introducing to Stored Procedure
Stored procedure by definition is a segment of code which contains declarative or procedural SQL statement.

Getting Started with Stored Procedure


You will learn how to write the first stored procedure and how to call it.

Parameter List in Stored Procedure


A stored procedure can have zero, one or more than one parameters. If a stored procedure has more than one parameter, each one must be separated by a comma.

Body Part of a Stored Procedure


The body part of a stored procedure is where you can put your business logic code inside to execute it as you want it to do. 41

Local Variables in Stored Procedure


Local variables are used in stored procedure to keep temporary intermediate results.

Common Usage Flow-Control in Stored Procedure


There are two most common usage of flow-control which are conditional execution and loop.

Modifying and Compiling Stored Procecdure


Once a store procedure is resided in the database server catalog, we can modify it by using the ALTER PROCEDURE statement or remove it by using DROP PROCEDURE

Introducing to Stored Procedure


Stored procedure by definition is a segment of code which contains declarative or procedural SQL statements. A stored procedure is resided in the catalog of the database server so we can call it from a trigger, another stored procedure or even from client appliations. As the definition above, the stored procedure can contains any SQL statement like INSERT, UPDATE and DELETE or any SQL data definition like CREATE TABLE, ALTER TABLE and etc. In addition, a stored procedure also supports procedure statements such as IF ELSE, WHILE... to make it as powerful as another programming languages such as C/C++, C# and Java. Using stored procedure has several advantages :

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

Getting Started with Stored Procedure


42

Writing the first stored procedure


Here is the first stored procedure source code:
1 CREATE PROCEDURE Delete_Employee 2 (@EmployeeId INT) 3 AS 4 5 BEGIN 6 DELETE FROM Employees 7 WHERE EmployeeId = @EmployeeId; 8 END

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.

Calling a stored procedure


We can call a stored procedure from the console window, from another stored procedure or from a program which can access database server. The syntax of calling a stored procedure is simple as follows:
1 EXEC spName(parameter_value_list)

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.

Parameter List in Stored Procedure


A stored procedure can have zero, one or more than one parameters. If a stored procedure has more than one parameter, each one must be separated by a comma. A parameter can be described by three parts : name, data type and its type which can by IN, OUT or INOUT. The first two pars are mandatory and the third part is optional. The name of parameter in Microsoft SQL Server must has @ sign as the prefix Otherwise the database server will notify the error and of course the stored procedure cannot be saved in the database catalog. Following the name is the parameter data type. The data type of the stored procedure can be any valid data type which are predefined in the database server. If you specify the size of the data type you can do it as follows:
1 @parameter VARCHAR(255)

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

3 AS 4 5 BEGIN 6 DELETE FROM Employees 7 WHERE EmployeeId = @EmployeeId; 8 END

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.

Body in Stored Procedure


Sponsored Links The body part of a stored procedure is where you can put your business logic codesinside to execute it as you want it to do. A stored procedure body always begin with BEGIN and END keywords. Inside the body, you can put the declarative SQL statements or procedure call like calling other stored procedures. Beside that, you can also use procedure statement like IF, WHILE; you can declare local variables and use them inside the stored procedure. Here is the general stored procedure syntax :
<create procedure statement> ::= CREATE PROCEDURE <procedure name> ( [ <parameter list> ] ) AS <procedure body> <procedure body> ::= <begin-end block> <begin-end block> ::= [ <label> : ] BEGIN <statement list> END [ <label> ] <statement list> ::= { <body statement> ; }... <statement in body::= <declarative statement> | <procedural statement> <declarative statement> ::= <EXEC statement> <CLOSE statement> <COMMIT statement> <DELETE statement> <EXECUTE immediate statement> <FETCH statement> <INSERT statement> <LOCK TABLE statement> <OPEN statement> <ROLLBACK statement> <savepoint statement> <SELECT statement> <SELECT INTO statement> <SET statement> <SET transaction statement> | | | | | | | | | | | | | | |

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

Local Variables in Stored Procedures


Local variables are used in stored procedure to keep temporary intermediate results. In order to use a local variable we have to declare it explicitly as follows:
1 <declare variable statement> ::= 2 DECLARE <variable list> <data type> [ 3 DEFAULT <expression> ] 4 5 <variable list> ::= 6 <variable> [ { , <variable> }... ]

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.

Common Usage Flow-Control in Stored Procedure


In this section, we will cover all basic flow-control statements which can be used in stored procedures. There are two most common usage of flow-control which are conditional execution and loop.

Conditional execution with IF-THEN-ELSE and CASE statement


The IF-THEN-ELSE statement is used to evaluate the value of boolean expression; if the value is True it execute the block code that follows it otherwise it will execute the block code that follows by ELSE.The ELSE part is optional in thestatement. Here is an stored procedure which finds the maximum value between two integers using IFTHEN-ELSE statement. The example is easy just for demonstration.
01 02 03 04 05 06 07 08 09 10 11 CREATE PROCEDURE FindMax @v1 INT, @v2 INT, @m INT OUTPUT AS BEGIN IF @v1 > @v2 SET @m = @v1 ELSE SET @m = @v2 END

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

jack mary newcomer anna Tom foo

3000.00 2500.00 2000.00 2800.00 2700.00 4700.00

And here is the stored procedure example:


01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 CREATE PROCEDURE DisplaySalaryLevel AS BEGIN SELECT employeeId, name,salary, salary_level = CASE salary WHEN salary < 1000 THEN 'very low' WHEN salary > 1000 AND salary < 2000 THEN 'low' WHEN salary > 2000 AND salary < 4000 THEN 'average' WHEN salary > 4000 AND salary < 10000 THEN 'high' WHEN salary > 10000 THEN 'very high' END FROM Production.Product END

Looping with WHILE statement


Since T-SQL is fourth generation language and designed to operate with sets of data therefore it is also possible to write the code to loop through the record set and perform operations on a single record. Using loop will cause the performance of the server but in some cases it is necessary to use this feature. Here we will you an example of using WHILE loop statement to calculate the factorial of an integer number.

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

Modifying and Compiling Stored Procecdure


Once a stored procedure is resided in the database server catalog, we can modify it by using the ALTER PROCEDURE statement as follows:
1 2 3 4 5 ALTER PROCEDURE spName(parameter_list) AS BEGIN -- stored procedure body here END

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

SQL Mathematical Functions


SQL mathematical functions are very important to all programming languages and also to SQL. Here we cover all common SQL mathematical functions such as ABS, POWER, SQRT, RANDOM...with clear explanations and source code examples

SQL String Functions


SQL string functions allow you to manipulate character data effectively. SQL Functions SQL Aggregate Functions

SQL Aggregate Functions


SQL MAX and MIN function
The SQL MAX() and MIN() functions allow you to display maximum and minimum values in a set.

SQL COUNT Function


The SQL COUNT() function used to count number of record of each database table.

SQL AVG Function


The SQL function AVG() calculates the arithmetic average of the series of numbers of its argument

SQL SUM Function


The SQL SUM() function uses to sum the values

SQL MAX and MIN Functions


The SQL MAX() and MIN() functions allow you to display maximum and minimum values in a set.
1 MAX ([DISTINCT]|[ALL] <expression>) 2 MIN([DISTINCT]|[ALL] <expression>)

Here we have employee table:


1 employee_id 2 ----------3 1 4 2 5 3 6 4 7 5 8 6 name -------jack mary newcomer anna Tom foo salary ------3000.00 2500.00 2000.00 2800.00 2700.00 4700.00

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

Here is the output:


1 max_salary 2 ---------3 4700.00 min_salary ---------2000.00

SQL COUNT Function


The SQL COUNT function is used to count a number of records of each database table. Here is the syntax:
1 COUNT([DISTINCT]|[ALL] <expression>)

Let's take a look at employees table


1 employee_id 2 ----------3 1 4 2 5 3 6 4 7 5 8 6 name -------jack mary newcomer anna Tom foo salary ------3000.00 2500.00 2000.00 2800.00 2700.00 4700.00

This query counts a number of employees of the employee table:


1 SELECT COUNT(*) as total_employee 2 FROM employees

Here is the output:


1 total_employee 2 -------------3 6

SQL AVG Function


The SQL AVG function calculates the arithmetic average of the series of numbers of its argument. The syntax is simple as follows:
1 AVG ([DISTINCT]|[ALL] <numeric expression="">)

For example, the following query could be used to calculate the average salary of all employees in employees table: 52

1 SELECT AVG(salary) average_salary 2 FROM employees 1 average_salary 2 -------------3 2950.000000

SQL MAX and MIN Functions


The SQL SUM() function uses to sum the values. Here is the syntax:
1 SUM([DISTINCT]|[ALL] <numeric_expression>)

We have the sample table: Employee


1 employee_id 2 ----------3 1 4 2 5 3 6 4 7 5 8 6 name salary -------- ------jack 3000.00 mary 2500.00 newcomer 2000.00 anna 2800.00 Tom 2700.00 foo 4700.00

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

Here is the output:


1 total_salary 2 -----------3 17700.00

SQL Mathematical Functions


SQL CEIL() (or CEILING) and FLOOR() Functions
Both SQL CEIL(or CEILING) and FLOOR functions are round the numbers. SQL CEIL roundup to the nearest integer value while FLOOR round down to the next least integer value.

SQL RAND Function


The SQL RAND() function is used to generate some random numbers at run time.

SQL ABS Function


SQL ABS function returns the absolute value of an numeric input argument. 53

SQL EXP Function


The SQL EXP() function returns e raised to the n-th power (e is the base of the natural logarithm and is equal to approximately 2.718281828459).

SQL PI Function
SQL PI() function maybe the most simplest mathematical SQL function because it returns a constant value of pi

SQL SQRT Function


The SQL SQRT function extracts the square root from the positive numeric input argument. SQL SQRT function accepts only positive arguments, and returns an error when a negative argument is passed in.

SQL POWER Function


The SQL POWER() function returns the

SQL ROUND Function


The SQL ROUND function rounds a number to a specific length or precision.

SQL LOG Function


The SQL LOG() function allows us to operate mathematical logarithmic calculation

SQL Trigonometric Functions


SQL trigonometric functions allow you to operates trigonometric calculations.Here are some common SQL trigonometric functions you need to know in your daily SQL programming.

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.

Using Transact-SQL Cursor Syntax


In this section, you will learn to use required steps to work with cursor.

Introducing to Database Cursor


SQL was designed to work with a set of data and SELECT statement is the most important statement. SQL statement allows us to select a record or a set of records based on some criteria and it solves almost problem in database management. But 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. There are many types of cursors are implemented in various RDBMS products using different syntax. Even though, the way we work with cursors are following this fashion: 1. We have to define a cursor with and set its features 2. Then we must populate a set of records to use with the cursor 55

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.

Using Transact-SQL Cursor Syntax


In order to using Transact-SQL cursors, you have to perform the following steps:

Create a cursor with declare cursor statement based on a SELECT statement.

1 DECLARE cursor_name CURSOR 2 FOR select_statement Populate the cursor with Open

statement.

1 OPEN {{[GLOBAL] cursor_name} cursor_variable_name} 2

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

1 CLOSE {{[GLOBAL] cursor_name }|cursor_variable_name} 2

Deallocate the cursor by using Deallocate statement.

1 DEALLOCATE {{[GLOBAL] cursor_name }|@cursor_variable_name}

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

You might also like