SQL - Joins - Views
SQL - Joins - Views
1
What is a Join?
• Use a join to query data from more than one table
• Prefix the column name with the table name or table alias when the same
column name appears in more than one table
2
Cross Join (Cartesian Product)
• All rows in the first table are joined to all rows in the second table
• To avoid a Cartesian product, always include a valid join condition in a
WHERE clause
3
Qualifying Ambiguous Column Names
• Use table prefixes or table aliases to qualify column names that are in
multiple tables
4
Inner Join
• Inner Joins are also called simple joins or natural joins
• This type of join involves primary and foreign key
• The SELECT clause specifies the column names from two or more tables to
be retrieved
• The FROM clause specifies the two tables that the database must access
• The WHERE clause specifies how the tables are to be joined
• If joined columns have different data types, an error is returned
5
INNER Join/Natural Joins (cont’d)
• SQL-89 compliant Syntax - Simple Join
SELECT customernumber, customername, employeenumber, firstname || ' ' || lastname
FROM dbs211_customers c, dbs211_employees e WHERE c.salesrepemployeenumber = e.employeenumber;
7
RIGHT OUTER JOIN (RIGHT JOIN)
• A join between two tables that returns the results of the inner join as well as
unmatched rows right tables is a right outer join.
SELECT customernumber, customername, employeenumber, firstname || ' ' || lastname
FROM dbs211_customers c
RIGHT OUTER JOIN dbs211_employees e ON c.salesrepemployeenumber = e.employeenumber;
8
FULL OUTER JOIN (FULL JOIN)
• A join between two tables that returns the results of an inner join as well as the
results of a left and right join.
SELECT customernumber, customername, employeenumber, firstname || ' ' || lastname
FROM dbs211_customers c
FULL OUTER JOIN dbs211_employees e ON c.salesrepemployeenumber = e.employeenumber;
10
Creating a View
• You embed a subquery within the CREATE VIEW statement
• You can use the OR REPLACE option to change the definition of the view
without dropping and re-creating it.
• You can retrieve data from a view as you would from any table.
• The subquery can contain an ORDER BY clause
11
Querying a View
• When you query a view, Oracle:
• Retrieves the view definition from the data dictionary
• Checks access privileges for the view base table
• Retrieves the data, or updates the base table
SELECT *
FROM customervw;
• You can query the data dictionary table called USER_VIEWS to see the
name of the view and definition
SELECT *
FROM user_views;
12
Removing a View
• DROP VIEW statement removes the view definition
• Dropping views has no effect on the tables
13
Inline Views
• An inline view is a subquery with an alias name that you can use within a SQL
statement
SELECT *
FROM (SELECT DISTINCT productvendor
FROM dbs211_products)
WHERE ROWNUM <= 10
ORDER BY productvendor;