SQL Tutorial

What is SQL?
• • •

SQL stands for Structured Query Language SQL is pronounced as /ˌɛs.kjuːˈɛl/ 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

3

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, you’ve learned how to use simple SQL SELECT statement to retrieve data from a table. You’ve 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.

4

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'

5

lastname. you can use AND operator to combine both conditions like the following query: SELECT lastname.------.-------------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. 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. If one of condition is unknown or NULL the entire condition evaluates to UNKNOWN. title. (You will learn how to deal with NULL in the next tutorials later). firstname. city FROM employees WHERE city = 'London' OR city = 'Seattle' firstname lastname city --------. the entire condition is evaluated to TRUE. SQL WHERE with AND operator Multiple conditions are joined by AND operator must be TRUE for entire condition evaluate to TRUE.--------. the entire condition evaluates to FALSE as well.--------. If one of condition is UNKNOWN or NULL the entire condition is evaluated to UNKNOWN or NULL.-----------------------. SELECT firstname.------- 6 . country. If one of condition is false. 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 OR operator in this case. date(hiredate) FROM employees WHERE hiredate > '1993-01-01' AND country = 'USA' lastname firstname title country date(hiredate) -------. If one of condition is TRUE.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.

In case the column name is lengthy and sometimes it is designed as an abbreviation.-------Mishi Kobe Niku 97. The first column alias is product which represents for productname and the second alias is the price which represent for unitprice. the column alias enables the output more meaningful and easy to read. the column's name heading is too technical that does not bring you any information therefore you want to change it in the output. Let’s take a look at several examples of using SQL column alias. 2 unitPrice AS price 3 FROM products 4 WHERE unitPrice >50 product price -----------------------. SQL supports two types of alias which are known as column alias and table alias.0000 Thüringer Rostbratwurst 123. 7 .5000 Manjimup Dried Apples 53. the column headings of the output are the same as columns’ name. 1 SELECT productName AS product. you’ve learned how to filter the records in the result set in the SQL SELECT statement by using the SQL WHERE clause with conditions. You’ve also learned how to use various common basic operators to construct a condition and use logical operators to combine condition together.Nancy Steven Michael Robert Laura Anne Davolio Buchanan Suyama King Callahan Dodsworth Seattle London London London Seattle London In this tutorial.7900 Côte de Blaye 263.0000 In the SELECT statement above. 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.5000 Sir Rodney's Marmalade 81. you will learn how to use different SQL alias including column alias and table alias with SQL SELECT statement. we used two column aliases.0000 Carnarvon Tigers 62. 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. You can assign a column alias in the column list of the SELECT statement by using AS keyword. SQL Column Alias Basically when you select data from a database table. SQL provides you SQL alias to allow you to do so. However. SQL Alias In this tutorial.0000 Raclette Courdavault 55.

You can omit the AS keyword in the column alias. • • You use column alias to reorganize or reformat the output to make the output more meaningful. 2 M.Be noted that the AS keyword is optional. When you use table alias.column_name SQL alias is is very useful when using with SQL subqueries. In this tutorial. you've learned how to use SQL alias including column alias and table alias.ReportsTo Employee name Manager name ------------. 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. the column has to be refered as follows to avoid ambiguous column name error.lastname "Employee name". 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.lastname "Manager name" 3 FROM employees E 4 INNER JOIN employees M ON M. we refered to the same table employee. 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. 1 table_alias. SQL DISTINCT 8 . If the column alias contain space but it must be enclosed in quotes. SQL self join and SQL INNER JOIN statements.employeeID = E.-----------Davolio Fuller Leverling Fuller Peacock Fuller Buchanan Fuller Suyama Buchanan King Buchanan Callahan Fuller Dodsworth Buchanan In above query. We can rewrite the above SELECT query as follows: 1 SELECT productName product. 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. 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 DISTINCT is used to eliminate the duplicated rows in the result of SELECT statement. you get the result with the duplicate row which you don’t expect. You can even put more columns after the DISTINCT keyword.------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.In this tutorial. In this case. For example. you will learn how to use SQL DISTINCT with SQL SELECT statement to eliminate duplicate records. you can answer this question by performing the following query: 1 SELECT DISTINCT city. At this time. For instance. the combination of all columns is used to evaluate the rows are duplicate or not. 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. country 2 FROM employees city country -------. 9 . you want to know all cities and countries information which employees live in. 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 You’ve put DISTINCT keyword before the column name which you want it distinction in value.

SQL ORDER BY statement allows you to sort the result set based on one or more sort keys in ascending or descending fashion. 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). 1 SELECT lastname.Beside DISTINCT keyword. firstname ASC lastname firstname --------... you can use ALL keyword to indicate that you don’t want to eliminate duplicated records. you will learn how to use SQL ORDER BY clause to sort the result set based on criteria. firstname 2 FROM employees 3 ORDER BY lastname DESC. The sort_key (sort_key1. 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..--------Suyama Michael 10 . you can sort all employees by their last name by performing the following query. sort_key2. column2… 2 FROM table_name 3 ORDER BY sort_key1 [ASC | DESC]. This is known as multi column sorting.) in SQL ORDER BY must be sortable. the default ordering is ascending. Here is the syntax of SQL ORDER BY: 1 SELECT column1. numeric or date time data type. sort_key2 [ASC | DESC] … SQL ORDER BY can only be used in SQL SELECT statement. It can be character.--------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. In this case you sort last name in ascending order. 1 SELECT lastname. Because ALL keyword is default to the SELECT statement so you don’t have to explicitly specify it in the SELECT statement. If you don’t specify the sort order by using ASC and DESC keywords. SQL ORDER BY In this tutorial. firstname 2 FROM employees 3 ORDER BY lastname lastname firstname --------.

you can use CONCAT function.Margaret Suyama.firstname) fullname 2 FROM employees 3 ORDER BY fullname fullname ---------------Buchanan.'.Andrew King. SQL ORDER BY can also accept any expression.-------------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.'. to construct full name of employees and then sort them all by full name. which allows you concatenate multiple strings in into one.Laura Davolio. And based on this sorted result. it then sorts the first name in ascending order. This sometimes led you to an 11 . firstname.Anne Fuller. For example.Robert Leverling. 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. Here is the query example: 1 SELECT CONCAT(lastname. date(hiredate) 2 FROM employees 3 ORDER BY 3 DESC lastname firstname date(hiredate) --------.Steven Callahan.Janet Peacock. 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.Nancy Dodsworth.Michael Almost RDMBS allows you to specify the sort key based on the positional number of column in the selection list. Suppose you want to sort employees by hired date to find out who are the most new hire employees of the company.--------.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. You can use positional number in ORDER BY clause as follows: 1 SELECT lastname.

unitPrice 2 FROM products 3 WHERE unitPrice IN (18.--------Chai 18. you only use it if you don't have any option. To find all products which have unit price are 18. for instance. unitPrice 2 FROM products 3 WHERE unitPrice = 18 OR unitPrice = 19 OR unitPrice = 20 As you can see.unexpected result if you forget to change the positional number. you will learn how to use SQL IN operator along with SQL WHERE clause to retrieve data in a set of values. SQL IN In this tutorial.0000 Inlagd Sill 19.0000 Lakkalikööri 18. SQL IN operator helps you to reduce the complexity of combining multiple OR conditions therefore it make SQL statement easier to understand and maintain. Therefore it is not recommended to use positional number in ORDER BY clause. 19 and 20 you perform the following query: 1 SELECT productName.0000 Steeleye Stout 18. 20) 12 .0000 Maxilaku 20. value2. In this tutorial. The syntax of using SQL IN operator is as follows: 1 SELECT column_list 2 FROM table_name 3 WHERE column IN (value1. you’ve learnt how to use SQL ORDER BY clause to sort the result in ascending and descending order. 19. value3…) The set of values must be comma-delimited and enclosed within parentheses. 19. To find all records which has a column value are not in a set you can use NOT IN. 1 SELECT productName. 20) productName unitPrice ---------------. unitPrice 2 FROM products 3 WHERE unitPrice NOT IN (18.0000 Chartreuse verte 18. 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.0000 Chang 19. SQL IN operator allows you to determine if a value is contained in a set of values.0000 The query above can be rewritten as following by using OR operator to combine multiple conditions.

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.0000 23. 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.0000 6.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 . Furthermore. unitPrice --------10. you can use SQL BETWEEN operator like the following query: 1 SELECT productName. For example you want to retrieve products which have unit price from 18$ to 19$.0000 Inlagd Sill 19.0000 40.0000 Chartreuse verte 18.0000 21.0000 Steeleye Stout 18. you’ve learn how to use SQL IN operator to find records which has value in a set.. SQL IN operator is also used in subquery which you will learn later in SQL subquery tutorial. In this tutorial.0000 31.0000 30. unitPrice 2 FROM products 3 WHERE unitPrice BETWEEN 18 AND 19 productName unitPrice ---------------.0000 21.0000 Chang 19.4000 13 .0000 Boston Crab Meat 18.3500 25. SQL BETWEEN In this tutorial. you’ve also learnt how to combine NOT operator with SQL IN operator to find all records which has value not in a set.--------Chai 18.0000 22.0000 38.2500 Beside these above usages..0000 97. SQL BETWEEN operator allows you to retrieve records which has value in a range of values.

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. Here is the query: productName ------------------------------Mishi Kobe Niku Konbu Teatime Chocolate Biscuits Sir Rodney's Marmalade Tunnbröd Guaraná Fantástica Thüringer Rostbratwurst Geitost Côte de Blaye Jack's New England Clam Chowder Rogede sild Zaanse koeken Filo Mix Tourtière Rhönbräu Klosterbier unitPrice --------97. In addition you’ve 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.7900 2. 1. SQL LIKE statement is used in the WHERE clause of any valid SQL statements such as SELECT. SQL provides you two wildcard characters to construct a pattern.5000 263. 2.5000 9.6500 9. SQL LIKE Statement In this tutorial. you can combine SQL NOT operator with SQL BETWEEN operator.0000 9.0000 7.0000 4.2000 81. UPDATE and DELETE.5000 7.5000 123.5000 9.0000 9.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. Percentage (% ) wildcard allows you to match a sequence of any characters including space.Lakkalikööri 18. They are percentage (%) and underscore (_). column2… 2 FROM table_name 14 . 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. Underscore ( _ ) wildcard allows you to match any single character. INSERT.7500 In this tutorial you’ve learned how to use SQL BETWEEN operator to find values which are in a range of values.4500 7.0000 6. The syntax of SQL LIKE statement is as follows: 1 SELECT column1.

To find all employees which have the first name ending with character ‘t’. 1 SELECT lastname. 1 SELECT lastname. firstname 2 FROM employees 3 WHERE lastname LIKE 'D%' lastname firstname --------. followed by character ‘a’ and followed by any characters. It could be CHAR.--------Davolio Nancy Dodsworth Anne The expression ‘D%’ means find all string starting with character ‘D’ and followed by any characters. you can execute the following query as follows: 1 SELECT lastname. Suppose you want to find all employees with the last name starting with D character. You can use the combination of both wildcard characters.--------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 use perform the following query.--------Fuller Andrew Callahan Laura Two wildcard characters ‘%’ and ‘_’ can combine together to construct a pattern. you can execute the following query. NVARCHAR… data type. You can put the wildcard ‘%’ at the beginning and the end of a string to find any string which contains string within those wildcards. firstname 2 FROM employees 3 WHERE firstname LIKE '%t' lastname firstname --------. firstname 2 FROM employees 3 WHERE lastname LIKE '%ll%' lastname firstname -------. For example you can find all employees which have last name starting with any single characters. For example to find all employees which have last name contain string “ll”. Let’s take a look at several examples of using SQL LIKE statement and constructing patterns.3 WHERE column LIKE pattern The data type of column must be alphanumeric in order to use SQL LIKE statement. Here is the query to do so: 15 . VARCHAR.

c2. ...--------Fuller Andrew Leverling Janet Peacock Margaret Buchanan Steven Suyama Michael King Robert Callahan Laura In this tutorial.. cn ORDER BY order_columns Let’s take a look at several examples of using SQL GROUP BY to see how it works.c2. The common syntax of SQL GROUP BY is as follows: 1 2 3 4 5 SELECT c1.. MIN. For each group you can apply aggregate functions such as SUM. 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.firstname 2 FROM employees 3 WHERE lastname NOT LIKE 'D%' lastname firstname --------. For example if you want to find all employees which first name is not starting with character ‘D’. SQL GROUP BY is used to divide a database table into groups based on group columns. aggregate_function(expression) FROM tables WHERE where_conditions GROUP BY c1.1 SELECT lastname. AVG. You can use SQL GROUP BY and SUM function to do so. SUM(unitPrice * quantity) 2 FROM order_details 3 GROUP BY orderID Here is the excerpt of the result 16 . Here is the query: 1 SELECT orderID. cn. 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. you can perform the following query: 1 SELECT lastname. you’ve learned how to use SQL LIKE statement to find string of text which matches a pattern. you will learn how to SQL GROUP BY clause to group a set of result set based on group columns.. SQL GROUP BY In this tutorial. You’ve learned how to use two wildcard characters: percentage (%) and underscore (_) to construct a pattern for using in SQL LIKE statement. MAX and COUNT to output the summary information. Suppose you want to find the total money of every sale order you have in order details table.

0000 1863. 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.2000 2490.8000 625.5000 517.8000 1119. 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.0000 1444.8000 1746.8000 625.9000 2018.0000 670.orderID ------10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 SUM(unitPrice * quantity) ------------------------440.8000 3730.4000 1813.0000 670.2000 You can use SQL GROUP BY clause together with SQL ORDER BY clause to sort the output result.8000 1119.5000 517. At this time SQL GROUP BY acts like SELECT DISTINCT to distinguish all records based on group columns.0000 1863.0000 1444.2000 SQL engine first looks at the GROUP BY clause and groups the table into groups based on the order identity.4000 1813.9000 2018.8000 1746.8000 3730. Here is the query: 1 SELECT orderID.6000 100. You can use SQL GROUP BY without the aggregate functions. Then SQL engine computes the sum of unitPrice column multiple with quantity column for each group.6000 100.2000 2490. SUM(unitPrice * quantity) total FROM Order_details GROUP BY OrderID ORDER BY total DESC Here is the excerpt of the result OrderID ------total ---------- 17 .

orderid) AS cnt FROM orders a INNER JOIN customers b ON a.2400 10741.customerid GROUP BY b. if you want to know how many sale orders were booked by a customer and sold by a employee.6000 SQL GROUP BY with multiple columns You can use SQL GROUP by with multiple columns in GROUP BY clause. you will learn HAVING clause which is related to GROUP BY.2000 10835.customerid = b.employeeid ORDER BY b. Here is the SQL statement to do so: 1 2 3 4 5 6 7 8 9 SELECT b. In the next tutorial.2000 11490.a.2000 11493.0000 16321.0000 12281.0000 11283.7000 11380. you can count sale order number and group by customer and employee. SQL Having 18 .employeeid .customerid. you’ve 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. 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. let’s move on. a.10865 11030 10981 10372 10424 10817 10889 10417 10897 10353 17250. For example.9000 15810. COUNT(a.customerid.customerid .

SQL HAVING clause is used together with SQL GROUP BY clause to filter group of records based on conditions. you can use HAVING together with the GROUP BY clause. 1 SELECT OrderID.0000 10981 15810. Here is the database diagram of them: 19 . COUNT(productID) prd_count 2 FROM order_details 3 GROUP BY orderID 4 HAVING prd_count > 5 orderID prd_count ------. right join. If you want to find all sale orders which have total sale greater than $120000. SQL HAVING clause is similar to WHERE clause in functionality manner but filter group of records not records. Sample tables We have two tables: categories and products in the sample database to demonstrate how the SQL JOIN works.---------10372 12281. Her e is the query: 1 SELECT orderID. you can use COUNT function with HAVING and GROUP BY together.0000 11030 16321. outer join. SQL provides five types of join: inner join. Let’s take a look at several examples of using SQL HAVING. » 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.2000 10865 17250. SUM(unitPrice * quantity) total 2 FROM Order_details 3 GROUP BY OrderID 4 HAVING total > 12000 OrderID total ------.9000 Suppose you want to find all orders which have a number of products greater than 5 . left join and self-join.--------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 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. you can use SQL INNER JOIN to combine the records in both tables as follows: 1 SELECT productID.productName. 2.categoryID = categories. 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..categoryName 2 FROM products 3 INNER JOIN categories ON products. SQL INNER JOIN returns records from both tables where a match is found based on join conditions (join_condition). Table_A and table_B are sometimes called joined-tables. One product belongs to only one category. and category name of each product from both tables products and categories. no records is returned. The join condition determines whether both records are matched or not. Suppose you need the following information: productId.categoryID Here is the excerpt output result from the query above: productID --------1 2 3 4 5 6 7 8 9 10 .1. If there is no match found. productName... In this case. 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 . One category can have multiple products.

There is another form of SQL INNER JOIN which called implicit inner join. SQL LEFT OUTER JOIN Suppose we join two tables A and B. LEFT OUTER JOIN and RIGHT OUTER. categories 3 WHERE products. 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. Most of the time you use foreign keys to form the join condition. In the next tutorial. In this tutorial. we can rewrite the example query as follows: 1 SELECT productID.productName. Here is the implicit SQL INNER JOIN syntax: 1 SELECT selection_list 2 FROM table_A. Here is the Venn diagram to visualize how SQL LEFT OUTER JOIN works. In this form you list all joined-tables after the FROM clause and put join condition in WHERE clause of the SQL SELECT statement. Left outer join returns all records from the table A (left table) plus matching records in the table B (right table). SQL finds a corresponding category in the categories table which has the same categoryID. 21 .categoryID There is another way to visualize the SQL INNER JOIN by using the Venn diagrams. you've learned how to use SQL INNER JOIN to retrieve data from two tables. SQL returns records otherwise no record is returned. In this case categoryID is the foreign key of two tables.For each product in the products table. As our above example. If there is a match found. SQL OUTER JOIN Different from the SQL INNER JOIN. There are three types of SQL OUTER JOIN: FULL OUTER JOIN. table_B 3 WHERE join_condition.categoryName 2 FROM products.categoryID = categories. you will learn how to use another kind of SQL join called outer join. SQL OUTER JOIN returns all records from both joined tables even there is no matching record found. In this way you can see that SQL INNER JOIN returns only records that match in both table_A and table_ B.

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. even no matching record found in the table A. Venn diagram to visualize how SQL Full Outer Join works: 22 .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).

SQL Self-join SQL self-join simply is a normal join which is used to join a table to itself. . you’ve learned how SQL OUTER JOIN works and all kinds of SQL OUTER JOIN: SQL LEFT OUTER JOIN.. SQL self-join can be any form of join such as SQL inner join. 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.column_name2. SQL outer join… so you can apply any join to the SQL self-join.column_name1 = B.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. we have employees table which stores not only employee data but also organizational structure.. 23 . The column reportsTo specifies the manager of an employee and is referenced to employeeID column. In our database sample. Here is common syntax of SQL self-join: SELECT column_list FROM table_A AS A INNER JOIN table_A AS B ON A. WHERE row_conditions SQL self-join is very useful when you want to retrieve related data storing in one table such as organizational structure. SQL RIGHT OUTER JOIN and SQL FULL OUTER JOIN.

lastname) manager FROM employees e INNER JOIN employees m ON m. The SQL statement contains a subquery is also called outer select or outer query. UPDATE and DELETE statement. INSERT.firstname. e.lastname) employee.firstname. A SQL subquery is somtimes refered as inner select or inner query.m. concat(m.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.employeeId = e. A SQL subquery can be used anywhere in a query where an expression is allowed.To list all information of employees and managers we can use SQL self-join as follows. SELECT concat(e. A SQL subquery is usually nested inside a SELECT. 24 .

Here is an example of using an SQL subquery as an expression in SELECT statement as MaxDiscount column: 1 SELECT orderid. 25 . 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.

! <. The total of quantity is calculated by using aggregate function SUM and GROUP BY clause.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. A SELECT statement of a SQL subquery must be enclosed in parenthesises. 01 02 03 04 05 06 07 08 09 10 SELECT o. e1. 1 SELECT e1. e1. The query at the next higher level is evaluated with these customer numbers and returns all sale orders numbers from those customers. 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 . ! >.reportsto 5 FROM employees e2 ) Subqueries with Comparison Operators A subquery can be used with comparison operators such as (=.employeeid.quantity) quantity FROM order_details o INNER JOIN products p ON p.• • A regular FROM clause to specify the table where a selected field is chose from.productid = o.productid WHERE o. >. The following SQL query is used to find the total quantity product bought by customers from USA. < >. Product name is selected by join order details table with product tables. p. The following query finds all managers of the company by refering table employees twice in outer query and subquery. Optional clauses such as WHERE.lastname 2 FROM employees e1 3 WHERE e1. It is not recommended to have a high number of leve of nesting subquery in a SQL statement. or < =). SUM(o. For example.productname. Finally outer query uses the order numbers to find all product number from order details table. <. > =.employeeid IN ( 4 SELECT e2.firstname. 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. A number of subquery can include in a subquery depends on the implementation of each RDBMS. A SQL subquery can include one or more subquery.productid. GROUP BY or HAVING.

productname. 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. 1 SELECT productid. 3 unitprice .unitprice 2 FROM products p1 3 WHERE unitprice > (SELECT AVG(unitprice) 4 FROM products 5 WHERE categoryid = p1.(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.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 a subquery to update the unit price of all products supplied by vendor number 15. A subquery can nested in the DML statements such as UPDATE. 1 UPDATE products 2 SET unitprice = unitprice * 0. 27 . 1 SELECT productid. DELETE and INSERT statements. DELETE and INSERT statement.Subqueries with UPDATE. and each corresponding column must has the same data type or at least convertible data type. productname. It means both columns lists must have the same number of columns. The subquery is evaluated for every rows selected by the outerquery. 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). 2 (SELECT AVG(unitprice) FROM products) average.categoryid) SQL UNION SQL UNION is used to combine results of two or more SQL SELECT queries into one. The following query is a typical example of correlated query for finding products which have price greater than average unit price in its category.

…). 28 . value2. In this case. Suppose you want to find all the cities of all customers and suppliers. column2…) 2 VALUES (value1. Here is the syntax of SQL INSERT statement which allows you to insert one record at a time into a database table. you've learned how to use SQL UNION to combine result of two or more SQL SELECT queries into one. Be noted that by default the DISTINCT is used if you don’t specify anything after UNION. SQL INSERT SQL INSERT statement allows you to insert one or more records into a database table. To enable duplication of records. 1 INSERT INTO table_name (column1. Let’s take a look at several examples of using SQL UNION. SQL INSERT statement is sometimes referred as SQL INSERT INTO statement. 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. in this case NULL values are considered as a single value. In addition SQL INSERT statement also allows you to copy data from a database tables to another database table. you can use ALL keyword followed after UNION explicitly. Insert one record into a database table.By default SQL UNION eliminates all duplicate records.

NOT null constraints… otherwise the insert action will be failed and new row is not added to the database table. 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. SQL INSERT statement allows you to copy data from another database tables to a database table. Here is an example of inserting multiple records into Shippers table.) must be same. Only data we have to provide for INSERT statement are company name and phone.…). Let’s take a look at an example of inserting data into the Shippers table by using SQL INSERT statement. column2. Here is the syntax: 1 2 3 4 INSERT INTO table_name(column1.'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. 1 INSERT INTO Shippers (companyName. Suppose you have a temporary table called table_tmp with the structure exactly the same as the shippers table. 3 ('DHL'. Here is the syntax: 1 INSERT INTO table_name(column1.value2. value2… FROM table_name2 … The selection list must be corresponding to columns of the database table you want to copy data.…).. the default value for column is used. the database server returns number of row affected.…) SELECT value1. 1 INSERT INTO shippers(companyName. 3 (value1. value2. After executing the query. column2.'1-800-782-7892').) and values (value1. you provide multiple values which are corresponding to the column list of the database table. 4… In this form. The values inserting to the database table must also satisfy other conditions such as constraints of foreign key. phone) 2 VALUES ('Alliance Shippers'. Now you want to copy data from the shippers table into this temporary 29 ...phone) 2 VALUES ('UPS'.column2…) 2 VALUES (value1. you specify the name of database table. followed after the INSERT INTO statement.value2. If the column is omitted. which you want to insert data into..In this form. The number of columns (column1.'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 don’t need to list it there in the column list..

region and postal code. If you update data in more than one column. The WHERE clause is optional. you can use SQL INSERT INTO SELECT statement. Another example is one of employee of the company change the address so you want to update address information including address. You can also use data which you retrieve from another table and then use it for SQL UDPATE statement as well. phone) 2 SELECT companyName. In addition. It is not required to provide the data directly to the SQL UPDATE statement. you can modify data of the whole table or subset of data based on condition in WHERE clause. Suppose one of employee in the company get married and need to change her last name. In this case by performing the following query: 1 INSERT INTO shippers_tmp (companyName. 3 column2 = value2 4 WHERE condition First you specify a database table where you want to update data after UPDATE keyword. Here is the query to do so: 1 UPDATE employees 2 SET lastname = 'Phan' 3 WHERE employeeID = 3. you’ve learned how to use SQL INSERT statement to insert one or more records into a database table. With SQL UPDATE statement. If you omit the WHERE clause. so you have to make the change by using the SQL UPDATE statement. Suppose her employee ID is 3. phone 3 FROM shippers In this tutorial. Let’s take a look at several examples of using SQL UPDATE. Here is the typical syntax of SQL UPDATE statement: 1 UPDATE table_name 2 SET column1 = value1. SQL UPDATE SQL UPDATE statement allows you to modify data in a database table. You can update data in one column or more. the columns has to be separated by commas (. city.table. 30 . 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. you also learned how to copy the data from a database table to another database table by using SQL INSERT SELECT INTO statement. all the records of the database table will be updated.). In this case you can use SQL UPDATE to change this data.

region = 'CA' WHERE employeeID = 3 In this tutorial. If you want to delete all data in a database table. city = 'San Jose'. To delete all employees in the table employees (not recommended. you will learn how to use SQL DELETE statement to remove data from database tables. 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. SQL provide you TRUNCATE statement which is more efficiently to delete the whole table./div> Let’s take a look at couples of examples using SQL DELETE statement. postalcode = 95125. it will be deleted otherwise nothing happens. it will delete all records in the database table. SQL DELETE statement allows you to delete one or more records in a database table. 1 DELETE FROM employeeterritories 2 WHERE employeeID = 3 31 . If you want to delete an employee you have to delete a record which has employeeid in employeeterritories table also. 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. So you have to execute two DELETE statements as follows: 1 DELETE FROM employees 2 WHERE employeeID = 3. you've learned how to use SQL UPDATE statement to update data in a database table.1 2 3 4 5 6 UPDATE employees SET address = '1300 Carter St'. SQL DELETE In this tutorial. 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. It is very time consuming and less efficient to use SQL DELETE statement to do so especially with the table with a big data.

other records in the linked table. Maximum length of each column: You have to specify the maximum length of data for each column. 32 . if exist. 3. timespan. try to imagine the maximum length a product can have. int. numerical (smallint. Name of each column in the table: It should be meaningful also and in a noun with singular form. Database table name. For example if you store product name. Database table is a basic element of the database. Beside those components above you can have another additions for each column such as the column is mandatory or not (NULL or not NULL). . Therefore if a record in a table is deleted. such as 255 characters.blob…you can refer it in the specific RDBMS. you’ve learned how to use SQL DELETE statement to delete one or more records in a database table. 04 SupplierID int(11) DEFAULT NULL. In this tutorial. If a column is unique and not null it can be a primary key of the table. bigint). you will learn how to use SQL CREATE TABLE statement to create database table. Data type for each column: Choose the correct data type for column is very important in the design phrase. 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 ). 4. Column_name2 data_type(data_length ). date. For example products is the name of a table which stores product data. You’ve also learned about referential integrity constraints between tables to allow you to delete records in linked table automatically by deleting record in other table. default value of the column and value of the column is unique or not. SQL CREATE TABLE In this tutorial. time datetime. The most common data types are text (varchar. 03 ProductName varchar(40) NOT NULL. 05 CategoryID int(11) DEFAULT NULL.Almost RDBMS allows you to create a constraint called referential integrity between two linked tables. nvarchar).. Here is an example of creating products table: 01 CREATE TABLE products ( 02 ProductID int(11) NOT NULL AUTO_INCREMENT. SQL provides CREATE TABLE statement to allow you to do so. Therefore in this case you just only have to execute the first DELETE query to make the data to be integrity. ) There are four components you need to specify when creating a database table: 1. 2. It is suggested that the name should be meaningful and in plural form of a noun. Before storing data in a table you have to create it. are deleted also.

SQL ALTER TABLE In this tutorial. you can alter it by using SQL ALTER TABLE or removing it using SQL DROP TABLE. Modify of maximum length of a column. UnitPrice decimal(19. Once table is created. PRIMARY KEY keyword is used to specify the primary key of the 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. SQL provides you ALTER TABLE statement to allow you to do so. There are also other columns used to describe a product of the products table with different data type. you will learn how to use SQL ALTER TABLE to modify database table schema. length and default value. You can not only create and remove a database table but also modify an existing database table. To add new column in a table you use the following syntax: ALTER TABLE table_name ADD COLUMN new_column datatype(datalength) 33 . Add or remove constraints of table. we've created a products table. PRIMARY KEY (ProductID) ) In the above example. Discontinued tinyint(4) NOT NULL.06 07 08 09 10 11 12 13 QuantityPerUnit varchar(20) DEFAULT NULL.4) DEFAULT NULL. Add or remove default value of a column. 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. UnitsInStock smallint(6) DEFAULT NULL. UnitsOnOrder smallint(6) DEFAULT NULL. ReorderLevel smallint(6) DEFAULT NULL.

table constraints. In the statment you specify the table name you want to remove. you’ve learnt how to modifying table by using SQL ALTER TABLE statement. indexes. In this tutorial.First you specify the table you want to add a new column and then you specify column name. 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. its data type and its maximum length of data. If you want to remove table in a different database you need to use the following syntax: 1 DROP TABLE database_name. Here is the query: ALTER TABLE products DROP COLUMN availableOnline When you drop a column. SQL DROP TABLE is used to remove the whole database table in term of table structure and data. table definition.table_name In the above syntax. The syntax of SQL DROP TABLE is as follows: 1 DROP TABLE table_name In order to remove table. 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. you'll need to have sufficient permission to do so. not only the data in the column is removed but also all the duplicated records in that table are removed also. trigger and permission spec of that table. When you use SQL DROP TABLE. 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. 34 . you will learn how to use SQL DROP TABLE statement to completely delete database table structure and data from a database. SQL DROP TABLE In this tutorial. If you drop a key column which is a part of a composite key of the table. you specify the database followed by a full stop and table name. You’ve learnt how to add or removing a column from a database table. all the data in that column is removed. the database will remove the table in the current working database. the database engine removes all objects related to that table including data.

It is safer to specify the database name when you use SQL DROP TABLE statement. 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. testing and production systems. If you just want to delete the data use SQL DELETE or SQL TRUNCATE statement instead. views and indexes. 35 . You should always find all the foreign key constraints or referencing table that reference to the table being removed. You can find the most basic SQL statements from basic SQL statement to advanced SQL Join.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. Because in the database landscape you may have different database systems and names for development. You have to asked yourself whether the table being removed is still used in the future. You can print it out and stick it to your desk. testing and development systems and potentially drop table in the production system with the thought that it is development system. If this is the case. You may confuse the production. SQL Statements Cheat Sheet SQL statements cheat sheet gives you the most common usage SQL query. Then you remove all the references first before dropping table. you'll need to execute the following query: 1 DROP TABLE tmp. you have to backup the database first before droping table. In addition you can find the SQL statements for creating database objects such as tables.employees Remarks on SQL DROP TABLE • • • • Before executing the SQL DROP TABLE you need to to consider it seriously. Sometimes you have to go to those systems at the same time to do the work.

36 . Postgresqlguide. drop one or more columns from a table. it mainly focus on SQL standard with practical examples.• • • • MySQL Tutorial MySQL tutorial site provides you useful tutorials of SQL and MySQL.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.com gives you basic guides about the PostgreSQL from the start.coderecipes. 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. ALTER TABLE Statement with SQL ALTER TABLE statement you can add. http://www. SQL Tutorial Yet another SQL tutorial website.

SQL MINUS or EXCEPT Operator SQL MINUS or EXCEPT operator work on two table expressions.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. If the second table expression includes the records which are not appear in the first table expression. 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. The result set takes records from the first table expression. 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. How to Create SQL View SQL View is a virtual table which is used to encapsulate a complex queries. SQL CASE Expression Tutorial SQL CASE expression is used as a kind of IF-THEN-ELSE statement. SQL INTERSECT Opertor Tutorial 37 . and then subtract out the ones that appear in the second table expression. these records will be ignored. 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.DROP Table Statement DROP TABLE statement allows you drop an existing table in database which is useful in some programming situations.

The duplicated records of two result sets are eliminate except theUNION ALL is used. 2006 AS year FROM cost2007 UNION SELECT * . the data type conversion will be occurred but it is very dependent-implementations.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 . and same data type (or automatically cast to each other) in all columns. SQL UNION Operator SQL UNION operator is one of the basic set operations in the relational database. In most implementations. 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 * . 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. 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.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. You can check it out your RDBMS to find out.

It is usually used in a data warehouse application in which the database models are not good nomalized. his salary and a computed column which is called salary level. 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. SQL CASE Expression A special scalar expression in SQL language is CASE expression.00 2500. SQL CASE expression is used as a kind of IF-THEN-ELSE statement. The ELSE part of the case expression is optional.00 4700. the CASE expression will return NULL. It is more intuitive to demonstrate CASE expression through an example. 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 . 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 .00 3000. 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. Here is the sql query: 1 SELECT name. If the ELSE part is omitted and all the conditions in the WHEN does not meet. The case expression can be used in anywhere scalar expressions are allowed. It is similar to switch statement in modern programming language such as Java or C#.00 We can use the CASE expression to print out the employee name.00 2800... including in WHERE and HAVING clause of the select statement.salary.3 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.00 2700.

And the output is : 1 2 3 4 5 6 7 8 name -------newcomer mary Tom anna jack foo salary ------2000.00 3000. 40 . 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). Unlike the UNION operator. And greater than 3000.00 2700. INTERSECT operator.00 salary_level -----------low average average average average high SQL MINUS or EXCEPT Operator SQL MINUS or EXCEPT operator work on two table expressions. removes all duplicated row from the result sets. these records will be ignored. SQL MINUS or EXCEPT is equivalent of the difference operator from set theory. greater than 2000 and less than or equal to 300. Some RDBMS uses MINUS and the other uses EXCEPT keyword. the salary level is average. 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.The logic is simple if the salary of the employee lower than 2000 the salary level is low.00 4700.00 2800. The result set takes records from the first table expression. the salary level is high (of course just for example). 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.00 2500. like UNION operator. SQL MINUS or EXCEPT operator is one of the set operators. If the second table expression includes the records which are not appear in the first table expression. and then subtract out the ones that appear in the second table expression. 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. INTERSECT operator operates as AND operator on tables expression.

00 We can find employee who work in department id 1 and two and have salary greater than 2500$ by using INTERSECT operator.x).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. one or more than one parameters.00 4700.00 2700.00 2000. including MySQL (version < 5. This is an example of using INTERSECT operator. Getting Started with Stored Procedure You will learn how to write the first stored procedure and how to call it.00 2800. does not support INTERSECT operator. 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.00 2700. 41 .00 2800. Parameter List in Stored Procedure A stored procedure can have zero.2) INTERSECT SELECT * FROM employees WHERE salary > 2500 employee_id name department_id ----------.Be note that several RDBMS. If a stored procedure has more than one parameter. This example using the sample table in both table expressions.00 2500. 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. 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.------------1 jack 1 4 anna 1 5 Tom 2 job_id -----1 1 2 salary ------3000.

Common Usage Flow-Control in Stored Procedure There are two most common usage of flow-control which are conditional execution and loop. they are generally executed faster than uncompiled SQL statements which are sent from the client applications. One of the most advantage of stored procedure is code reusability. a stored procedure can be reused over and over again by multiple applications. Using stored procedure has several advantages : • • • • It is used to increases the performance of application because when we create stored procedures. to make it as powerful as another programming languages such as C/C++. 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. Modifying and Compiling Stored Procecdure Once a store procedure is resided in the database server catalog. In addition. the stored procedure can contains any SQL statement like INSERT.. a stored procedure also supports procedure statements such as IF ELSE. You can follow this tutorial to understand more about stored procedure. A stored procedure is resided in the catalog of the database server so we can call it from a trigger. Stored procedures can be used for database security purpose because each store procedure can have its own database privileges. Once created. WHILE. UPDATE and DELETE or any SQL data definition like CREATE TABLE. As the definition above. Start learning how to write a stored procedure by following the tutorial getting started with stored procedure Getting Started with Stored Procedure 42 . they are compiled and stored in database catalog.. Later when client applications call them. you can also use MySQL with a change a little bit because of specification of each database server is different. another stored procedure or even from client appliations. C# and Java. 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. It is the best to illustrate the ability of stored procedure by showing examples.Local Variables in Stored Procedure Local variables are used in stored procedure to keep temporary intermediate results. We will use Microsoft SQL Server to demonstrate stored procedure. ALTER TABLE and etc.

the name of stored procedure must be unique. Microsoft SQL Server requires prefix @ for every parameters and variables of stored procedure. The CREATE PROCEDURE is similar to CREATE TABLE or INDEX statement. the database server will store the stored procedure name and code in its catalog for reusing later by another stored procedure or programs. Followed each parameter is its type. The CREATE PROCEDURE will force the database server add the stored procedure to the its catalog.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. It deletes employee by employee identity. The name of stored procedure is followed after the CREATE PROCEDURE statement. Calling a stored procedure We can call a stored procedure from the console window. In almost relation database product. The main part of a stored procedure is the stored procedure body. In this example the body is very simple. its type is integer (INT). in this case. from another stored procedure or from a program which can access database server. for example each stored procedure should begin with "sp". The second part of the stored procedure is parameter list. 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. It would be the best that the name is meaningful and follows by the naming convention of the database server specification. After the EXEC statement is the stored procedure name followed by parameter list. 8 END A stored procedure must contains at least three parts: stored procedure name. 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 . It is actually a SQL statement. In this case the list contains only one parameter @EmployeeId (the employee identity). It starts with keywords BEGIN and ends with keyword END. in this case it is Delete_Employee. When all syntax statements inside body are correct. parameter list and its body.

we pass the employee identity to the storprocedure and delete the employee based on it. In Microsoft SQL Server 2005/20008. Parameter List in Stored Procedure A stored procedure can have zero. 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. it allows you to specify the default value of the parameter. As you guess IN is abbreviation of input. OUT is abbreviation of output and INOUT is combined of both. A parameter can be described by three parts : name. this is a big plus because you can call a stored procedure without passing parameters. If a stored procedure has more than one parameter. Output parameter allows you get the value back from the stored procedure. one or more than one parameters. 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. 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 . Following the name is the parameter data type. It will use default values. Next you will learn how to use parameter list to pass and get data in and out of stored procedures parameter list in stored procedure. The data type of the stored procedure can be any valid data type which are predefined in the database server. 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. With input parameter you can pass the value to the stored procedure. The first two pars are mandatory and the third part is optional. This part is optional. data type and its type which can by IN. Here is syntax of default value of parameter. OUT and INOUT. the values of them can be passed to it and separated by a comma. In the following tutorials. The INOUT parameter type as its name suggested can act as both types of parameter. As in the previous tutorial example. There are three parameter types: IN. In some SQL database sever product. 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. 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.If a stored procedure has more than one parameters. OUT or INOUT. each one must be separated by a comma. As you see writing and calling a stored procedure is very simple and easy. by default it is the IN.

. 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. <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 .. SQL stored procedure parameter list is simple and easy to grasp? let's move to the body part of the stored procedure. Inside the body. Beside that. you can declare local variables and use them inside the stored procedure. }. 8 END When you call it without passing parameter value. WHILE. it will delete the employee with the identity is zero. you can also use procedure statement like IF. 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> .3 AS 4 5 BEGIN 6 DELETE FROM Employees 7 WHERE EmployeeId = @EmployeeId. you can put the declarative SQL statements or procedure call like calling other stored procedures.

Labeling the block has its own advantages.create temporary table to store paged data CREATE TABLE #ALLROW( RowID INT PRIMAY KEY IDENTITY(1.<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.pagesize @CurrentPage int = 1. Name.declare local variables for pagination DECLARE @UpperBand INT. Imagine we have employee table. For example. EmployeeId INT. 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.1)* @PageSize SET @UpperBand = @CurrentPage* @PageSize + 1 -. 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.assign itemcount output parameter SET @ItemCount = ( SELECT COUNT(employeeId) FROM employees ) -. Here is stored procedure to make it possible: CREATE PROCEDURE GetEmployeePaged @PageSize int = 10. Name VARCHAR(255).current page no @ItemCount int output -.-.2) ) -.insert data into the temporary table INSERT INTO #ALLROW SELECT EmployeeId. You can have one or more blocks. @LowerBand INT SET @LowerBand = (@CurrentPage . Let's get your hand with some source code to demonstrate the stored procedure body.-. each block can be nested each other.total employee found AS BEGIN -. salary DECIMAL(7.1). it makes your code more clean when you have mutilple blocks. salary FROM employees -.get paged data SELECT * FROM #ALLROW WHERE RowID > @LowerBand AND RowID < @UpperBand 46 .

<variable> }. @currentpage specifies the current page number and @itemcount specifies total record found. Next tutorial: Local variables in stored procedure Local Variables in Stored Procedures Local variables are used in stored procedure to keep temporary intermediate results. 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. 47 . ] DECLARE keywords is used to declare local variables. Finally we create a temporary table to store the data. Then we use SET statement to assign output parameter @itemcount to the total records of the employee. you can leverage it to deal with tough situation in database developement.END First in parameter list we have three parameters and their meanings are exactly what they are. Local variable has its own scope. 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. If supported. we can specify the default value for local variable.1. Inside each code block local variable only visible it the block it declared. 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> [ { .. including scalar subqueries.. @pagesize specifies number of record per page.@itemcount) The next we declare two local variables. As you can see the stored procedure is very flexible. insert the data into the temporary table and retrieve the needed records. These variables are used inside the stored procedure for determining the start row and end row we will retrive the records. So we can get the employee record in the page 1 with 10 record per page by calling: 1 EXEC GetEmployeePaged(10. These variables' values are calculated based on the @pagesize and @currentpage. It does not exist when the stored procedure finish. The expression for the default value of local variables are not limited to literals (like 'name' or 1) but may consist of compound expressions.

. CASE statement evaluates a list of boolean expression and returns one of multiple possible result expressions. You can refer to the example in stored procedure body tutorial. Common Usage Flow-Control in Stored Procedure In this section.The ELSE part is optional in thestatement. @m INT OUTPUT AS BEGIN IF @v1 > @v2 SET @m = @v1 ELSE SET @m = @v2 END In complex cases. if the value is True it execute the block code that follows it otherwise it will execute the block code that follows by ELSE. <local variable definition> }.------- 48 . Here is an stored procedure which finds the maximum value between two integers using IFTHEN-ELSE statement. Conditional execution with IF-THEN-ELSE and CASE statement The IF-THEN-ELSE statement is used to evaluate the value of boolean expression. Here is the syntax : 1 <set statement> ::= 2 SET <local variable definition> 3 [ {. we will cover all basic flow-control statements which can be used in stored procedures. we will show you how to use flow-control statements in stored procedure. 01 02 03 04 05 06 07 08 09 10 11 CREATE PROCEDURE FindMax @v1 INT.. CASE statement is similar to the swith-case statement in other programming languages such as C/C++.In the next tutorial. @v2 INT.The SET statement can be used to assign value to local variable. We have employee table data as follows: 1 employee_id 2 ----------name salary -------. ] 4 5 <local variable definition> ::= 6 <local variable> { = | := } <scalar expression> We can use SET statement to assign value or expression to local variable. Here is an example of using CASE statement to display salary level of employee. The example is easy just for demonstration. There are two most common usage of flow-control which are conditional execution and loop. C# or Java. we can use CASE statement instead of IF-THEN-ELSE statement. Local variable is intermedia storage to store temporary result in stored procedure.

1 END END 49 . Using loop will cause the performance of the server but in some cases it is necessary to use this feature.00 4700. 01 02 03 04 05 06 07 08 09 10 11 12 13 CREATE PROCEDURE Cal_Factorial @inyN INT. 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.00 2700.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.00 2000. @intFactorial BIGINT OUTPUT AS BEGIN SET @intFactorial = 1 WHILE @inyN > 1 BEGIN SET @intFactorial = @intFactorial * @inyN SET @inyN = @inyN . Here we will you an example of using WHILE loop statement to calculate the factorial of an integer number.00 2500.salary.00 2800.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.3 4 5 6 7 8 1 2 3 4 5 6 jack mary newcomer anna Tom foo 3000.

view. 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.we can specify which is the best to use WITH RECOMPILE. Stored procedure is compiled before it executes. 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 -. 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. be noted that some database products have a feature that allows you to remove the dependency database objects like table. the compiler is called and compile the stored procedure again.stored procedure body here END To remove a stored procedure from database catalog. we can use DROP PROCEDURE. Each database server has its own compiling strategy.In the real world database programming you will need to use the conditional statements to write own your stored procedures. index or other stored procedures also. 50 . 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. Therefore for each stored procedure .stored procedure body here 6 END The WITH RECOMPILE statement guarantees that each time the stored procedure is invoked. we can modify it by using the ALTER PROCEDURE statement as follows: 1 2 3 4 5 ALTER PROCEDURE spName(parameter_list) AS BEGIN -. But be noted that the compilation process takes time and also decreases the performance of the database server. 1 DROP PROCEDURE spName When you remove stored procedure.

.00 2500.00 2800.00 2700. » 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. 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.with clear explanations and source code examples SQL String Functions SQL string functions allow you to manipulate character data effectively.. RANDOM.00 4700. POWER.SQL Mathematical Functions SQL mathematical functions are very important to all programming languages and also to SQL.00 2000. 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. Here we cover all common SQL mathematical functions such as ABS. SQL COUNT Function The SQL COUNT() function used to count number of record of each database table.00 51 . SQRT.

00 SQL COUNT Function The SQL COUNT function is used to count a number of records of each database table. The syntax is simple as follows: 1 AVG ([DISTINCT]|[ALL] <numeric expression="">) For example.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 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. the following query could be used to calculate the average salary of all employees in employees table: 52 .00 4700.00 2500.00 2800. 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.To find the highest and lowest salary of employees in the list.00 2000.00 2700.

SQL ABS Function SQL ABS function returns the absolute value of an numeric input argument. SQL RAND Function The SQL RAND() function is used to generate some random numbers at run time.00 mary 2500.00 newcomer 2000. SQL CEIL roundup to the nearest integer value while FLOOR round down to the next least integer value.------jack 3000. 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 -------.1 SELECT AVG(salary) average_salary 2 FROM employees 1 average_salary 2 -------------3 2950.00 In order to calculate the total amount of salary the company has to pay each month for all employees. 53 .00 SQL Mathematical Functions SQL CEIL() (or CEILING) and FLOOR() Functions Both SQL CEIL(or CEILING) and FLOOR functions are round the numbers.000000 SQL MAX and MIN Functions The SQL SUM() function uses to sum the values.00 foo 4700.00 Tom 2700.00 anna 2800. 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.

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. SQL SQRT function accepts only positive arguments. 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. 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. drop the tables. 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. 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. Triggers are a kind of stored procedure which are invoked automatically by database server when predefined events occurred. Trigger is a kind of stored procedure means it can contains declarative or procedural SQL statements except one thing it cannot be invoked 54 . Events here can be altering the tables.Here are some common SQL trigonometric functions you need to know in your daily SQL programming.718281828459). adding or removing rows on a table. and returns an error when a negative argument is passed in.

you will learn to use required steps to work with cursor. Because of this feature. But in some database management contexts. the way we work with cursors are following this fashion: 1. Database Cursor Introducing to Database Cursor In some database management contexts. Using Transact-SQL Cursor Syntax In this section. we need to traverse through a set or records. Triggers can be used to provide transparent logging service to log data changes and then send notification to the database administrator. triggers are usually consider as events in the database. The triggers can put the burden of interdependency on the database and also burden of maintenance. Even though. There are many types of cursors are implemented in various RDBMS products using different syntax. And triggers can be used to enforce complex security authorization context. So it is easier to demonstrate trigger in a specified database server. Triggers can be used to generate and maintain derived data in derived column such as computed column. This is the reason why database cursors has invented. Introducing to Database Cursor SQL was designed to work with a set of data and SELECT statement is the most important statement. move to next record and loop until the final record is reached. process each record. Triggers are useful for use in the database but it is suggested that it should be used only when necessary. Triggers was added to SQL3 standard but different database servers implement trigger in different ways. move to next record and loop until the final record is reached. We have to define a cursor with and set its features 2. 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. process each record. we need to traverse through a set or records. Then we must populate a set of records to use with the cursor 55 . This is the reason why database cursors has invented. Triggers can be applied in some contexts : • • • • • Triggers can helps database administrator gather statistic data on table access. 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.. Triggers can be used to enforce data integrity when the business rule of data is too complex and prevent invalid transaction.explicitly by user or other stored procedures. It only can be invoked when a predefined event occurred.

. Let's move to the section which we will show you how to use Transact-SQL cursors. Finally we have to close and release the cursor resources.3. . Let's move to the an example how to use cursor. In this tutorial.. 56 .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. Data from one or more current records is fetched. then we can make some modification on it. we will use Transact-SQL cursors for demonstration. . 5. functions or triggers.. We must set the position for cursor to a record or set of records that we need to traverse through 4. 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[. Transact-SQL cursor can be used from stored procedure. We also provide you resources if you work with other RDBMS such as MySQL. 1 DECLARE cursor_name CURSOR 2 FOR select_statement • Populate the cursor with Open 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. Using Transact-SQL Cursor Syntax In order to using Transact-SQL cursors. Oracle. Loop the step 3 and 4 until the cursor reaches the final record in the set of record 6. you have to perform the following steps:  Create a cursor with declare cursor statement based on a SELECT statement.

57 .

Sign up to vote on this title
UsefulNot useful