database programming using sql
TRANSCRIPT
Introduction to DatabaseLab: Introduction to Oracle and SQL
(CSE 3151)
Lab - 0
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan UniversityAug 2016
Ajit K Nayak1.2Introduction to databases
Relational Model
The relational model uses a set of tables/
relations to represent data and the relationship
among those data for a specific enterprise.
Each table is arranged in a two dimensional
matrix, i.e. columns and rows.
Each column has a unique name called
fields/attributes of the relation.
Each row is a record of the relation type.
Ajit K Nayak1.4Introduction to databases
SQL
Edgar F. Codd, designed a set of rules
(Codds rule) for ideal relational database
management system.
Structured Query Language (SQL) was one of
the first commercial languages that is used
widely as a database language.
SQL adheres to some of the Codd’s rules.
SQL became a standard of ANSI in 1986, and
of the International Organization for
Standardization (ISO) in 1987.
Both the standards are identical
Ajit K Nayak1.5Introduction to databases
Oracle
Oracle Database is an object-relational
database management system developed
by Oracle Corporation.
It uses SQL as the language and complies to
the ANSI/ISO standards
SQL consists of
a data definition language(DDL),
a data manipulation language(DML),
a and Data Control Language(DCL).
The names are according to their function.
Ajit K Nayak1.6Introduction to databases
DDL
A data definition language or data
description language (DDL) provides syntax
for defining data structures, especially
database schemas.
Statements are
CREATE : to create tables etc.
DROP: to delete table
ALTER: to change an object (field, type, etc)
RENAME: to rename a table
Ajit K Nayak1.7Introduction to databases
DML
A data manipulation language (DML)
provides a family of syntax elements used to
operate on the data in table.
Statements are
SELECT : to retrieve data from table.
INSERT: to insert records into the table
UPDATE: to change data inside table
DELETE: to delete rows/records from a table
Ajit K Nayak1.8Introduction to databases
DCL
A data control language (DCL) is used to
control access to data stored in a database
(Authorization).
Statements are
GRANT : to allow specified users to perform
specified tasks.
REVOKE: to cancel previously granted or denied
permissions.
Ajit K Nayak1.9Introduction to databases
Datatypes - MinimalData type Description
CHARACTER(n) Character string. Fixed-length n
VARCHAR(n) Character string. Variable length. Maximum
length n
BOOLEAN Stores TRUE or FALSE values
INTEGER Integer numerical (no decimal).
NUMERIC(p,s) precision p, scale s. Example: numeric(5,2) is
a number that has 3 digits before the decimal
and 2 digits after the decimal
DATE Stores year, month, and day values
TIME Stores hour, minute, and second values
Ajit K Nayak1.11Introduction to databases
Create Table - I
SQL is case insensitive. However, try to follow
one case only.
To create a table we need atleast:
The table name (r)
the names of the columns (A1, A2, . . .)
Datatype of columns in order (D1, D2, D3, . . .)
Syntax
create table r (A1 D1, A2 D2, ..., An Dn);
Ajit K Nayak1.12Introduction to databases
Create Table - II
Let’s create the table as shown.
create table instructor (
ID char(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2));
instructor
Ajit K Nayak1.13Introduction to databases
Insert Records - I
To insert into a table we need:
The table name (r)
value of the columns in order (V1, V2, V3, . . .)
Syntax
insert into r values(V1, V2, ..., Vn);
Ajit K Nayak1.14Introduction to databases
Insert records - II
Let’s insert records in the table instructor.
insert into instructor values (‘10101’, ’Srinivasan’, ’Comp.Sci’, 65000);
insert into instructor values (‘12121’, ’Wu’, ’Finance’, 90000);
. . .
instructor
Ajit K Nayak1.15Introduction to databases
Retrieve data – The SELECT statement
The select statement lists the attribute values in
the result of a query
Syntax
select column(s)
from table(s)
where condition(s) (optional)
NOTE: SQL names are case insensitive (i.e., you
may use upper- or lower-case letters.)
E.g., Name ≡ NAME ≡ name
Ajit K Nayak1.16Introduction to databases
The SELECT statement -II
from and where are two clauses used with select
statements. The where clause is optional
Example
select name
from instructor
Output : Lists all the names inserted into table
instructor.Srinivasan
Wu
Mozart
Einstein
. . .
Ajit K Nayak1.17Introduction to databases
The SELECT statement -III
Example
select name
from instructor
where salary < 65000
OutputLists all the names in table instructor
having salary less than 65000.Mozart
El Said
. . .
Introduction to DatabaseLab: Basic Operations in SQL
(CSE 3151)
Lab - 2
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan UniversityAug 2016
Ajit K Nayak1.2Introduction to databases
Review
SQL is a standard for database (relational)
programming having following components
DDL
To define the relations
DML
To access or manipulate data inside relation
DCL
To provide access permissions
TCL (Transaction Control Language)
Transaction control (COMMIT, ROLLBACK,
SAVEPOINT)
Ajit K Nayak1.3Introduction to databases
Transaction Control - I
Transaction is a unit of a program execution
that accesses and possibly modifies various
data objects (reading, writing)
Some of the transaction make permanent
changes in the database but some are not.
COMMIT is used to save changes permanently
in a database manually.
DDL commands uses implicit COMMIT (auto
commit),
But DML needs explicit COMMIT. (to be issued
manually)
Ajit K Nayak1.4Introduction to databases
Transaction Control - II
Until you commit a transaction (DML):
You can see any changes you have made during
the transaction by querying the modified tables.
(local change)
But other users cannot see the changes.
After you commit the transaction, the changes are
visible to other users' statements that execute after
the commit. (global change)
You can roll back (undo) any changes made
during the transaction with the ROLLBACK
statement.
So, before leaving the lab issue: COMMIT;
Ajit K Nayak1.5Introduction to databases
UPDATE
Used to change/modify one or more records.
Conditional Update
UPDATE instructor
SET name = „Uthhapa‟
WHERE name = „Wu‟;
Update all rows
UPDATE instructor
SET name = salary = salary+100;
Ajit K Nayak1.6Introduction to databases
DELETE
To delete one or more rows
Conditional delete
DELETE FROM instructor
WHERE name = „Wu‟;
Delete all rows
DELETE FROM instructor;
Ajit K Nayak1.7Introduction to databases
The Select Statement - I The select statement may be used in following
situations
Projection: to choose one or
more columns in a table.
Selection: to choose one or
more columns in a table.
Ajit K Nayak1.8Introduction to databases
The Select Statement - II
Joining: to bring together data that is
stored in different tables by creating a
link between them.
Ajit K Nayak1.9Introduction to databases
Operations
Arithmetic Operations
+, -, *, /
Column Alias
Concatenation Operator (II)
DISTINCT operator
Comparison Operations (<, >, >=,<=, BETWEEN,
IN, LIKE, NULL)
Logical Operators (AND, OR, NOT)
Ajit K Nayak1.10Introduction to databases
Examples - I
Arithmetic
1) SELECT name, salary, salary * 0.3
FROM instructor;
Alias
2) SELECT name, salary, salary *0.3 AS diff
FROM instructor;
Concatenation (||)
3) SELECT name || „ belongs to ‟||
dept_name “Employee Dept”
FROM instructor;
Ajit K Nayak1.11Introduction to databases
Examples - II
SELECT dept_name from instructor;
Displays all the departments with duplcates
DISTINCT : Eliminates duplicate rows
4) SELECT DISTINCT dept_name
FROM instructor;
BETWEEN (Between two values inclusive)
5) SELECT name, salary
FROM instructor
WHERE salary BETWEEN 40000 AND 60000;
Ajit K Nayak1.12Introduction to databases
Examples - III
IN (set): to chose values from a list
6) SELECT name, dept_name
FROM instructor
WHERE dept_name IN (Comp.Sci, Physics);
LIKE: wildcard search
% : denotes zero or more characters
_ : denotes one character
7) SELECT name
FROM employees
WHERE name LIKE ‟E%‟;
Ajit K Nayak1.13Introduction to databases
Examples - IV
AND
8) SELECT id, name
FROM instructor
WHERE salary >= 50000
AND dept_name LIKE ‟Comp%‟;
NOT
9) SELECT name, id
FROM employees
WHERE dept_name
NOT IN (‟History‟, ‟Biology‟);
Ajit K Nayak1.14Introduction to databases
Group Functions
group functions operate on sets of rows to give
one result per group.
These sets may be the whole table or the table
split into groups.
AVG
COUNT
MAX
MIN
STDDEV
SUM
VARIANCE
Ajit K Nayak1.15Introduction to databases
Group Functions Example
SELECT AVG(salary), MAX(salary),
MIN(salary), SUM(salary)
FROM instructor;
Ajit K Nayak1.16Introduction to databases
Group Functions Example
1) SELECT AVG(salary), MAX(salary),
MIN(salary), SUM(salary)
FROM instructor;
Who is getting highest salary?
2) SELECT name, Dept, salary
FROM instructor
WHERE salary = (
SELECT MAX(salary)
FROM instructor);
Ajit K Nayak1.17Introduction to databases
Maintaining Lab Records
Use plain A4 sheet
Design a cover page stating
Reg. No, Name, Branch, Section, session, college
name, university name
Design a content page containing assignment
number, date, page no of solution
Write the question, query, output of the query
Submit for verification in next lab.
Introduction to DatabaseLab: Functions in SQL
(CSE 3151)
Lab - 3
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan UniversityAug 2016
Ajit K Nayak1.2Introduction to databases
Dual Table
If you want to have some task without using a
table…
Today’s date
Solve an arithmetic expression (3+4)
. . .
But the select command needs a table…
Oracle provides a 1x1 dummy table for these purpose
SELECT sysdate from DUAL;
SELECT 3+4 from DUAL;
SELECT * from DUAL;
SELECT 1 from DUAL;
Ajit K Nayak1.3Introduction to databases
Single row functions: character To manipulate character data
LOWER, UPPER, INITCAP, CONCAT, SUBSTR, INSTR, LENGTH,
LPAD, RPAD, TRIM, REPLACE
Examples
LOWER(’SQL Course’) output: sql course
UPPER(’SQL Course’) output: SQL COURSE
INITCAP(’SQL Course’) output: Sql Course
CONCAT(’Hello’, ’World’) output: HelloWorld
SUBSTR(’HelloWorld’,1,5) output: Hello
LENGTH(’HelloWorld’) output: 10
INSTR(’HelloWorld’, ’W’) output: 6
LPAD(salary,10,’*’) output: *****24000
RPAD(salary, 10, ’*’) output: 24000*****
TRIM(’H’ FROM ’HelloWorld’) output: elloWorld
Ajit K Nayak1.4Introduction to databases
Single row functions: Numeric
To Manipulate Numeric data
ROUND, TRUNC, MOD, ABS, ACOS, ASIN, ATAN,
ATAN2, BITAND, CEIL, COS, COSH, EXP, FLOOR, LN,
LOG , POWER, SIGN, SIN, SINH, SQRT, TAN,
TANH, TRUNC
Examples
ROUND(45.926, 2) output: ?
TRUNC(45.926, 2) output: ?
MOD(1600, 300) output: ?
ABS(-87) output: ?
CIEL(3.456) output: ?
COS(60) output: ?
POWER(2,3) output: ?
Introduction to DatabaseLab: Sorting and DDL
(CSE 3151)
Lab - 4
Ajit K Nayak, Ph.D.Siksha ‘O’ Anusandhan University
Aug 2016
Ajit K Nayak1.2Introduction to databases
Sorting rows
The clause ORDER BY is used to display sorted
outputs.
It has to be used as the last clause of any
select statement.
SELECT name, salary
FROM instructor
ORDER BY salary ASC;
ASC is default case.
DESC is used for descending order It is also possible to sort according to multiple columns
Ajit K Nayak1.3Introduction to databases
Grouping rows
The clause can’t be used to select individual
rows. Used with group functions.
The result is sorted ASC by default
Order by clause may e used with this clause.
SELECT dept_name, AVG(salary)
FROM instructor
GROUP BY dept_name;
Do not used WHERE, HAVING clause may be
used to restrict resultant groups.
HAVING AVG(salary) > 60000;
Ajit K Nayak1.4Introduction to databases
DDL Commands - I
ALTER TABLE statement can be used to:ADD a new column
MODIFY an existing column
Define a default value for the new column
DROP a column
Ajit K Nayak1.5Introduction to databases
ALTER TABLE - I
ADD a column to an existing table
ALTER TABLE instructor
ADD (doj date);Adds a new column doj at the end.
MODIFY a column datatype
ALTER TABLE instructor
MODIFY (name varchar2(30));Can modify type, size, default values of cols.
Ajit K Nayak1.6Introduction to databases
ALTER TABLE - II
MODIFY a default value
ALTER TABLE instructor
MODIFY (salary numeric(8,2) default 1000);
DROP a column
ALTER TABLE instructor
DROP COLUMN doj;
MARK UNUSED a columnALTER TABLE instructor
SET UNUSED (doj);
At a later time
ALTER TABLE instructor
DROP UNUSED COLUMNS;
Ajit K Nayak1.7Introduction to databases
DDL - II
Renaming objects
Rename a table
RENAME instructor TO faculty;
Rename a table columnALTER TABLE instructor
RENAME COLUMN dept_name TO department;
Ajit K Nayak1.8Introduction to databases
DDL - III
Truncate statement removes all the rows
from a table.
TRUNCATE TABLE instructor;
Drop statement removes rows and table
structureDROP TABLE instructor;
Introduction to DatabaseLab: Data Constraints
(CSE 3151)
Lab - 5
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan UniversityAug 2016
Ajit K Nayak5.2Introduction to databases LAB
Constraints in Oracle
Constraints enforce rules into the tables that
Can enforce rules on data when a row is inserted,
updated, or deleted. That is the constraints must be
satisfied for the operation to succeed.
Prevent the deletion of a table if there are
dependencies from other table
Constraints can be defined in either column
level or table level
Either a constraint can be defined while creating a
table (CREATE TABLE), Or it can be added at a later
time to an existing table (ALTER TABLE)
Ajit K Nayak5.3Introduction to databases LAB
Constraint Types
Constraints
I/O Constraints
Business rule Constraints
Primary Key Constraint
Foreign Key Constraint
Not NULL Constraint
Unique Constraint
CHECK Constraint
Ajit K Nayak5.4Introduction to databases LAB
Constraints - I
Constraints Description
NOT NULL Specifies that the column can’t contain a null
value
UNIQUE Specifies a column or combination of columns
whose values must be unique for all rows in the
table but allows some values to be null.
PRIMARY KEY Uniquely identifies each row of the table
(unique + not null)
FOREIGN KEY Requires values in one table to match values in
another table.
CHECK Requires a value in the database to comply
with a specified condition.
Ajit K Nayak5.5Introduction to databases LAB
Constraint Levels
Column level Constraints
Applied to the current column called inline
specification.
i.e. local to a specific column
Can’t be applied if data constraints span across
multiple columns in a table
Table level Constraints
It is applied when data constraints span across
multiple columns in a table (out-of-line specification)
Defined after defining all table columns
Stored as a part of global table definition
Ajit K Nayak5.6Introduction to databases LAB
NULL Value
NULL value
Used for a column when we do not have a value
for that column
It can be used for columns of any data type
When no value is supplied for a column, Oracle
assumes NULL value for that column (default)
It is different from blank or zero values
If the column has already a NULL value in it, then
Oracle ignores the UNIQUE, FOREIGN, and CHECK
constraints
NOT NULL constraints must be declared inline. All
other constraints can be declared either inline or
out of line.
Ajit K Nayak5.7Introduction to databases LAB
NOT NULL
If the table is not yet created
CREATE TABLE customers(
id INT NOT NULL,
name VARCHAR2(20) NOT NULL,
address VARCHAR2(25) ,
salary NUMERIC(18, 2) );
If the table is existing
ALTER TABLE CUSTOMERS
MODIFY salary NUMERIC(18, 2) NOT NULL;
Ajit K Nayak5.8Introduction to databases LAB
UNIQUE - I in-line
CREATE TABLE customers(
id INT NOT NULL,
name VARCHAR2(20) UNIQUE,
address VARCHAR2(25) ,
salary NUMERIC(18, 2) );
Out-of-line
CREATE TABLE customers(
. . .
UNIQUE (name, address) );
OR
CONSTRAINT cust_add UNIQUE(name, address)
A Name may be assigned
to the constraint
Ajit K Nayak5.9Introduction to databases LAB
UNIQUE - II
In Existing table
ALTER TABLE customers
ADD UNIQUE (address);
In Existing table (with constraint name)
ALTER TABLE customers
ADD CONSTRAINT cust_add UNIQUE(name, address);
Drop a constraint
ALTER TABLE customers
DROP CONSTRAINT cust_add;
Ajit K Nayak5.10Introduction to databases LAB
Primary Key CREATE TABLE
id INT PRIMARY KEY,
. . .
Or
PRIMARY KEY (id, name)
Or
CONSTRAINT cust_id PRIMARY KEY (id, name)
ALTER TABLE
ADD PRIMARY KEY (id, name)
DROP KEY
DROP CONSTRAINT cust_id
Ajit K Nayak5.11Introduction to databases LAB
Foreign Key - I A FOREIGN KEY in one table points to a PRIMARY KEY in
another table.
cid LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
oid OrderNo cid
1 77895 3
2 44678 3
3 22456 2
4 24562 1
“cid" column in the orders table points
to the “cid" column in the customer
table.
The “cid" column is the PRIMARY KEY
in the customer table and is a
FOREIGN KEY in the order table.
Ajit K Nayak5.12Introduction to databases LAB
Foreign Key – Create table
Column level
CREATE TABLE orders(
oid int PRIMARY KEY,
OrderNo int NOT NULL,
cid int REFERENCES customer(cid));
Table level
CREATE TABLE orders(
oid int PRIMARY KEY,
OrderNo int NOT NULL,
cid int,
CONSTRAINT fk_order FOREIGN KEY (cid)
REFERENCES customer(cid));
Ajit K Nayak5.13Introduction to databases LAB
Foreign Key – Alter table
Column level
ALTER TABLE orders
ADD FOREIGN KEY (cid)
REFERENCES customer(cid);
Table level
ALTER TABLE orders
ADD CONSTRAINT fk_order
FOREIGN KEY (cid)
REFERENCES customer(cid);
DROP
ALTER TABLE orders
DROP CONSTRAINT fk_order;
Ajit K Nayak5.14Introduction to databases LAB
After Referencing
Extract information from two tables with
referential integritySELECT lastname, address, city, orderNo
FROM customer, orders
WHERE customer.cid = order.cid;
Ajit K Nayak5.15Introduction to databases LAB
Restrictions with referential integrity
Deletion restriction
Rows containing Referenced key values in the
parent table can’t be deleted that have
dependent rows in the child table.
Method 1 (Manual/ not advised)
Delete the row from child table
Then delete from parent table
Method 2 (Automated)
Use either ON DELETE CASCADE
or ON DELETE SET NULL clauses
Then oracle will automatically delete corresponding
rows in child table along with rows of parent table
Ajit K Nayak5.16Introduction to databases LAB
Restrictions with referential integrity
Insertion restriction
A row can’t be inserted into the child table if
referenced key values are not available in the
parent table.
Method
Insert into the parent table
Then insert into child table
Ajit K Nayak5.17Introduction to databases LAB
Deleting rows with referential integrity
Example:
CREATE TABLE orders(
oid int PRIMARY KEY,
OrderNo int NOT NULL,
cid int,
CONSTRAINT fk_order FOREIGN KEY (cid)
REFERENCES customer(cid)
ON DELETE CASCADE
);
Ajit K Nayak5.18Introduction to databases LAB
CHECK constraint
Applying business rule (mob# and email id)
CREATE TABLE customer (
. . .
mobNo char(10),
eMail varchar2(50));
ALTER TABLE customer
ADD CONSTRAINT ch_mob
CHECK (mobNo LIKE
'[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]');
ALTER TABLE customer
ADD CONSTRAINT ch_mail
CHECK (eMail Like '_%@_%._%');
Introduction to DatabaseLab: Subquery
(CSE 3151)
Lab - 6
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan UniversityAug 2016
Ajit K Nayak5.2Introduction to databases LAB
Subquery? Some times you may need two queries to
solve a single problem.
Ex: Who has a salary greater than Abel’s?
Subquery: What is Abel’s Salary?
Mainquery: Which employees salaries greater than
Abel’s salary.
Syntax:SELECT <columns>
FROM <table>
WHERE <expression>
(SELECT <columns>
FROM <table>
WHERE <expression>);
Subquery/
Innerquery
Mainquery/
Outerquery
Ajit K Nayak5.3Introduction to databases LAB
Example Ex: Find the employee names getting more
salary than Abel’s.
SELECT name
FROM employee
WHERE salary >
(SELECT salary
FROM employees
WHERE name = “Abel”);
Ajit K Nayak5.4Introduction to databases LAB
Subquery Types Single-row subqueries: Queries that return only
one row from the inner SELECT statement
Use single-row comparison operators
=, >, >=, <, <=, <>
Multiple-row subqueries: Queries that return
more than one row from the inner SELECT
statement
Use multiple-row comparison operators
IN, ANY, ALL
Ajit K Nayak5.5Introduction to databases LAB
Single-row subqueries - I Display the employees name and job ID
whose job ID is the same as that of employee
141.
SELECT name, job_id
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE employee_id = 141);
Ajit K Nayak5.6Introduction to databases LAB
Single-row subqueries - II Display the employees name and job_id whose job ID
is the same as that of employee 141 and salary same
as that of employee 143.
SELECT name, job_id
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE employee_id = 141)
AND salary >
(SELECT salary
FROM employees
WHERE employee_id = 143);
Ajit K Nayak5.7Introduction to databases LAB
Single-row subqueries - III Display the employees name, job_id, salary, who are
getting min salary.
SELECT name, job_id, salary
FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees);
List the departments getting min salary greater than the dept 50
SELECT dept_id, MIN(salary)
FROM employees
GROUP BY dept_id
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE dept_id = 50);
Ajit K Nayak5.8Introduction to databases LAB
Multiple-row subqueries - I List the employees of different department getting
minimum salary.
SELECT name, salary, dept_id
FROM employees
WHERE salary IN
(SELECT MIN(salary)
FROM employees
GROUP BY dept_id);
Ajit K Nayak5.9Introduction to databases LAB
Multiple-row subqueries - II Find employees info of employees getting salary less
than any IT programmers
SELECT emp_id, name, job_id, salary
FROM employees
WHERE salary < ANY
(SELECT salary
FROM employees
WHERE job_id = ’IT_PROG’)
AND job_id <> ’IT_PROG’;
Ajit K Nayak5.10Introduction to databases LAB
Multiple-row subqueries - III Find employees info of employees salary less than all IT
programmers
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary < ALL
(SELECT salary
FROM employees
WHERE job_id = ’IT_PROG’)
AND job_id <> ’IT_PROG’;
Ajit K Nayak5.11Introduction to databases LAB
Problem with Subquery
A common problem with subqueries is
no rows being returned by the inner
query.
Introduction to DatabaseLab: Joining Tables
(CSE 3151)
Lab - 7
Ajit K Nayak, Ph.D.Siksha ‘O’ Anusandhan University
Aug 2016
Ajit K Nayak5.2Introduction to databases LAB
Joining Tables
to obtain data from more than one table using
equality and non-equality joins
Join a table to itself by using a self join
Ajit K Nayak5.4Introduction to databases LAB
Cartesian Products
A Cartesian product is formed when: A join condition is omitted
A join condition is invalid
All rows in the first table are joined to all rows in the
second table
A Cartesian product tends to generate a large
number of rows, and the result is rarely useful.
To avoid a Cartesian product, always include
a valid join condition in a WHERE clause.
Ajit K Nayak5.5Introduction to databases LAB
Cartesian Products: Example SELECT last_name, department_name dept_name
FROM employees, departments;
Ajit K Nayak5.7Introduction to databases LAB
Joining Tables: Equijoins SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
SELECT employees.employee_id, employees.last_name,
employees.department_id, departments.department_id,
departments.location_id
FROM employees, departments
WHERE employees.department_id =
departments.department_id;
Ajit K Nayak5.8Introduction to databases LAB
Additional Search Conditions SELECT last_name, employees.department_id,
department_name
FROM employees, departments
WHERE employees.department_id =
departments.department_id
AND last_name = ’Matos’;
Ajit K Nayak5.9Introduction to databases LAB
Using Table alias SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e , departments d
WHERE e.department_id = d.department_id;
Ajit K Nayak5.10Introduction to databases LAB
Joining More than Two Tables SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id
AND d.location_id = l.location_id;
Ajit K Nayak5.12Introduction to databases LAB
Self Joins Sometimes you need to join a table to itself.
Ex: To find the name of each employee’s manager,
Need to join the EMPLOYEES table to itself, or
perform a self join.
SELECT worker.last_name || ’ works for ’||
manager.last_name
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id