SQL P
SQL P
By: Suresh Dasari Dec 10, 2011 Categories: General , SQL Joins , SQL Server Introduction: In this post I will explain what are the Joins in SQL Server and different types of Joins example (SQL LEFT outer Join, SQL RIGHT outer Join, SQL FULL outer Join, SQL Cross Join, SQL inner Join sample, Self Join example) and uses of Joins in SQL Server. Description: In SQL joins are used to get data from two or more tables based on relationship between some of the columns in tables. In most of the cases we will use primary key of first table and foreign key of secondary table to get data from tables by using this relationship we can reduce the duplication of data in every table. Before enter into Joins concept first design two tables in database and enter data like as shown below Create one table with primary key and give name as UserDetails UserID UserName FirstName LastName 1 SureshDasari Suresh Dasari 2 PrasanthiDonthi Prasanthi Donthi 3 MaheshDasari Mahesh Dasari Here UserID is the Primary key in UserDetails table After that create another table with Foreign Key and give name as OrderDetails OrderID OrderNo UserID 1 543224 1 2 213424 2 3 977776 3 4 323233 3 5 998756 1 Here OrderID is the Primary key and UserID is the foreign key in OrderDetails table. SQL contains different types of Joins we will see each concept with example by using above tables. Types of Joins 1) Inner Joins 2) Outer Joins 3) Self Join Inner Join The join that displays only the rows that have a match in both the joined tables is known as inner join. This is default join in the query and view Designer. Syntax for Inner Join SELECT t1.column_name,t2.column_name FROM table_name1 t1 INNER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for inner join Example SELECT u.UserName,u.LastName,o.OrderNo FROM UserDetails u
INNER JOIN OrderDetails o ON u.UserID=o.UserID Once we run that query our output will be like this UserName LastName SureshDasari Dasari PrasanthiDonthi Donthi MaheshDasari Dasari MaheshDasari Dasari SureshDasari Dasari We can write our inner join query like this also it will give same result SELECT u.UserName,u.LastName,o.OrderNo FROM UserDetails u JOIN OrderDetails o ON u.UserID=o.UserID Based on above result we can say that INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in "UserDetails" that do not have matches in "OrderDetails", those rows will NOT be listed. In inner Join we are having different types of Joins those are 1) Equi Join 2) Natural Join 3) Cross Join Equi Join The Equi join is used to display all the matched records from the joined tables and also display redundant values. In this join we need to use * sign to join the table. Syntax for Equi Join SELECT * FROM table_name1 t1 INNER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for Equi join Example SELECT * FROM UserDetails u INNER JOIN OrderDetails o ON u.UserID=o.UserID Once we run above query our output will be like this UserID UserName FirstName LastName OrderID OrderNo UserID 1 SureshDasari Suresh Dasari 1 543224 1 2 PrasanthiDonthi Prasanthi Donthi 2 213424 2 3 MaheshDasari Mahesh Dasari 3 977776 3 3 MaheshDasari Mahesh Dasari 4 323233 3 1 SureshDasari Suresh Dasari 5 998756 1 In equi join we need to use only equality comparisons in the join relation. If we use other operators such as (<,>) for our comparison condition then our Joins disqualifies for equi join. Natural Joins OrderNo 543224 213424 977776 323233 998756
The Natural join is same as our Equi join but only the difference is it will restrict to display redundant values. Syntax for Natural Join SELECT * FROM table_name1 t1 NATURAL JOIN table_name2 t2 Example SELECT * FROM UserDetails NATURAL JOIN OrderDetails Note: These NATURAL Joins wont work in our SQL Server (only supports in Oracle) it will throw syntax error. If you observe above code "NATURAL" is not highlighted, indicating that it is not recognized as a keyword. Cross Join A cross join that produces Cartesian product of the tables that involved in the join. The size of a Cartesian product is the number of the rows in first table multiplied by the number of rows in the second table. Syntax for Cross Join SELECT * FROM table_name1 CROSS JOIN table_name2 Or we can write it in another way also SELECT * FROM table_name1,table_name2 Now check the below query for Cross join Example SELECT * FROM UserDetails CROSS JOIN OrderDetails Or SELECT * FROM UserDetails, OrderDetails Once we run that query our output will be like this UserID UserName FirstName 1 SureshDasari Suresh 1 SureshDasari Suresh 1 SureshDasari Suresh 1 SureshDasari Suresh 1 SureshDasari Suresh 2 PrasanthiDonthi Prasanthi 2 PrasanthiDonthi Prasanthi 2 PrasanthiDonthi Prasanthi 2 PrasanthiDonthi Prasanthi 2 PrasanthiDonthi Prasanthi 3 MaheshDasari Mahesh 3 MaheshDasari Mahesh 3 MaheshDasari Mahesh 3 MaheshDasari Mahesh 3 MaheshDasari Mahesh Outer Joins LastName Dasari Dasari Dasari Dasari Dasari Donthi Donthi Donthi Donthi Donthi Dasari Dasari Dasari Dasari Dasari OrderID 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 OrderNo 543224 213424 977776 323233 998756 543224 213424 977776 323233 998756 543224 213424 977776 323233 998756 UserID 1 2 3 3 1 1 2 3 3 1 1 2 3 3 1
A join that return all the rows that satisfy the condition and unmatched rows in the joined table is an Outer Join. We are having three types of Outer Joins Left Outer Join The left outer join displays all the rows from the first table and matched rows from the second table. Syntax for Left Outer Join SELECT Column_List FROM table_name1 t1 LEFT OUTER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for Left Outer join Example SELECT u.UserID,u.UserName,o.OrderNo FROM UserDetails u LEFT OUTER JOIN OrderDetails o ON u.UserID=o.UserID Once we run that query our output will be like this UserID UserName OrderNo 1 SureshDasari 543224 1 SureshDasari 998756 2 PrasanthiDonthi 213424 3 MaheshDasari 977776 3 MaheshDasari 323233 Right Outer Join The right outer join displays all the rows from the second table and matched rows from the first table. Syntax for Right Outer Join SELECT Column_List FROM table_name1 t1 RIGHT OUTER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for Right Outer join Example SELECT u.UserID,u.UserName,o.OrderNo FROM UserDetails u RIGHT OUTER JOIN OrderDetails o ON u.UserID=o.UserID Once we run that query our output will be like this UserID UserName OrderNo 1 SureshDasari 543224 2 PrasanthiDonthi 213424 3 MaheshDasari 977776 3 MaheshDasari 323233 1 SureshDasari 998756 Full Outer Join Full Outer Join displays all the matching and non matching rows of both the tables. Syntax for Full Outer Join SELECT Column_List FROM table_name1 t1
FULL OUTER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for Full Outer join Example SELECT u.UserID,u.UserName,o.OrderNo FROM UserDetails u FULL OUTER JOIN OrderDetails o ON u.UserID=o.UserID Once we run that query our output will be like this UserID UserName FirstName LastName OrderID OrderNo UserID 1 SureshDasari Suresh Dasari 1 543224 1 1 SureshDasari Suresh Dasari 5 998756 1 2 PrasanthiDonthi Prasanthi Donthi 2 213424 2 3 MaheshDasari Mahesh Dasari 3 977776 3 3 MaheshDasari Mahesh Dasari 4 323233 3 Self Join Joining the table itself called self join. Self join is used to retrieve the records having some relation or similarity with other records in the same table. Here we need to use aliases for the same table to set a self join between single table and retrieve records satisfying the condition in where clause. To implement self join first design table and give a name as EmployeeDetails EmpID EmpName EmpMgrID 1 Suresh 2 2 Prasanthi 4 3 Mahesh 2 4 Sai 1 5 Nagaraju 1 6 Mahendra 3 7 Sanjay 3 Now I want to get manager names of particular employee for that we need to write query like this select e2.EmpName,e1.EmpName as 'Manager' from EmployeeDetails e1 INNER JOIN EmployeeDetails e2 on e1.EmpID=e2.EmpMgrID Here if you observe above query EmployeeDetails table joined itself using table aliases e1 and e2. After that run our query output will be like this EmpName Manger Sai Suresh Nagaraju Suresh Suresh Prasanthi Mahesh Prasanthi Mahendra Mahesh Sanjay Mahesh Prasanthi Sai
-- use of = SELECT *
FROM HumanResources.Employee E WHERE E.EmployeeID = ( SELECT EA.EmployeeID FROM HumanResources.EmployeeAddress EA WHERE EA.EmployeeID = E.EmployeeID) -- use of in SELECT * FROM HumanResources.Employee E WHERE E.EmployeeID IN ( SELECT EA.EmployeeID FROM HumanResources.EmployeeAddress EA WHERE EA.EmployeeID = E.EmployeeID) -- use of exists SELECT * FROM HumanResources.Employee E WHERE EXISTS ( SELECT EA.EmployeeID FROM HumanResources.EmployeeAddress EA WHERE EA.EmployeeID = E.EmployeeID)
Explicitly specifying the desired fields also allows us to control the order in which the fields are returned, so that if we wanted the last name to appear before the first name, we could write
This will limit the number of rows that answer the query and are fetched. In many cases, this is where most of the "action" of a query takes place. We can continue with our previous query, and limit it to only those employees living in London:
SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE City = 'London'
resulting in
If you wanted to get the opposite, the employees who do not live in London, you would write
SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE City <> 'London'
It is not necessary to test for equality; you can also use the standard equality/inequality operators that you would expect. For example, to get a list of employees who where hired on or after a given date, you would write
SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE HireDate >= '1-july-1993'
and get the resulting rows
Of course, we can write more complex conditions. The obvious way to do this is by having multiple conditions in theWHERE clause. If we want to know which employees were hired between two given dates, we could write
EmployeeID, FirstName, LastName, HireDate, City Employees (HireDate >= '1-june-1992') AND (HireDate <= '15-december-1993')
Note that SQL also has a special BETWEEN operator that checks to see if a value is between two values (including equality on both ends). This allows us to rewrite the previous query as
EmployeeID, FirstName, LastName, HireDate, City Employees HireDate BETWEEN '1-june-1992' AND '15-december-1993'
We could also use the NOT operator, to fetch those rows that are not between the specified dates:
EmployeeID, FirstName, LastName, HireDate, City Employees HireDate NOT BETWEEN '1-june-1992' AND '15-december-1993'
Let us finish this section on the WHERE clause by looking at two additional, slightly more sophisticated, comparison operators. What if we want to check if a column value is equal to more than one value? If it is only 2 values, then it is easy enough to test for each of those values, combining them with the OR operator and writing something like
SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE City = 'London' OR City = 'Seattle'
However, if there are three, four, or more values that we want to compare against, the above approach quickly becomes messy. In such cases, we can use the IN operator to test against a set of values. If we wanted to see if the City was either Seattle, Tacoma, or Redmond, we would write
SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE City IN ('Seattle', 'Tacoma', 'Redmond')
producing the results shown below.
As with the BETWEEN operator, here too we can reverse the results obtained and query for those rows where City is not in the specified list: SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE City NOT IN ('Seattle', 'Tacoma', 'Redmond') Finally, the LIKE operator allows us to perform basic pattern-matching using wildcard characters. For Microsoft SQL Server, the wildcard characters are defined as follows:
Wildcard
Description
_ (underscore)
[]
matches any single character within the specified range (e.g. [a-f]) or set (e.g. [abcdef]).
[^]
matches any single character not within the specified range (e.g. [^a-f])
WHERE FirstName LIKE '_im' finds all three-letter first names that end with 'im' (e.g. Jim, Tim). WHERE LastName LIKE '%stein' finds all employees whose last name ends with 'stein' WHERE LastName LIKE '%stein%' finds all employees whose last name includes 'stein' anywhere in the name. WHERE FirstName LIKE '[JT]im' finds three-letter first names that end with 'im' and begin with either 'J' or 'T' (that is, only Jim and Tim) WHERE LastName LIKE 'm[^c]%' finds all last names beginning with 'm' where the following (second) letter is not 'c'.
Here too, we can opt to use the NOT operator: to find all of the employees whose first name does not start with 'M' or 'A', we would write
SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE (FirstName NOT LIKE 'M%') AND (FirstName NOT LIKE 'A%')
resulting in
SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees ORDER BY City
By default, the sort order for a column is ascending (from lowest value to highest value), as shown below for the previous query:
If we want the sort order for a column to be descending, we can include the DESC keyword after the column name. The ORDER BY clause is not limited to a single column. You can include a comma-delimited list of columns to sort bythe rows will all be sorted by the first column specified and then by the next column specified. If we add the Country field to the SELECT clause and want to sort by Country and City, we would write:
SELECT EmployeeID, FirstName, LastName, HireDate, Country, City FROM Employees ORDER BY Country, City DESC
Note that to make it interesting, we have specified the sort order for the City column to be descending (from highest to lowest value). The sort order for the Country column is still ascending. We could be more explicit about this by writing
SELECT EmployeeID, FirstName, LastName, HireDate, Country, City FROM Employees ORDER BY Country ASC, City DESC
but this is not necessary and is rarely done. The results returned by this query are
It is important to note that a column does not need to be included in the list of selected (returned) columns in order to be used in the ORDER BY clause. If we don't need to see/use the Country values, but are only interested in them as the primary sorting field we could write the query as
SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees ORDER BY Country ASC, City DESC
with the results being sorted in the same order as before:
SQL Results:
day_of_order 2008-08-16 00:00:00.000
USE mydatabase; SELECT * FROM orders WHERE day_of_order = (SELECT MAX(day_of_order) FROM orders)
id customer
day_of_order
product
quantity
SQL Subquery
Syntax - Subquery SELECT Statement WHERE ColumnName [Comparison Operator] (SELECT Statement / Values) Results of one Sql query or Sql statement as the input for another Select query, Insert Into query,Insert From query, Update query and Delete query. You also can use the result of Subquery as a search condition for using in the IN( ) function or EXISTS operator. Comparison Operator such as =, >, <, >=, <=, LIKE, IN Below is example for SQL UNION
Sales($) 2500
BeautyCentury 3000
TravelYourself 2800
Table1
http://travelyourself.blogspot.com
SQL UNION ALL Statement SELECT Sales FROM TABLE1 UNION ALL SELECT Sales FROM TABLE2 Result Sales 2500 3000 2800 2900 3000 2800
SQL In:
USE mydatabase; SELECT product FROM orders WHERE customer IN ('Gerald Garner','A+Maintenance');
Results:
product Hanging Files 19" LCD Screen
Our results represent a query run to achieve a list of products sold to two of our customers. Now let's convert this query to a subquery and use this query as an input list to check the inventory table to see if we have any of these items in stock.
SQL In:
USE mydatabase; SELECT * FROM inventory WHERE product in (SELECT product FROM orders WHERE customer IN ('Gerald Garner','A+Maintenance'));
SQL Results:
id product inventory price 179.99 14.99
By specifying a sub query as our list of values we were able to take advantage of the relationship our tables have with each other and create a very dynamic query. This query saves us the time of scrolling through the entire inventory table and checking the stock of each item purchased by any of our recent customers.
sql - not in
SQL NOT IN, as you may have guessed, allows the developer toeliminate a list of specific values from the result set.
SQL Results:
product Status
SQL Results:
product Total Items
HP Printer Stapler
4 3
SQL Having:
USE mydatabase; SELECT day_of_order, product, SUM(quantity) as "Total" FROM orders GROUP BY day_of_order,product,quantity HAVING quantity > 7 ORDER BY day_of_order;
SQL Results:
day_of_order product Total
SELECT employees.Lastname, employees.Firstname, invoices.Sale, invoices.Price FROM employees INNER JOIN invoices ON employees.id = invoices.EmployeeID UNION SELECT employees2.Lastname, employees2.Firstname, invoices.Sale, invoices.Price FROM employees2 INNER JOIN invoices ON employees2.id = invoices.EmployeeID;
SQL Table:
Lastname Firstname Sale Price
HOT DOG
1.99
SELECT getdate(); -- Selects the current (server) date and time. CREATE DATABASE MyDatabase; -- Creates a database named Mydatabase; INSERT INTO orders -- Inserts data into a database table VALUES('A+Maintenance','8/16/08','Hanging Files',12);
SQL Results:
id customer day_of_order 1 Tizag 2 Tizag product quantity 4
1.ALTER TABLE orders ADD discount VARCHAR(10); 2.ALTER TABLE orders ALTER COLUMN discount DECIMAL(18,2); 3.ALTER TABLE orders DROP COLUMN discount; Create table CREATE TABLE inventory ( id INT IDENTITY(1,1) PRIMARY KEY, product VARCHAR(50) UNIQUE, quantity INT, price DECIMAL(18,2) );