P. 1
SQL

SQL

|Views: 13|Likes:
Published by Manorma Kumari

More info:

Published by: Manorma Kumari on Mar 18, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

12/22/2011

pdf

text

original

SQL Tutorial

SQL is short for Structured Query Language and is a widely used database language, providing means of data manipulation (store, retrieve, update, delete) and database creation. Almost all modern Relational Database Management Systems like MS SQL Server, Microsoft Access, MSDE, Oracle, DB2, Sybase, MySQL, Postgres and Informix use SQL as standard database language. Now a word of warning here, although all those RDBMS use SQL, they use different SQL dialects. For example MS SQL Server specific version of the SQL is called T-SQL, Oracle version of SQL is called PL/SQL, MS Access version of SQL is called JET SQL, etc. Our SQL tutorial will teach you how to use commonly used SQL commands and you will be able to apply most of the knowledge gathered from this SQL tutorial to any of the databases above.

SQL Database Table
The foundation of every Relational Database Management System is a database object called table. Every database consists of one or more tables, which store the database’s data/information. Each table has its own unique name and consists of columns and rows. The database table columns (called also table fields) have their own unique names and have a pre-defined data types. Table columns can have various attributes defining the column functionality (the column is a primary key, there is an index defined on the column, the column has certain default value, etc.). While table columns describe the data types, the table rows contain the actual data for the columns. Here is an example of a simple database table, containing customers data. The first row, listed in bold, contains the names of the table columns: Table: Customers FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John.Smith@yahoo.com goldfish@fishhere.net pb@herowndomain.org jim@supergig.co.uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 2222222 323 4554545 416 3233232 416 3238888

Now that we’ve learned what is a database table, we can continue with our sql tutorial and learn how to manipulate the data within the database tables.

SQL SELECT
The SQL SELECT statement is used to select data from a SQL database table. This is usually the very first SQL command every SQL newbie learns and this is because the SELECT SQL statement is one of the most used SQL commands. Please have a look at the general SQL SELECT syntax:

SELECT Column1, Column2, Column3, FROM Table1

The list of column names after the SQL SELECT command determines which columns you want to be returned in your result set. If you want to select all columns from a database table, you can use the following SQL statement:

SELECT * FROM Table1

When the list of columns following the SELECT SQL command is replaced with asterix (*) all table columns are returned. Word of caution here, it’s always better to explicitly specify the columns in the SELECT list, as this will improve your query performance significantly. The table name following the SQL FROM keyword (in our case Table1) tells the SQL interpreter which table to use to retrieve the data.

SQL SELECT INTO
The SQL SELECT INTO statement is used to select data from a SQL database table and to insert it to a different table at the same time. The general SQL SELECT INTO syntax looks like this:

SELECT Column1, Column2, Column3, INTO Table2

org jim@supergig.net pb@herowndomain. We will use our Customers database table to illustrate the usage of SQL DISTINCT.co.FROM Table1 The list of column names after the SQL SELECT command determines which columns will be copied. and the table name after the SQL INTO keyword specifies to which table to copy those rows. we will use the following SQL DISTINCT statement: SELECT DISTINCT LastName FROM Customers The result of the SQL DISTINCT expression above will look like this: LastName . we need the following SQL SELECT INTO statement: SELECT * INTO Customers_copy FROM Customers SQL DISTINCT The SQL DISTINCT clause is used together with the SQL SELECT keyword. to return a dataset with unique entries for certain database table column. If we want to make an exact copy of the data in our Customers table.com goldfish@fishhere.Smith@yahoo. FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John.uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 2222222 323 4554545 416 3233232 416 3238888 For example if we want to select all distinct surnames from our Customers table.

having last name 'Smith' we need to use the following SQL syntax: SELECT * FROM Customers WHERE LastName = 'Smith' The result of the SQL expression above will be the following: FirstName John James LastName Smith Smith Email John.org jim@supergig. Table: Customers FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John.Smith@yahoo.net pb@herowndomain.Smith Goldfish Brown SQL WHERE The SQL WHERE clause is used to select data conditionally. to illustrate the use of the SQL WHERE command.Smith@yahoo. We are going to use the Customers table from the previous chapter.com jim@supergig. by adding it to already existing SQL SELECT query.co.uk DOB 2/4/1968 20/10/1980 Phone 626 222-2222 416 323-8888 In this simple SQL query we used the "=" (Equal) operator in our WHERE criteria: LastName = 'Smith' But we can use any of the following comparison operators in conjunction with the SQL WHERE clause: <> (Not Equal) SELECT * FROM Customers .com goldfish@fishhere.uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 222-2222 323 455-4545 416 323-3232 416 323-8888 If we want to select all customers from our database table.co.

Check the SQL LIKE article for more details. .WHERE LastName <> 'Smith' > (Greater than) SELECT * FROM Customers WHERE DOB > '1/1/1970' >= (Greater or Equal) SELECT * FROM Customers WHERE DOB >= '1/1/1970' < (Less than) SELECT * FROM Customers WHERE DOB < '1/1/1970' <= (Less or Equal) SELECT * FROM Customers WHERE DOB =< '1/1/1970' LIKE (similar to) SELECT * FROM Customers WHERE Phone LIKE '626%' Note the LIKE syntax is different with the different RDBMS (SQL Server syntax used above).

uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 222-2222 323 455-4545 416 323-3232 416 323-8888 The SQL LIKE clause is very useful when you want to specify a search condition within your SQL WHERE clause.Smith@yahoo.uk DOB 2/4/1968 20/10/1980 Phone 626 222-2222 416 323-8888 If you want to select all Customers with phone numbers starting with '416' you will use this SQL expression: SELECT * FROM Customers WHERE Phone LIKE '416%' .org jim@supergig.co.co.com jim@supergig.net pb@herowndomain. For example if you want to select all customers having FirstName starting with 'J' you need to use the following SQL statement: SELECT * FROM Customers WHERE FirstName LIKE 'J%' Here is the result of the SQL statement above: FirstName John James LastName Smith Smith Email John.com goldfish@fishhere. based on a part of a column contents.Smith@yahoo.Between (Defines a range) SELECT * FROM Customers WHERE DOB BETWEEN '1/1/1970' AND '1/1/1975' SQL LIKE We will use the Customers table to illustrate the SQL LIKE clause usage: FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John.

co. for example '%' is a wildcard character for MS SQL Server representing any string. specifies both the columns and the values to be inserted in them: . Note that different databases use different characters as wildcard characters.org jim@supergig. You can put the wildcard anywhere in the string following the SQL LIKE clause and you can put as many wildcards as you like too. The first syntax form of the INSERT INTO SQL clause doesn't specify the column names where the data will be inserted.com pb@herowndomain. and '*' is the corresponding wildcard character used in MS Access.Smith@yahoo.uk DOB 2/4/1968 5/24/1978 20/10/1980 Phone 626 222-2222 416 323-3232 416 323-8888 SQL INSERT INTO The SQL INSERT INTO syntax has 2 main forms and the result of either of them is adding a new row into the database table. Another wildcard character is '_' representing any single character.The '%' is a so called wildcard character and represents any string in our pattern. Have a look at the following SQL statement: SELECT * FROM Customers WHERE Phone LIKE '[4-6]_6%' This SQL expression will return all customers satisfying the following conditions: • • • • The Phone column starts with a digit between 4 and 6 ([4-6]) Second character in the Phone column can be anything (_) The third character in the Phone column is 6 (6) The remainder of the Phone column can be any character string (%) Here is the result of this SQL expression: FirstName John Paula James LastName Smith Brown Smith Email John. value3…) The second form of the SQL INSERT INTO command. value2. The '[]' specifies a range of characters. but just their values: INSERT INTO Table1 VALUES (value1.

'626 888-8888') INSERT INTO Customers (FirstName.hunt@tgmail. '1/1/1974'. where we insert a single row by specifying its values for all columns. 'Hunt') INSERT INTO SELECT Another type of INSERT INTO allows us to insert multiple rows into a table. Phone) VALUES ('Peter'.hunt@tgmail. If we want to insert a new row into our Customers table. Unlike the previous example.net'. Value2. 'peter. you’ll have to use the second syntax form of the SQL INSERT INTO clause. 'Hunt'.com goldfish@fishhere. because the first form will produce an error if you haven’t supplied values for all columns. 'Hunt'.uk peter.hunt@tgmail.co.Smith@yahoo.net DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 1/1/1974 Phone 626 222-2222 323 455-4545 416 323-3232 416 323-8888 626 888-8888 If you want to enter data for just a few of the table columns. Email. Value3…) As you might already have guessed.org jim@supergig. LastName) VALUES ('Peter'. '626 888-8888') The result of the execution of either of the 2 INSERT INTO SQL statements will be a new row added to our Customers database table: FirstName John Steven Paula James Peter LastName Smith Goldfish Brown Smith Hunt Email John. otherwise you will get an error. Column3…) VALUES (Value1.INSERT INTO Table1 (Column1. Column2. 'peter. the number of the columns in the second INSERT INTO syntax form must match the number of values into the SQL statement. To insert only the FirstName and LastName columns. '1/1/1974'. we now use a SELECT . we are going to use one of the following 2 SQL statements: INSERT INTO Customers VALUES ('Peter'. LastName. DOB. execute the following SQL statement: INSERT INTO Customers (FirstName.net pb@herowndomain.net'.

Sales. and you already know that the source data resides in the Sales_Information table. . The entire statement can easily contain WHERE. Other relational databases will have different syntax.net pb@herowndomain.Smith@yahoo. "column4". If you are thinking whether this means that you are using information from another table. that collects the sales information for year 1998. and HAVING clauses. FROM "table2" Note that this is the simplest form. Date) SELECT store_name. GROUP BY.org jim@supergig. if we wish to have a table.. Column2 = Value2 WHERE Some_Column = Some_Value The SQL UPDATE clause changes the data in already existing database row(s) and usually we need to add a conditional SQL WHERE clause to our SQL UPDATE statement in order to specify which row(s) we intend to update.. Sql update The SQL UPDATE general syntax looks like this: UPDATE Table1 SET Column1 = Value1.'yyyy')=1998. So for example.uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 222-2222 323 455-4545 416 323-3232 416 323-8888 . you are correct. Date FROM Sales_Information WHERE Year(Date) = 1998 Here I have used the SQL Server syntax to extract the year information out of a date. Steven Goldfish's date of birth to '5/10/1974' in our Customers database table FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John. Store_Information. as well as table joins and aliases.co. "column2".statement to specify the data that we want to insert into the table. you will use to_char(date. Sales. in Oracle.com goldfish@fishhere. For example.. The syntax is as follows: INSERT INTO "table1" ("column1". we'll type in: INSERT INTO Store_Information (store_name..) SELECT "column3". . If we want to update the Mr.

co. Here comes the SQL DELETE statement! The SQL DELETE command has the following generic SQL syntax: DELETE FROM Table1 WHERE Some_Column = Some_Value . Now it’s time to learn how to remove data from a database.net pb@herowndomain. so be careful with the SQL UPDATE command usage.Smith@yahoo.com goldfish@fishhere. all customers' DOB will be updated to '5/10/1974'. by using the SQL WHERE clause in our UPDATE statement.we need the following SQL UPDATE statement: UPDATE Customers SET DOB = '5/10/1974' WHERE LastName = 'Goldfish' AND FirstName = 'Steven' If we don’t specify a WHERE clause in the SQL expression above. the Customers table will look as follows: FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John. For example if we want to change the phone number for all customers with last name Smith (we have 2 in our example Customers table). We can update several database table rows at once.uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 555-5555 323 455-4545 416 323-3232 626 555-5555 SQL DELETE So far we’ve learnt how to select data from a database table and how to insert and update data into a database table. we need to use the following SQL UPDATE statement: UPDATE Customers SET Phone = '626 555-5555' WHERE LastName = 'Smith' After the execution of the UPDATE SQL expression above.org jim@supergig.

uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 222-2222 323 455-4545 416 323-3232 416 323-8888 . The following SQL statement will delete all the data from our Customers table and we’ll end up with completely empty table: DELETE FROM Table1 If you specify a WHERE clause in your SQL DELETE statement.co.net pb@herowndomain. you will use the following statement: SELECT * FROM Customers ORDER BY DOB The result of the above SQL expression will be the following: FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John.If you skip the SQL WHERE clause when executing SQL DELETE expression.Smith@yahoo. For example if you want to select all the persons from the already familiar Customers table and order the result by date of birth.com goldfish@fishhere.org jim@supergig.org DOB 4/4/1974 5/24/1978 Phone 323 455-4545 416 323-3232 SQL ORDER BY The SQL ORDER BY clause comes in handy when you want to sort your SQL result sets by some column(s).net pb@herowndomain. then all the data in the specified table will be deleted. only the table rows satisfying the WHERE criteria will be deleted: DELETE FROM Customers WHERE LastName = 'Smith' The SQL query above will delete all database rows having LastName 'Smith' and will leave the Customers table in the following state: FirstName Steven Paula LastName Goldfish Brown Email goldfish@fishhere.

than the result set is ordered alphabetically. LastName SQL AND &OR The SQL AND clause is used when you want to specify more than one condition in your SQL WHERE clause.As you can see the rows are sorted in ascending order by the DOB column. The following SQL expression will order by DOB and LastName: SELECT * FROM Customers ORDER BY DOB. but what if you want to sort them in descending order? To do that you will have to add the DESC SQL keyword after your SQL ORDER BY clause: SELECT * FROM Customers ORDER BY DOB DESC The result of the SQL query above will look like this: FirstName James Paula Steven John LastName Smith Brown Goldfish Smith Email jim@supergig.org goldfish@fishhere. you will use the following SQL expression: .net John. For example if you want to select all customers with FirstName "John" and LastName "Smith". and at the same time you want all conditions to be true. alphabetically or reverse.uk pb@herowndomain.Smith@yahoo. hence the following to SQL expressions produce the same result: SELECT * FROM Customers ORDER BY DOB SELECT * FROM Customers ORDER BY DOB ASC You can sort your result set by more than one column by specifying those columns in the SQL ORDER BY list.co.com DOB 20/10/1980 5/24/1978 4/4/1974 2/4/1968 Phone 416 323-8888 416 323-3232 323 455-4545 626 222-2222 If you don't specify how to order your rows.

but not the first one (FirstName = 'John').org jim@supergig.uk DOB 5/24/1978 20/10/1980 Phone 416 323-3232 416 323-8888 You can combine AND and OR clauses anyway you want and you can use parentheses to define your logical expressions. selecting all customers with LastName 'Brown' and FirstName either 'James' or 'Paula': SELECT * FROM Customers WHERE (FirstName = 'James' OR FirstName = 'Paula') AND LastName = 'Brown' The result of the SQL expression above will be: . If we want to select all customers having FirstName 'James' or FirstName 'Paula' we need to use the following SQL statement: SELECT * FROM Customers WHERE FirstName = 'James' OR FirstName = 'Paula' The result of this query will be the following: FirstName Paula James LastName Brown Smith Email pb@herowndomain. Here is an example of such a SQL query.co.co.Smith@yahoo.uk DOB 20/10/1980 Phone 416 323-8888 The SQL OR statement is used in similar fashion and the major difference compared to the SQL AND is that OR clause will return all rows satisfying any of the conditions listed in the WHERE clause. and that's why it's not returned by our SQL query: FirstName James LastName Smith Email jim@supergig. satisfies the second of the conditions (LastName = 'Smith').com DOB 2/4/1968 Phone 626 222-2222 The following row in our Customer table.SELECT * FROM Customers WHERE FirstName = 'John' AND LastName = 'Smith' The result of the SQL query above is: FirstName John LastName Smith Email John.

Column3. …) Lets use the EmployeeHours table to illustrate how SQL IN works: Employee John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown Date 5/6/2004 5/6/2004 5/6/2004 5/7/2004 5/7/2004 5/7/2004 5/8/2004 5/8/2004 5/8/2004 Hours 8 8 8 9 8 10 8 8 9 Consider the following SQL query using the SQL IN clause: SELECT * FROM EmployeeHours WHERE Date IN ('5/6/2004'.org DOB 5/24/1978 Phone 416 323-3232 SQL IN The SQL IN clause allows you to specify discrete values in your SQL WHERE search criteria. THE SQL IN syntax looks like this: SELECT Column1. … FROM Table1 WHERE Column1 IN (Valu1. '5/7/2004') This SQL expression will select only the entries where the column Date has value of '5/6/2004' or '5/7/2004'.FirstName Paula LastName Brown Email pb@herowndomain. and you can see the result below: Employee John Smith Allan Babel Tina Crown John Smith Date 5/6/2004 5/6/2004 5/6/2004 5/7/2004 Hours 8 8 8 9 . Column2. Value2.

uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 222-2222 323 455-4545 416 323-3232 416 323-8888 Consider the following SQL BETWEEN statement: .net pb@herowndomain. the SQL BETWEEN gives you the ability to specify a range in your search criteria. We are going to use the familiar Customers table to show how SQL BETWEEN works: FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John.Allan Babel Tina Crown 5/7/2004 5/7/2004 8 10 We can use the SQL IN statement with another column in our EmployeeHours table: SELECT * FROM EmployeeHours WHERE Hours IN (9. … FROM Table1 WHERE Column1 BETWEEN Value1 AND Value2 The 2 values defining the range for SQL BETWEEN clause can be dates. which allows you to specify discrete values in your SQL WHERE criteria. In contrast with the SQL IN keyword. Column2. 10) The result of the SQL query above will be: Employee John Smith Tina Crown Tina Crown Date 5/7/2004 5/7/2004 5/8/2004 Hours 9 10 9 SQL BETWEEN The SQL BETWEEN & AND keywords define a range of data between 2 values. The SQL BETWEEN syntax looks like this: SELECT Column1.Smith@yahoo.org jim@supergig.com goldfish@fishhere. Column3.co. numbers or just text.

Employee FROM EmployeeHours AS Emp Here is the result of the SQL expression above: Employee John Smith .org jim@supergig. showing how to use SQL table aliases: SELECT Emp. SQL column aliases are used to make the output of your SQL queries easy to read and more meaningful: SELECT Employee.uk DOB 5/24/1978 20/10/1980 Phone 416 323-3232 416 323-8888 SQL ALIASES SQL aliases can be used with database tables and with database table columns.SELECT * FROM Customers WHERE DOB BETWEEN '1/1/1975' AND '1/1/2004' The SQL BETWEEN statement above will select all Customers having DOB column between '1/1/1975' and '1/1/2004' dates.co. depending on task you are performing. SUM(Hours) As SumHoursPerEmployee FROM EmployeeHours GROUP BY Employee In the example above we created SQL alias SumHoursPerEmployee and the result of this SQL query will be the following: Employee John Smith Allan Babel Tina Crown SumHoursPerEmployee 25 24 27 Consider the following SQL statement. Here is the result of this SQL expression: FirstName Paula James LastName Brown Smith Email pb@herowndomain.

we can select the highest date of birth with the following SQL MAX expression: . The SQL COUNT syntax is simple and looks like this: SELECT COUNT(Column1) FROM Table1 If we want to count the number of customers in our Customers table. we will use the following SQL COUNT statement: SELECT COUNT(LastName) AS NumberOfCustomers FROM Customers The result of this SQL COUNT query will be: NumberOfCustomers 4 SQL MAX The SQL MAX aggregate function allows us to select the highest (maximum) value for a certain column. The SQL MAX function syntax is very simple and it looks like this: SELECT MAX(Column1) FROM Table1 If we use the Customers table from our previous chapters.Allan Babel Tina Crown The SQL table aliases are very useful when you select data from multiple tables. SQL COUNT The SQL COUNT aggregate function is used to count the number of rows in a database table.

we will use the following SQL AVG statement: SELECT AVG(SaleAmount) AS AvgSaleAmount FROM Sales which will result in the following dataset: . we can select the lowest date of birth with the following SQL MIN expression: SELECT MIN(DOB) AS MinDOB FROM Customers SQL AVG The SQL AVG aggregate function selects the average value for certain table column.SELECT MAX(DOB) AS MaxDOB FROM Customers SQL MIN The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column. Have a look at the SQL AVG syntax: SELECT AVG(Column1) FROM Table1 If we want to find out what is the average SaleAmount in the Sales table. The SQL MIN function syntax is very simple and it looks like this: SELECT MIN(Column1) FROM Table1 If we use the Customers table from our previous chapters.

55 Consider the following SQL SUM statement: SELECT SUM(SaleAmount) FROM Sales This SQL statement will return the sum of all SaleAmount fields and the result of it will be: SaleAmount $978.67 Of course you can specify search criteria using the SQL WHERE clause in your SQL SUM statement. you will use the following SQL SUM statement: SELECT SUM(SaleAmount) FROM Sales .AvgSaleAmount $195. The SQL SUM syntax is displayed below: SELECT SUM(Column1) FROM Table1 We are going to use the Sales table to illustrate the use of SQL SUM clause: Sales: CustomerID 2 1 3 3 4 Date 5/6/2004 5/7/2004 5/7/2004 5/13/2004 5/22/2004 SaleAmount $100.95 $122.95 $100.73 SQL SUM The SQL SUM aggregate function allows selecting the total for a numeric column. If you want to select the total sales for customer with CustomerID = 3.00 $555.22 $99.

he needs to execute the following SQL statement: SELECT SUM (Hours) FROM EmployeeHours But what if the manager wants to get the sum of all hours for each of his employees? To do that he need to modify his SQL query and use the SQL GROUP BY statement: SELECT Employee.WHERE CustomerID = 3 The result will be: SaleAmount $222. SUM (Hours) . Consider the following database table called EmployeeHours storing the daily hours for each employee of a factious company: Employee John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown Date 5/6/2004 5/6/2004 5/6/2004 5/7/2004 5/7/2004 5/7/2004 5/8/2004 5/8/2004 5/8/2004 Hours 8 8 8 9 8 10 8 8 9 If the manager of the company wants to get the simple sum of all hours worked by all employees. The best way to explain how and when to use the SQL GROUP BY statement is by example. and that’s what we are going to do.95 SQL GROUP BY The SQL GROUP BY statement is used along with the SQL aggregate functions like SUM to provide means of grouping the result dataset by certain database table column(s).

FROM EmployeeHours GROUP BY Employee The result of the SQL expression above will be the following: Employee John Smith Allan Babel Tina Crown Hours 25 24 27 As you can see we have only one entry for each employee. The SQL GROUP BY clause can be used with other SQL aggregate functions. SUM(Hours) FROM EmployeeHours GROUP BY Date Here is the result of the above SQL expression: Date 5/6/2004 5/7/2004 5/8/2004 Hours 24 27 25 . because we are grouping by the Employee column. AVG(Hours) FROM EmployeeHours GROUP BY Employee The result of the SQL statement above will be: Employee John Smith Allan Babel Tina Crown Hours 8. to find out what is the total number of hours worked on each of the dates into the table: SELECT Date. for example SQL AVG: SELECT Employee.33 8 9 In our Employee table we can group by the date column too.

by a SQL aggregate function used in your SELECT list of columns. For example the following SQL statement will generate an error: SELECT Employee. To be able to use SQL JOIN clause to extract data from 2 (or more) tables. We are going to illustrate our SQL JOIN example with the following 2 tables: Customers: . SUM (Hours) FROM EmployeeHours WHERE SUM (Hours) > 24 GROUP BY Employee The SQL HAVING clause is used to do exactly this. we need a relationship between certain columns in these tables. to specify a condition for an aggregate function which is used in your query: SELECT Employee. The result of the SQL HAVING clause can be seen below: Employee John Smith Tina Crown Hours 25 27 SQL JOINS The SQL JOIN clause is used whenever we have to select data from 2 or more tables. You can't specify criteria in a SQL WHERE clause against a column in the SELECT list for which SQL aggregate function is used.SQL HAVING The SQL HAVING clause is used to restrict conditionally the output of a SQL statement. SUM (Hours) FROM EmployeeHours GROUP BY Employee HAVING SUM (Hours) > 24 The above SQL statement will select all employees and the sum of their respective hours. as long as this sum is greater than 24.

22 $222. The SQL JOIN condition has been specified after the SQL WHERE clause and says that the 2 tables have to be matched by their respective CustomerID columns.LastName.95 $100.CustomerID GROUP BY Customers.95 $100.org 5/24/1978 3233232 416 4 James Smith jim@supergig. Customers. Consider the following SQL statement: SELECT Customers.LastName The SQL expression above will select all distinct customers (their first and last names) and the total respective amount of dollars they have spent.net 4/4/1974 4554545 416 3 Paula Brown pb@herowndomain. Sales WHERE Customers.SaleAmount) AS SalesPerCustomer FROM Customers. Customers.00 $555.Smith@yahoo.55 As you can see those 2 tables have common field called CustomerID and thanks to that we can extract information from both tables by matching their CustomerID columns.uk 20/10/1980 3238888 Sales: CustomerID 2 1 3 3 4 Date 5/6/2004 5/7/2004 5/7/2004 5/13/2004 5/22/2004 SaleAmount $100.FirstName.com DOB 2/4/1968 Phone 626 2222222 323 2 Steven Goldfish goldfish@fishhere.CustomerID 1 FirstName John LastName Smith Email John. Here is the result of this SQL statement: FirstName John Steven Paula LastName Smith Goldfish Brown SalesPerCustomers $99.co.22 $99.95 .CustomerID = Sales.FirstName.95 $122. SUM(Sales.

FirstName. then INNER JOIN is used. In short "INNER JOIN" = "JOIN" (note that different databases have different syntax for their JOIN clauses).CustomerID = Sales.LastName.FirstName.22 Even though Paula and James are listed as customers in the Customers table they won't be displayed because they haven't purchased anything yet.CustomerID = Sales.SaleAmount) AS SalesPerCustomer FROM Customers JOIN Sales ON Customers. If the Sales table has the following rows: CustomerID 2 1 Date 5/6/2004 5/6/2004 SaleAmount $100. The INNER JOIN will select all rows from both tables as long as there is a match between the columns we are matching on. .CustomerID GROUP BY Customers. In case we have a customer in the Customers table.CustomerID GROUP BY Customers. Customers.55 The SQL statement above can be re-written using the SQL JOIN clause like this: SELECT Customers.95 $100. Customers.FirstName.95 And we use the same SQL JOIN statement from above: SELECT Customers. SUM(Sales. which still hasn't made any orders (there are no entries for this customer in the Sales table).LastName We'll get the following result: FirstName John Steven LastName Smith Goldfish SalesPerCustomers $99. If you don't put INNER or OUTER keywords in front of the SQL JOIN keyword. Customers. this customer will not be listed in the result of our SQL query above.FirstName. SUM(Sales. Customers.22 $99.James Smith $555.LastName.SaleAmount) AS SalesPerCustomer FROM Customers JOIN Sales ON Customers.LastName There are 2 types of SQL JOINS – INNER JOINS and OUTER JOINS.

Customers. except that it returns all rows from the second table (the right table in our SQL JOIN statement). The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword in most databases).22 NULL NULL Date 5/6/2004 5/6/2004 SaleAmount $100.22 $99. the SalesPerCustomer column has amount NULL (NULL means a column contains nothing). Customers.CustomerID GROUP BY Customers.95 $100.FirstName.LastName and the Sales table still has the following rows: CustomerID 2 1 The result will be the following: FirstName John Steven Paula James LastName Smith Goldfish Brown Smith SalesPerCustomers $99. If we slightly modify our last SQL statement to: SELECT Customers.CustomerID = Sales. no matter if they have matches in the second table. SUM(Sales.95 As you can see we have selected everything from the Customers (first table). selects all the rows from the first table listed after the FROM clause.But what if you want to display all the customers and their sales. The second type of SQL JOIN is called SQL OUTER JOIN and it has 2 sub-types called LEFT OUTER JOIN and RIGHT OUTER JOIN. For all rows from Customers. The RIGHT OUTER JOIN or just RIGHT JOIN behaves exactly as SQL LEFT JOIN.LastName. which don’t have a match in the Sales (second table). . no matter if they have ordered something or not? We’ll do that with the help of SQL OUTER JOIN clause.SaleAmount) AS SalesPerCustomer FROM Customers LEFT JOIN Sales ON Customers.FirstName.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->