Quick Search:
CODE
Oracle PL/SQL Code Library
JOBS
Find Or Post Oracle Jobs
FORUM
Oracle Discussion & Chat
 Oracle PL/SQL: Self-join example and syntax Jump to:  
Category: >> Oracle PL/SQL >> Self-join example and syntax Bookmark and Share

<< lastnext >>

Snippet Name: Self-join example and syntax

Description: A self-join is a way of joining a table to itself.

The example show could be the result of a query written to find all pairings of two employees in the same country, where all of the employee information is contained within a single large table.

Also see:
» ANSI Joins: FULL JOIN
» ANSI Joins: OUTER JOIN
» ANSI Joins: CROSS JOIN
» ANSI Joins: INNER JOIN
» FULL JOIN example and syntax
» RIGHT JOIN example and syntax
» LEFT JOIN example and syntax
» INNER JOIN example and syntax

Comment: (none)

Language: PL/SQL
Highlight Mode: PHP
Last Modified: March 07th, 2009

SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country
FROM Employee F, Employee S
WHERE F.Country = S.Country
AND F.EmployeeID < S.EmployeeID
ORDER BY F.EmployeeID, S.EmployeeID;
 
-- FOR this example, note that:
-- F and S are aliases FOR the first and second copies of the 
-- employee table.
 
-- The condition F.Country = S.Country excludes pairings between 
-- employees in different countries. The example question only 
-- wanted pairs of employees in the same country.
 
-- The condition F.EmployeeID < S.EmployeeID excludes pairings 
-- where the EmployeeIDs are the same.
 
-- F.EmployeeID < S.EmployeeID also excludes duplicate pairings.
 
 
-- The effect of outer joins can also be obtained using 
-- correlated subqueries. FOR example:
 
SELECT employee.LastName, employee.DepartmentID, department.DepartmentName 
FROM   employee LEFT OUTER JOIN department 
          ON employee.DepartmentID = department.DepartmentID
 
 
-- this can also be written AS:
 
SELECT employee.LastName, employee.DepartmentID,
  (SELECT department.DepartmentName 
    FROM department
   WHERE employee.DepartmentID = department.DepartmentID )
FROM   employee
 


Free
Oracle Magazine
Subscriptions
and Oracle White Papers


SQL University.net courses meet the most demanding needs of the business world for advanced education in a cost-effective manner. SQL University.net courses are available immediately for IT professionals and can be taken without disruption of your workplace schedule or processes.

Compared to traditional travel-based training, SQL University.net saves time and valuable corporate resources, allowing companies to do more with less. That's our mission, and that's what we deliver.

Click here to find out more
 
Home      :      Code Library      :      Sponsors      :      Privacy      :      Terms of Use      :      Contact Us 177 users online    © 2009 psoug.org

PSOUG LOGIN
Username: 
Password: 
Forgot your password?