SlideShare a Scribd company logo
Introduction to Database
Lab: Introduction to Oracle and SQL
(CSE 3151)
Lab - 0
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan University
Aug 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.3Introduction to databases
Example: Table / relation
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 - Minimal
Data 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.10Introduction to databases
Experiment Time
Let’s create, insert and retrieve
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
Output
Lists all the names in table instructor
having salary less than 65000.
Mozart
El Said
. . .
Ajit K Nayak1.18Introduction to databases
Assignment - I
Ajit K Nayak1.19Introduction to databases
End of Lab 1
Thank You
Introduction to Database
Lab: Basic Operations in SQL
(CSE 3151)
Lab - 2
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan University
Aug 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.
Ajit K Nayak1.18Introduction to databases
Task
 Execute all the queries discussed
 Solve Assignment 2
Ajit K Nayak1.19Introduction to databases
End of Lab 2
Thank You
Introduction to Database
Lab: Functions in SQL
(CSE 3151)
Lab - 3
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan University
Aug 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: ?
Ajit K Nayak1.5Introduction to databases
End of Lab 3
Thank You
Introduction to Database
Lab: 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 column
ALTER 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 column
ALTER 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
structure
DROP TABLE instructor;
Ajit K Nayak1.9Introduction to databases
End of Lab 4
Thank You
Introduction to Database
Lab: Data Constraints
(CSE 3151)
Lab - 5
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan University
Aug 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 integrity
SELECT 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 '_%@_%._%');
Ajit K Nayak5.19Introduction to databases LAB
End of Lab 5
Thank You
Introduction to Database
Lab: Subquery
(CSE 3151)
Lab - 6
Ajit K Nayak, Ph.D.
Siksha ‘O’ Anusandhan University
Aug 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.
Ajit K Nayak5.12Introduction to databases LAB
End of Lab 6
Thank You
Introduction to Database
Lab: 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.3Introduction to databases LAB
Obtaining data from multiple tables
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.6Introduction to databases LAB
Generating a Cartesian Product
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.11Introduction to databases LAB
Joining more than two tables
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
Ajit K Nayak5.13Introduction to databases LAB
Self Joins
Ajit K Nayak5.14Introduction to databases LAB
End of Lab 7
Thank You

More Related Content

What's hot (20)

Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
Md.Mojibul Hoque
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
thewebsacademy
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?
CPD INDIA
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
farwa waqar
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
1keydata
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
baabtra.com - No. 1 supplier of quality freshers
 
PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | Edureka
Edureka!
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
Bharat Kalia
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
rehaniltifat
 
database language ppt.pptx
database language ppt.pptxdatabase language ppt.pptx
database language ppt.pptx
Anusha sivakumar
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
Quang Minh Đoàn
 
Strings in c#
Strings in c#Strings in c#
Strings in c#
Dr.Neeraj Kumar Pandey
 
Creating Views - oracle database
Creating Views - oracle databaseCreating Views - oracle database
Creating Views - oracle database
Salman Memon
 
SQL Views
SQL ViewsSQL Views
SQL Views
baabtra.com - No. 1 supplier of quality freshers
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
Dhani Ahmad
 
SUBQUERIES.pptx
SUBQUERIES.pptxSUBQUERIES.pptx
SUBQUERIES.pptx
RenugadeviR5
 

Viewers also liked (20)

Omg Fundamental Certification 4
Omg Fundamental Certification 4Omg Fundamental Certification 4
Omg Fundamental Certification 4
Ricardo Quintero
 
Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3
Ricardo Quintero
 
Perfiles UML
Perfiles UMLPerfiles UML
Perfiles UML
Jose R. Hilera
 
Software Engineering :UML class diagrams
Software Engineering :UML class diagramsSoftware Engineering :UML class diagrams
Software Engineering :UML class diagrams
Ajit Nayak
 
INNOVATION IS NOT AN OPTION
INNOVATION IS NOT AN OPTIONINNOVATION IS NOT AN OPTION
INNOVATION IS NOT AN OPTION
Sebastien Juras
 
Computer Fundamentals & Intro to C Programming module i
Computer Fundamentals & Intro to C Programming module iComputer Fundamentals & Intro to C Programming module i
Computer Fundamentals & Intro to C Programming module i
Ajit Nayak
 
01 conceptos de diseño
01 conceptos de diseño01 conceptos de diseño
01 conceptos de diseño
Ricardo Quintero
 
Parallel programming using MPI
Parallel programming using MPIParallel programming using MPI
Parallel programming using MPI
Ajit Nayak
 
Psychology explains the power of Storytelling
Psychology explains the power of StorytellingPsychology explains the power of Storytelling
Psychology explains the power of Storytelling
Sebastien Juras
 
Software Engineering :Behavioral Modelling - I Sequence diagram
Software Engineering :Behavioral Modelling - I Sequence diagram Software Engineering :Behavioral Modelling - I Sequence diagram
Software Engineering :Behavioral Modelling - I Sequence diagram
Ajit Nayak
 
Software Engineering : OOAD using UML
Software Engineering : OOAD using UMLSoftware Engineering : OOAD using UML
Software Engineering : OOAD using UML
Ajit Nayak
 
Uml Omg Fundamental Certification 2
Uml Omg Fundamental Certification 2Uml Omg Fundamental Certification 2
Uml Omg Fundamental Certification 2
Ricardo Quintero
 
Software Engineering :Behavioral Modelling - II State diagram
Software Engineering :Behavioral Modelling - II State diagramSoftware Engineering :Behavioral Modelling - II State diagram
Software Engineering :Behavioral Modelling - II State diagram
Ajit Nayak
 
Is your company fully engaged towards innovation?
Is your company fully engaged towards innovation?Is your company fully engaged towards innovation?
Is your company fully engaged towards innovation?
Sebastien Juras
 
Things to know to improve your willpower
Things to know to improve your willpowerThings to know to improve your willpower
Things to know to improve your willpower
Sebastien Juras
 
Operating Systems Part III-Memory Management
Operating Systems Part III-Memory ManagementOperating Systems Part III-Memory Management
Operating Systems Part III-Memory Management
Ajit Nayak
 
03 administracion de requisitos
03 administracion de requisitos03 administracion de requisitos
03 administracion de requisitos
Ricardo Quintero
 
The Ultimate gift
The Ultimate giftThe Ultimate gift
The Ultimate gift
Sebastien Juras
 
The badguy summary
The badguy   summaryThe badguy   summary
The badguy summary
Sebastien Juras
 
Six things to know about your brain to become an expert
Six things to know about your brain to become an expertSix things to know about your brain to become an expert
Six things to know about your brain to become an expert
Sebastien Juras
 
Omg Fundamental Certification 4
Omg Fundamental Certification 4Omg Fundamental Certification 4
Omg Fundamental Certification 4
Ricardo Quintero
 
Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3Uml Omg Fundamental Certification 3
Uml Omg Fundamental Certification 3
Ricardo Quintero
 
Software Engineering :UML class diagrams
Software Engineering :UML class diagramsSoftware Engineering :UML class diagrams
Software Engineering :UML class diagrams
Ajit Nayak
 
INNOVATION IS NOT AN OPTION
INNOVATION IS NOT AN OPTIONINNOVATION IS NOT AN OPTION
INNOVATION IS NOT AN OPTION
Sebastien Juras
 
Computer Fundamentals & Intro to C Programming module i
Computer Fundamentals & Intro to C Programming module iComputer Fundamentals & Intro to C Programming module i
Computer Fundamentals & Intro to C Programming module i
Ajit Nayak
 
Parallel programming using MPI
Parallel programming using MPIParallel programming using MPI
Parallel programming using MPI
Ajit Nayak
 
Psychology explains the power of Storytelling
Psychology explains the power of StorytellingPsychology explains the power of Storytelling
Psychology explains the power of Storytelling
Sebastien Juras
 
Software Engineering :Behavioral Modelling - I Sequence diagram
Software Engineering :Behavioral Modelling - I Sequence diagram Software Engineering :Behavioral Modelling - I Sequence diagram
Software Engineering :Behavioral Modelling - I Sequence diagram
Ajit Nayak
 
Software Engineering : OOAD using UML
Software Engineering : OOAD using UMLSoftware Engineering : OOAD using UML
Software Engineering : OOAD using UML
Ajit Nayak
 
Uml Omg Fundamental Certification 2
Uml Omg Fundamental Certification 2Uml Omg Fundamental Certification 2
Uml Omg Fundamental Certification 2
Ricardo Quintero
 
Software Engineering :Behavioral Modelling - II State diagram
Software Engineering :Behavioral Modelling - II State diagramSoftware Engineering :Behavioral Modelling - II State diagram
Software Engineering :Behavioral Modelling - II State diagram
Ajit Nayak
 
Is your company fully engaged towards innovation?
Is your company fully engaged towards innovation?Is your company fully engaged towards innovation?
Is your company fully engaged towards innovation?
Sebastien Juras
 
Things to know to improve your willpower
Things to know to improve your willpowerThings to know to improve your willpower
Things to know to improve your willpower
Sebastien Juras
 
Operating Systems Part III-Memory Management
Operating Systems Part III-Memory ManagementOperating Systems Part III-Memory Management
Operating Systems Part III-Memory Management
Ajit Nayak
 
03 administracion de requisitos
03 administracion de requisitos03 administracion de requisitos
03 administracion de requisitos
Ricardo Quintero
 
Six things to know about your brain to become an expert
Six things to know about your brain to become an expertSix things to know about your brain to become an expert
Six things to know about your brain to become an expert
Sebastien Juras
 
Ad

Similar to Database Programming using SQL (20)

Oracle
OracleOracle
Oracle
Rajeev Uppala
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
Sherif Gad
 
STRUCTURED QUERY LANGUAGE
STRUCTURED QUERY LANGUAGESTRUCTURED QUERY LANGUAGE
STRUCTURED QUERY LANGUAGE
SarithaDhanapal
 
DBMS UNIT-2.pptx ggggggggggggggggggggggg
DBMS UNIT-2.pptx gggggggggggggggggggggggDBMS UNIT-2.pptx ggggggggggggggggggggggg
DBMS UNIT-2.pptx ggggggggggggggggggggggg
Praveen Kumar
 
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Neeraj Bhandari
 
SQL LECTURE.pptx
SQL LECTURE.pptxSQL LECTURE.pptx
SQL LECTURE.pptx
TechnoSavage
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
EliasPetros
 
Introduction.pptxyfdvkbvvxxmnvczsyjkmnbvhj
Introduction.pptxyfdvkbvvxxmnvczsyjkmnbvhjIntroduction.pptxyfdvkbvvxxmnvczsyjkmnbvhj
Introduction.pptxyfdvkbvvxxmnvczsyjkmnbvhj
shindepoornima94
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
EliasPetros
 
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
Rohan Byanjankar
 
Database management system unit 1 Bca 2-semester notes
Database management system  unit 1 Bca 2-semester notesDatabase management system  unit 1 Bca 2-semester notes
Database management system unit 1 Bca 2-semester notes
n32310997
 
My SQL.pptx
My SQL.pptxMy SQL.pptx
My SQL.pptx
KieveBarreto1
 
Sql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.pptSql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.ppt
DrRShaliniVISTAS
 
database in my squel assignment for students.pdf
database in my squel assignment for students.pdfdatabase in my squel assignment for students.pdf
database in my squel assignment for students.pdf
mashorialli500
 
Databases and SQL - Lecture C
Databases and SQL - Lecture CDatabases and SQL - Lecture C
Databases and SQL - Lecture C
CMDLearning
 
sql notes Provideby AGN HUB Tech & It Solutions
sql notes Provideby AGN HUB Tech & It Solutionssql notes Provideby AGN HUB Tech & It Solutions
sql notes Provideby AGN HUB Tech & It Solutions
mohanagn2244
 
225523359001djcj4_DBMS_LAB_THEORY_DML.pdf
225523359001djcj4_DBMS_LAB_THEORY_DML.pdf225523359001djcj4_DBMS_LAB_THEORY_DML.pdf
225523359001djcj4_DBMS_LAB_THEORY_DML.pdf
sahilurrahemankhan
 
Sql a practical_introduction
Sql a practical_introductionSql a practical_introduction
Sql a practical_introduction
investnow
 
rdbms parul university oracle dbms bca mca
rdbms parul university oracle dbms bca mcardbms parul university oracle dbms bca mca
rdbms parul university oracle dbms bca mca
VaibhavSrivastav52
 
Dbms sql-final
Dbms  sql-finalDbms  sql-final
Dbms sql-final
NV Chandra Sekhar Nittala
 
STRUCTURED QUERY LANGUAGE
STRUCTURED QUERY LANGUAGESTRUCTURED QUERY LANGUAGE
STRUCTURED QUERY LANGUAGE
SarithaDhanapal
 
DBMS UNIT-2.pptx ggggggggggggggggggggggg
DBMS UNIT-2.pptx gggggggggggggggggggggggDBMS UNIT-2.pptx ggggggggggggggggggggggg
DBMS UNIT-2.pptx ggggggggggggggggggggggg
Praveen Kumar
 
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Neeraj Bhandari
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
EliasPetros
 
Introduction.pptxyfdvkbvvxxmnvczsyjkmnbvhj
Introduction.pptxyfdvkbvvxxmnvczsyjkmnbvhjIntroduction.pptxyfdvkbvvxxmnvczsyjkmnbvhj
Introduction.pptxyfdvkbvvxxmnvczsyjkmnbvhj
shindepoornima94
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
EliasPetros
 
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
Rohan Byanjankar
 
Database management system unit 1 Bca 2-semester notes
Database management system  unit 1 Bca 2-semester notesDatabase management system  unit 1 Bca 2-semester notes
Database management system unit 1 Bca 2-semester notes
n32310997
 
Sql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.pptSql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.ppt
DrRShaliniVISTAS
 
database in my squel assignment for students.pdf
database in my squel assignment for students.pdfdatabase in my squel assignment for students.pdf
database in my squel assignment for students.pdf
mashorialli500
 
Databases and SQL - Lecture C
Databases and SQL - Lecture CDatabases and SQL - Lecture C
Databases and SQL - Lecture C
CMDLearning
 
sql notes Provideby AGN HUB Tech & It Solutions
sql notes Provideby AGN HUB Tech & It Solutionssql notes Provideby AGN HUB Tech & It Solutions
sql notes Provideby AGN HUB Tech & It Solutions
mohanagn2244
 
225523359001djcj4_DBMS_LAB_THEORY_DML.pdf
225523359001djcj4_DBMS_LAB_THEORY_DML.pdf225523359001djcj4_DBMS_LAB_THEORY_DML.pdf
225523359001djcj4_DBMS_LAB_THEORY_DML.pdf
sahilurrahemankhan
 
Sql a practical_introduction
Sql a practical_introductionSql a practical_introduction
Sql a practical_introduction
investnow
 
rdbms parul university oracle dbms bca mca
rdbms parul university oracle dbms bca mcardbms parul university oracle dbms bca mca
rdbms parul university oracle dbms bca mca
VaibhavSrivastav52
 
Ad

More from Ajit Nayak (20)

Software Engineering : Software testing
Software Engineering : Software testingSoftware Engineering : Software testing
Software Engineering : Software testing
Ajit Nayak
 
Software Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & SpecificationSoftware Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & Specification
Ajit Nayak
 
Software Engineering : Process Models
Software Engineering : Process ModelsSoftware Engineering : Process Models
Software Engineering : Process Models
Ajit Nayak
 
Software Engineering an Introduction
Software Engineering an IntroductionSoftware Engineering an Introduction
Software Engineering an Introduction
Ajit Nayak
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
Ajit Nayak
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
Ajit Nayak
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt III
Ajit Nayak
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
Ajit Nayak
 
Object Oriented Analysis Design using UML
Object Oriented Analysis Design using UMLObject Oriented Analysis Design using UML
Object Oriented Analysis Design using UML
Ajit Nayak
 
Operating Systems Part I-Basics
Operating Systems Part I-BasicsOperating Systems Part I-Basics
Operating Systems Part I-Basics
Ajit Nayak
 
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Operating Systems Part II-Process Scheduling, Synchronisation & DeadlockOperating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Ajit Nayak
 
Introduction to database-Transaction Concurrency and Recovery
Introduction to database-Transaction Concurrency and RecoveryIntroduction to database-Transaction Concurrency and Recovery
Introduction to database-Transaction Concurrency and Recovery
Ajit Nayak
 
Introduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculusIntroduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculus
Ajit Nayak
 
Introduction to database-Normalisation
Introduction to database-NormalisationIntroduction to database-Normalisation
Introduction to database-Normalisation
Ajit Nayak
 
Introduction to database-ER Model
Introduction to database-ER ModelIntroduction to database-ER Model
Introduction to database-ER Model
Ajit Nayak
 
Computer Networks Module III
Computer Networks Module IIIComputer Networks Module III
Computer Networks Module III
Ajit Nayak
 
Computer Networks Module II
Computer Networks Module IIComputer Networks Module II
Computer Networks Module II
Ajit Nayak
 
Computer Networks Module I
Computer Networks Module IComputer Networks Module I
Computer Networks Module I
Ajit Nayak
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
Ajit Nayak
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
Ajit Nayak
 
Software Engineering : Software testing
Software Engineering : Software testingSoftware Engineering : Software testing
Software Engineering : Software testing
Ajit Nayak
 
Software Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & SpecificationSoftware Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & Specification
Ajit Nayak
 
Software Engineering : Process Models
Software Engineering : Process ModelsSoftware Engineering : Process Models
Software Engineering : Process Models
Ajit Nayak
 
Software Engineering an Introduction
Software Engineering an IntroductionSoftware Engineering an Introduction
Software Engineering an Introduction
Ajit Nayak
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
Ajit Nayak
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
Ajit Nayak
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt III
Ajit Nayak
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
Ajit Nayak
 
Object Oriented Analysis Design using UML
Object Oriented Analysis Design using UMLObject Oriented Analysis Design using UML
Object Oriented Analysis Design using UML
Ajit Nayak
 
Operating Systems Part I-Basics
Operating Systems Part I-BasicsOperating Systems Part I-Basics
Operating Systems Part I-Basics
Ajit Nayak
 
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Operating Systems Part II-Process Scheduling, Synchronisation & DeadlockOperating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Ajit Nayak
 
Introduction to database-Transaction Concurrency and Recovery
Introduction to database-Transaction Concurrency and RecoveryIntroduction to database-Transaction Concurrency and Recovery
Introduction to database-Transaction Concurrency and Recovery
Ajit Nayak
 
Introduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculusIntroduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculus
Ajit Nayak
 
Introduction to database-Normalisation
Introduction to database-NormalisationIntroduction to database-Normalisation
Introduction to database-Normalisation
Ajit Nayak
 
Introduction to database-ER Model
Introduction to database-ER ModelIntroduction to database-ER Model
Introduction to database-ER Model
Ajit Nayak
 
Computer Networks Module III
Computer Networks Module IIIComputer Networks Module III
Computer Networks Module III
Ajit Nayak
 
Computer Networks Module II
Computer Networks Module IIComputer Networks Module II
Computer Networks Module II
Ajit Nayak
 
Computer Networks Module I
Computer Networks Module IComputer Networks Module I
Computer Networks Module I
Ajit Nayak
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
Ajit Nayak
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
Ajit Nayak
 

Recently uploaded (20)

Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Ppt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineeringPpt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineering
ravindrabodke
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Ppt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineeringPpt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineering
ravindrabodke
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 

Database Programming using SQL

  • 1. Introduction to Database Lab: Introduction to Oracle and SQL (CSE 3151) Lab - 0 Ajit K Nayak, Ph.D. Siksha ‘O’ Anusandhan University Aug 2016
  • 2. 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.
  • 3. Ajit K Nayak1.3Introduction to databases Example: Table / relation
  • 4. 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
  • 5. 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.
  • 6. 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
  • 7. 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
  • 8. 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.
  • 9. Ajit K Nayak1.9Introduction to databases Datatypes - Minimal Data 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
  • 10. Ajit K Nayak1.10Introduction to databases Experiment Time Let’s create, insert and retrieve
  • 11. 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);
  • 12. 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
  • 13. 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);
  • 14. 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
  • 15. 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
  • 16. 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 . . .
  • 17. Ajit K Nayak1.17Introduction to databases The SELECT statement -III  Example select name from instructor where salary < 65000 Output Lists all the names in table instructor having salary less than 65000. Mozart El Said . . .
  • 18. Ajit K Nayak1.18Introduction to databases Assignment - I
  • 19. Ajit K Nayak1.19Introduction to databases End of Lab 1 Thank You
  • 20. Introduction to Database Lab: Basic Operations in SQL (CSE 3151) Lab - 2 Ajit K Nayak, Ph.D. Siksha ‘O’ Anusandhan University Aug 2016
  • 21. 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)
  • 22. 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)
  • 23. 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;
  • 24. 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;
  • 25. 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;
  • 26. 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.
  • 27. 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.
  • 28. 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)
  • 29. 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;
  • 30. 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;
  • 31. 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%‟;
  • 32. 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‟);
  • 33. 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
  • 34. Ajit K Nayak1.15Introduction to databases Group Functions Example SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM instructor;
  • 35. 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);
  • 36. 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.
  • 37. Ajit K Nayak1.18Introduction to databases Task  Execute all the queries discussed  Solve Assignment 2
  • 38. Ajit K Nayak1.19Introduction to databases End of Lab 2 Thank You
  • 39. Introduction to Database Lab: Functions in SQL (CSE 3151) Lab - 3 Ajit K Nayak, Ph.D. Siksha ‘O’ Anusandhan University Aug 2016
  • 40. 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;
  • 41. 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
  • 42. 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: ?
  • 43. Ajit K Nayak1.5Introduction to databases End of Lab 3 Thank You
  • 44. Introduction to Database Lab: Sorting and DDL (CSE 3151) Lab - 4 Ajit K Nayak, Ph.D. Siksha ‘O’ Anusandhan University Aug 2016
  • 45. 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
  • 46. 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;
  • 47. 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
  • 48. 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.
  • 49. 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 column ALTER TABLE instructor SET UNUSED (doj); At a later time ALTER TABLE instructor DROP UNUSED COLUMNS;
  • 50. Ajit K Nayak1.7Introduction to databases DDL - II  Renaming objects  Rename a table RENAME instructor TO faculty;  Rename a table column ALTER TABLE instructor RENAME COLUMN dept_name TO department;
  • 51. 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 structure DROP TABLE instructor;
  • 52. Ajit K Nayak1.9Introduction to databases End of Lab 4 Thank You
  • 53. Introduction to Database Lab: Data Constraints (CSE 3151) Lab - 5 Ajit K Nayak, Ph.D. Siksha ‘O’ Anusandhan University Aug 2016
  • 54. 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)
  • 55. 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
  • 56. 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.
  • 57. 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
  • 58. 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.
  • 59. 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;
  • 60. 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
  • 61. 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;
  • 62. 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
  • 63. 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.
  • 64. 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));
  • 65. 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;
  • 66. Ajit K Nayak5.14Introduction to databases LAB After Referencing  Extract information from two tables with referential integrity SELECT lastname, address, city, orderNo FROM customer, orders WHERE customer.cid = order.cid;
  • 67. 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
  • 68. 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
  • 69. 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 );
  • 70. 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 '_%@_%._%');
  • 71. Ajit K Nayak5.19Introduction to databases LAB End of Lab 5 Thank You
  • 72. Introduction to Database Lab: Subquery (CSE 3151) Lab - 6 Ajit K Nayak, Ph.D. Siksha ‘O’ Anusandhan University Aug 2016
  • 73. 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
  • 74. 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”);
  • 75. 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
  • 76. 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);
  • 77. 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);
  • 78. 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);
  • 79. 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);
  • 80. 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’;
  • 81. 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’;
  • 82. Ajit K Nayak5.11Introduction to databases LAB Problem with Subquery  A common problem with subqueries is no rows being returned by the inner query.
  • 83. Ajit K Nayak5.12Introduction to databases LAB End of Lab 6 Thank You
  • 84. Introduction to Database Lab: Joining Tables (CSE 3151) Lab - 7 Ajit K Nayak, Ph.D. Siksha ‘O’ Anusandhan University Aug 2016
  • 85. 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
  • 86. Ajit K Nayak5.3Introduction to databases LAB Obtaining data from multiple tables
  • 87. 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.
  • 88. Ajit K Nayak5.5Introduction to databases LAB Cartesian Products: Example  SELECT last_name, department_name dept_name FROM employees, departments;
  • 89. Ajit K Nayak5.6Introduction to databases LAB Generating a Cartesian Product
  • 90. 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;
  • 91. 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’;
  • 92. 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;
  • 93. 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;
  • 94. Ajit K Nayak5.11Introduction to databases LAB Joining more than two tables
  • 95. 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
  • 96. Ajit K Nayak5.13Introduction to databases LAB Self Joins
  • 97. Ajit K Nayak5.14Introduction to databases LAB End of Lab 7 Thank You