Section II SQL
Section II SQL
1
History
• IBM Sequel language developed as part of System R project at the
IBM San Jose Research Laboratory
• Renamed Structured Query Language (SQL)
• ANSI and ISO standard SQL:
– SQL-86
– SQL-89
– SQL-92
– SQL:1999 (language name became Y2K compliant!)
– SQL:2003
• Commercial systems offer most, if not all, SQL-92 features, plus
varying feature sets from later standards and special proprietary
features.
– Not all examples here may work on your particular system.
2
Background
• SQL – Structured Query Language
– Developed by IBM in the 1970’s, originally called
Sequel
– The standard relational-database language
– Uses relational-algebra and relational-calculus
constructs
– SQL is used to interact with a database to manage
and ret rieve data.
3
Background
• SQL is a language that all commercial RDBMS
implementations understand.
• You can’t write programs like the ones you would have done
using C langauge
4
Data types
• Integer
• Float
• Char
• Varchar2
• Number
• date
5
• Integers
• Decimal numbers--- NUMBER, INTEGER .
• Number is an oracle data type. Integer is an ANSI data type.
Integer is equivalent of NUMBER(38)
• The syntax for NUMBER is NUMBER(P,S) p is the precision
and s is the scale. P can range from 1
• to 38 and s from -84 to 127
6
• Variable length character strings ---
Varchar2(len)
• Variable length character string having
maximum length len bytes. We must specify
the size
• Dates-----DATE
7
• Constants/Literals
• ANSI standard defines format for literals
• Numeric: 21, -32, $0.75,1.2E4
• String: enclosed within ‘ …’
• Date : 12-mar-03*
8
• •Oracle has a built in function called
TO_DATE. This can be used to convert dates
written in other
• formats
• •E.g TO_DATE(‘Mar 12 2003’, ‘mon dd yyyy’)
• •The built in function sysdate can be used to
obtain the current system date.
9
The DDL, DML and DCL.
• SQL has three flavors of statements.
• DDL is Data Definition Language statements. Some examples:
• CREATE - to create objects in the database
• ALTER - alters the structure of the database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table, including all spaces
allocated for the records are
• removed
• COMMENT - add comments to the data dictionary
• GRANT - gives user's access privileges to database
• REVOKE - withdraw access privileges given with the GRANT
command
10
DML is Data Manipulation Language
statements
• Some examples:
• SELECT - retrieve data from the a database
• INSERT - insert data into a table
• UPDATE - updates existing data within a table
• DELETE - deletes all records from a table, the
space for the records remain
• CALL - call a PL/SQL or Java subprogram
• EXPLAIN PLAN - explain access path to data
• LOCK TABLE - control concurrency
11
DCL is Data Control Language
statements.
• Some examples:
• COMMIT - save work done
• SAVEPOINT - identify a point in a transaction
to which you can later rollback
• ROLLBACK - restore database to original since
the last COMMIT
• SET TRANSACTION - Change transaction
options like what rollback segment to use
12
SQL - CREATE TABLE
• Syntax:
• CREATE TABLE tablename (column_name data_ type constraints, …)
• Example:
• CREATE TABLE Emp (
• EmpNo short CONSTRAINT PKey PRIMARY KEY,
• EName VarChar(15),
• Job Char(10) CONSTRAINT Unik1 UNIQUE,
• Mgr short CONSTRAINT FKey1 REFERENCES EMP (EmpNo),
• Hiredate Date,
• Sal single,
• Comm single,
• DeptNo short CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
• Used to create a table by defining its structure, the data type and name of
the various columns, the relationships with columns of other tables etc.
13
SQL - ALTER TABLE
• Add/Drop Column
• Syntax:
• ALTER TABLE tablename (ADD/DROP
column_name)
• ALTER TABLE EMP (ADD Grade short);
• ALTER TABLE EMP (DROP Grade);
• Used to modify the structure of a table by adding
and removing columns
14
• SQL - ALTER TABLE
• Add/Drop Primary key
• ALTER TABLE EMP ADD CONSTRAINT Pkey1
PRIMARY KEY (EmpNo);
• ALTER TABLE EMP DROP CONSTRAINT Pkey1;
15
• SQL - ALTER TABLE
• Add/Drop Foreign key
• ALTER TABLE EMP ADD CONSTRAINT Fkey1
FOREIGN KEY (Mgr)
• REFERENCES EMP (EName);
• ALTER TABLE EMP DROP CONSTRAINT Fkey1;
16
• SQL - DROP TABLE
• DROP TABLE
• – Deletes table structure
• – Cannot be recovered
• – Use with caution
• DROP TABLE EMP;
17
• NULL
• Missing/unknown/inapplicable data
represented as a null value
• NULL is not a data value. It is just an indicator
that the value is unknown
18
• Data Manipulation Language Statements
The DML statements are used to:
– Insert data into the table
– Delete data from the table
– Retrieve data from the table
– Modify/ update data in the table
INSERT Statement
• Single-row insert : A single-row INSERT
statement adds a single new row of data to
the table.
• Inserting all columns:
• SQL permits omitting of the column list from
the INSERT statement . When the column list
is omit ted, SQL automatically generates a
column list consisting of all columns of the
table, in left to right sequence.
DELETE Statement
• The DELETE statement can delete one or more
rows from a table.
• Even if all the data is deleted from the table, the
definition of the table and its column is still stored
in the database. The table still exists. To erase the
definition of the table from the database, the
DROP TABLE statement must be used.
• The DELETE statement cannot delete column(s)
from a table. It deletes only row(s). To delete a
column from a table, the ALTER TABLE statement
must be used.
• Deleting all rows of a t able - Delete all current
customers
• 1. DELETE FROM Customer_Details;
• Deleting some rows of a t able- Delete Customer with
Cust _ID=102 from t he list of customers
• 2. DELETE FROM Customer_Details WHERE Cust_ID =
102;
• Examples of invalid DELETE Statement s
• 3. DELETE * FROM Customer_Details;
• OR
• 4. DELETE Cust_ID FROM Customer_Details;
Difference between TRUNCATE and DELETE statement
• TRUNCATE deletes all records from the table whereas DELETE can
be used to selectively delete records from a table using the WHERE
clause
2. List all Cust _ID, Cust _Last _Name where Account _t ype is
‘Savings’ and Bank_Branch is ‘Downt own’ .
SELECT Cust_ID, Cust_Last_Name
FROM Customer_Details
WHERE Account_Type = ‘Savings’
AND Bank_Branch = ‘Downtown’;
• 3. List all Cust _ID, Cust _Last _Name where neither Account _t ype
is ‘Savings’ and nor Bank_Branch is ‘Downt own’ .
SELECT Cust_ID, Cust_Last_Name
FROM Customer_Details
WHERE NOT Account_Type = ‘Savings’
AND NOT Bank_Branch = ‘Downtown’;
• 4. List all Cust _ID, Cust _Last _Name where eit her Account _t ype
is ‘Savings’ or Bank_Branch is ‘Downt own’ .
SELECT Cust_ID, Cust_Last_Name
FROM Customer_Details
WHERE Account_Type = ‘Savings’
OR Bank_Branch = ‘Downtown’;
To create the table from an existing table and to populate a
table with the contents of an existing table.
41
Select command to insert Records
• Inserting data set into a table from another
table.
• Syntax: -
• insert into <table_name>
• select column_name1,…,column_name n
• from <existing_table_name>
• [where <condition>];
•
• e.g. To insert rows into emp_temp from emp table.
•
• insert into emp_temp
• select empno, ename, deptno
• from emp;
• Note : - There are two sets of identical rows in the table EMP_TEMP.
This is because one set of rows was created during the CREATE table
As select command and other set of rows was created by the INSERT
command.
Select command for Column Aliases.
Syntax:
select column_name <alias_name> from
table_name;
e.g.
select ename “Employees” from emp;
• The COMMIT command used to save all changes
made by the transaction in the database. The
COMMIT command saves all modifications since
the last COMMIT or ROLLBACK command.
• The ROLLBACK command used to undo changes
made by a transaction. The ROLLBACK command
can only undo modifications since the last
COMMIT or ROLLBACK command that was issued.
44
The select Clause
• The select clause list the attributes desired in the
result of a query
– corresponds to the projection operation of the
relational algebra
• Example: find the names of all instructors:
select name
from instructor
• NOTE: SQL names are case insensitive (i.e., you
may use upper- or lower-case letters.)
– E.g. Name ≡ NAME ≡ name
– Some people use upper case wherever we use bold
font.
45
The select Clause (Cont.)
• SQL allows duplicates in relations as well as in query results.
• To force the elimination of duplicates, insert the keyword distinct after
select.
• Find the names of all departments with instructor, and remove
duplicates
select distinct dept_name
from instructor
• The keyword all specifies that duplicates not be removed.
46
The select Clause (Cont.)
• An asterisk in the select clause denotes “all attributes”
select *
from instructor
• The select clause can contain arithmetic expressions involving the
operation, +, –, *, and /, and operating on constants or attributes of
tuples.
• The query:
select ID, name, salary/12
from instructor
would return a relation that is the same as the instructor relation,
except that the value of the attribute salary is divided by 12.
47
The where Clause
• The where clause specifies conditions that the result must satisfy
– Corresponds to the selection predicate of the relational algebra.
• To find all instructors in Comp. Sci. dept with salary > 80000
select name
from instructor
where dept_name = ‘Comp. Sci.' and salary > 80000
• Comparison results can be combined using the logical connectives and,
or, and not.
• Comparisons can be applied to results of arithmetic expressions.
48
The from Clause
• The from clause lists the relations involved in the query
– Corresponds to the Cartesian product operation of the relational
algebra.
• Find the Cartesian product instructor X teaches
select *
from instructor, teaches
– generates every possible instructor – teaches pair, with all attributes
from both relations
• Cartesian product not very useful directly, but useful combined with
where-clause condition (selection operation in relational algebra)
49
Customer_Details
50
Customer_Transaction
51
SQL Operators
Overview
• An operator manipulates individual data items and returns a
result.
• The data items are called operands or arguments.
• Operators are represented by special characters or by keywords.
• For example, the multiplication operator is represented by an
asterisk (*) and the operator that tests for nulls is represented by
the keywords IS NULL.
• There are two general classes of operators:
Unary Operators
• A unary operator uses only one operand. A unary operator
typically appears with its operand in the following format.
operator operand
Binary Operators
• A binary operator uses two operands. A binary operator appears
with its operands in the following format.
operand1 operator operand2 52
Types of operators
54
Examples: -
1. select salary + 2000 from emp;
2. select ename , salary + comm “Total Salary” from emp where
deptno = 20;
Note:
1. * and / have equal higher precedence.
2. + and – have equal lower precedence.
55
Comparison or Relational Operators
• Comparison operators are used in conditions to compare one
expression with another. Comparison operators are listed as
below:
Examples: -
Display the list of employees whose job is ‘analyst’.
select * from emp where job = ‘analyst’;
56
Comparison or Relational Operators
Operator Description Example
= Equality test. SELECT ENAME "Employee" FROM EMP WHERE
SAL = 1500;
!=, ^=, <> Inequality test. SELECT ENAME FROM EMP WHERE SAL != 5000;
> Greater than test. SELECT ENAME "Employee", JOB "Title" FROM
EMP WHERE SAL > 3000;
< Less than test. SELECT * FROM PRICE WHERE MINPRICE < 30;
>= Greater than or equal SELECT * FROM PRICE WHERE MINPRICE >= 20;
to test.
<= Less than or equal to SELECT ENAME FROM EMP WHERE SAL <=
test. 1500;
57
Operator Description Example
IN "Equivalent to any member of" test. SELECT * FROM EMP WHERE
Equivalent to "=ANY". ENAME IN ('SMITH', 'WARD');
ANY/ SOME Compares a value to each value in a list or SELECT * FROM DEPT WHERE
returned by a query. Must be preceded by =, LOC = SOME ('NEW
!=, >, <, <= or >=. Evaluates to FASLE if the YORK','DALLAS');
query returns no rows.
IS [NOT] Tests for nulls. This is the only operator that SELECT * FROM EMP WHERE
NULL should be used to test for nulls. COMM IS NOT NULL AND SAL >
1500; 58
Operator Description Example
[NOT] [Not] greater than or equal to x and less SELECT ENAME, JOB
BETWEEN x than or equal to y. FROM EMP WHERE SAL
and y BETWEEN 3000 AND
5000;
EXISTS TRUE if a sub-query returns at least one SELECT * FROM EMP
row. WHERE EXISTS (SELECT
ENAME FROM EMP
WHERE MGR IS NULL);
x [NOT] LIKE TRUE if x does [not] match the pattern y. SELECT * FROM EMP
y [ESCAPE z] Within y, the character "%" matches any WHERE ENAME LIKE
string of zero or more characters except null. '%E%';
The character "_" matches any single
character. Any character following ESCAPE is
interpreted literally, useful when y contains
a percent (%) or underscore (_).
59
Logical operators
• A logical operator is used to combine the results of two conditions to
produce a single result.
• Logical operators which manipulate the results of conditions .
AND operator
• It is used to combine the result of two conditions and both the
conditions must be true for the entire condition to be true.
Examples:-
• Display the list of employees whose salary is between 5000 and
20000.
select * from emp where salary>= 5000 and salary <= 20000;
60
Logical operators
OR operator
• It is used to combine the result of two conditions and if one of the condition is
true, then entire condition is true.
Examples: -
1) Display the list of employees whose manager is 1003 or department is 30.
select * from emp where mgr = 1003 or deptno = 30;
2) Display the list of employees who belongs to department 10 or 30.
select * from emp where deptno = 10 or deptno=30;
NOT operator
• It is a negative of a single condition.
Examples: -
Display the list of employees whose salary is not less than 5000.
select * from emp where not salary < 5000 ;
2) Display the list of employees except job title as ‘Manager’.
select * from emp where not (job = ‘manager’);
61
Logical operators
Operator Description Example
NOT Returns TRUE if the following SELECT * FROM EMP WHERE NOT
condition is FALSE. Returns FALSE if (job IS NULL)
it is TRUE. If it is UNKNOWN, it
SELECT * FROM EMP WHERE NOT
remains UNKNOWN. (sal BETWEEN 1000 AND 2000)
63
To use comparison operators in ORACLE for range
searching and pattern matching of table data.
• Comparison Operators :
• IN, NOT IN
• BETWEEN, NOT BETWEEN
• IS NULL , IS NOT NULL
• ANY, ALL
• LIKE, NOT LIKE
64
IN, NOT IN
• The IN operator allows you to specify multiple values in a
WHERE clause.
• The IN operator is a shorthand for multiple OR conditions.
• IN Syntax
• SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
• or:
• SELECT column_name(s)
FROM table_name
WHERE column_nameIN (SELECT STATEMENT);
65
Custom
CustomerName ContactName Address City PostalCode Country
erID
1 AlfredsFutterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Avda. de la
2 Emparedados y Ana Trujillo Constitución México D.F. 05021 Mexico
helados 2222
Antonio Moreno Antonio Mataderos
3 México D.F. 05023 Mexico
Taquería Moreno 2312
120 Hanover
4 Around the Horn Thomas Hardy London WA1 1DP UK
Sq.
Christina
5 Berglundssnabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
Customers
66
IN, NOT IN
• Select all customers that are located in "Germany", "France"
and "UK“.
• SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
•
• Select all customers that are NOT located in "Germany",
"France" or "UK“.
• SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
• Select all customers that are from the same countries as the
suppliers.
• SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
67
BETWEEN, NOT BETWEEN
• The BETWEEN operator selects values within a
given range. The values can be numbers, text,
or dates.
• The BETWEEN operator is inclusive: begin and
end values are included.
• BETWEEN Syntax
• SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND
value2;
68
ProductI Supplier
ProductName CategoryID Unit Price
D ID
10 boxes x 20
1 Chais 1 1 18
bags
24 - 12 oz
2 Chang 1 1 19
bottles
12 - 550 ml
3 Aniseed Syrup 1 2 10
bottles
Chef Anton's
4 1 2 48 - 6 oz jars 22
Cajun Seasoning
Chef Anton's
5 1 2 36 boxes 21.35
Gumbo Mix
69
BETWEEN, NOT BETWEEN
72
OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2
78
String Operations
• “Find the names of all customers whose street
address includes the substring ‘Main’.”
select customer-name
from customer
where customer-street like ‘%Main%’
Schema:
Customer(id, name, age, address, salary, state)
80
Order by
• The rows of the query results are not arranged in any
particular order.
81
1. List the customers account numbers and their account
balances, in the increasing order of the balance.
SELECT Account_No, Total_Available_Balance_in_Dollars
FROM Customer_Transaction
ORDER BY Total_Available_Balance_in_Dollars;
82
2. List the customers and their account numbers in the decreasing order of the account
numbers.
SELECT Cust_Last_Name, Cust_First_Name, Account_No
FROM Customer_Details
ORDER BY Account_No DESC;
3. List the customers and their account numbers in the decreasing order of the
Customer Last Name and increasing order of account numbers.
84
UNION
• The UNION operation combines the rows from two sets of
query results.
Example:
SELECT Cust_ID
FROM Customer_Fixed_Deposit
UNION
SELECT Cust_ID
FROM Customer_Loan;
85
UNION
• To retain duplicate rows in a UNION operation,
specify the ALL keyword immediately following
the word UNION.
• Example:
SELECT Cust_ID
FROM Customer_Fixed_Deposit
UNION ALL
SELECT Cust_ID
FROM Customer_Loan;
86
87
88
• There are some restrictions on the table that
can be combined by a UNION operation:
89
• Neither of the two tables can be sorted with
the ORDER BY clause.
• However, the combined query results can be
sorted.
• Eliminating duplicate rows from query results
is a time consuming process, especially if the
query results contain a large number of rows.
90
Union
• “ Find all customers having a loan, an account,
or both at the bank.”
(SELECT customer-name
from depositor)
union
(SELECT customer-name
from borrower)
91
Names of all customers who have either an accountor an loan
92
INTERSECT
• The INTERSECT operation SELECTs the
common row from two sets of query results.
• Example:
SELECT Cust_ID
FROM Customer_Fixed_Deposit
INTERSECT
SELECT Cust_ID
FROM Customer_Loan;
93
94
INTERSECT
• “ Find all customers who have both a loan and
an account at the bank.”
(SELECT distinctcustomer-name
from depositor)
INTERSECT
(SELECT distinctcustomer-name
from borrower)
95
“ Find all customers who have both a loan and an account at the
bank.”
96
Except
• “Find all customers who have an account but
no loan at the bank.”
97
“Find all customers who have an account but no loan at the
bank.”
98
SetOperations
• Find courses that ran in Fall 2009 or in Spring 2010
(SELECT course_id from section where sem = ‘Fall’ and year = 2009)
union
(SELECT course_id from section where sem = ‘Spring’ and year = 2010)
(SELECT course_id from section where sem = ‘Fall’ and year = 2009)
except
(SELECT course_id from section where sem = ‘Spring’ and year = 2010)
99
Aggregation Functions
• Aggregation functions take a collection of values as
input and return a single value.
100
Aggregate Functions (Cont.)
10. List total number of Employees who have been assigned a Manager.
SELECT COUNT(Manager_ID)
FROM Employee_Manager;
106
Aggregate Functions – Group By
• Find the average salary of instructors in each department
– SELECT dept_name, avg (salary)
from instructor
group by dept_name;
– Note: departments with no instructor will not appear in result
avg_salary
Result
Instructor 107
GROUP BY
• The GROUP BY clause is used in a SELECT
statement to collect data across multiple
records and group the results by one or more
columns.
108
109
110
111
112
HAVING
• The HAVING clause is used along with the GROUP BY clause.
• Find the names and average salaries of all departments whose average salary is
greater than 42000.
• They can be very useful when you need to select rows from a
table with a condition that depends on the data in the table
itself.
• Note: Comparison conditions fall into two classes: single-row operators (>,
=, >=, <, <>, <=) and multiple-row operators (IN, ANY, ALL).
• The outer query takes the result of the inner query and uses
this result to display all the employees who earn more than
this amount.
• Execute the subquery (inner query) on its
own first to show the value that the
subquery returns.
• Only one ORDER BY clause can be used for a SELECT statement, and if
specified it must be the last clause in the main SELECT statement. Starting
with release Oracle8i, an ORDER BY clause can be used and is required in
the subquery to perform Top-N analysis.
• The Oracle server imposes no limit on the number of subqueries; the limit
is related to the buffer size that the query uses.
Top-N- Analysis
Types of Subqueries
• Single-row subqueries: Queries
that return only one row from the
inner SELECT statement
• Multiple-row subqueries:
Queries that return more than one
row from the inner SELECT statement
• The Oracle server returns results into the HAVING clause of the main
query.
• The SQL statement on the slide displays all the departments that have a
minimum salary greater than that of department 50.
The HAVING Clause with Subqueries
Problems with Subqueries
• A common problem with sub-queries is no rows being
returned by the inner query.
Problems with Subqueries
• There is no employee named Haas. So the subquery
returns no rows.
The NOT operator can be used with IN, ANY, and ALL operators.
Null Values in a Subquery
• One of the values returned by the inner query is a null value,
and hence the entire query returns no rows.
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
• Find all the employees whose salary is above average salary.
• Select * from emp where sal > (select avg(sal) from emp);
• Find the name and empno of that employee whose salary is
maximum.
• Select * from emp where sal = (select max(sal) from emp);
• To see second maximum salary
• Select max(sal) from emp where
sal < (select max(sal) from emp);
• Similarly to see the Third highest salary.
• Select max(sal) from emp where
sal < (select max(sal) from emp where
sal < (select max(sal) from emp));
• We want to see how many employees are there whose salary
is above average.
• Select count(*) from emp where
sal > (select AVG(sal) from emp);
• Display those employees who are working in Hyderabad.
• Remember emp and dept are joined on deptno and city
column is in the dept table. Assuming that wherever the
department is located the employee is working in that city.
• Select * from emp where deptno
in (select deptno from dept where city=’HYD’);
• Find the sum of salary deptwise.
Select sum(sal) from emp group by deptno;
• Display employee and their salaries with null salary replaced by ‘zero’.
Select ename, nvl(sal,’zero’ from emp;
• Find all employees whose salary is greater than at least one employee at
department 30.
Select * from emp where sal>any(select sal from emp where deptno=30)
• List the emps Whose Jobs are same as MILLER or Sal is more
than ALLEN.
• select * from emp where job = (select job from emp where
ename = ‘MILLER’ ) OR sal>(select sal from emp where ename =
‘ALLEN’);
• List the emps whose jobs same as SMITH or ALLEN.
• select * from emp where job in (select job from emp where
ename = ‘SMITH’ or ename = ‘ALLEN’);
• (OR)
• select * from emp where job in (select job from emp where
ename in (‘SMITH’,’ALLEN’);
• List the employees who are senior to most recently hired
employee working under king.
• select * from emp where hiredate <
(select max(hiredate) from emp
where mgr in (select empno from emp where ename = 'KING')) ;
• Find the total sal given to the MGR.
select sum (sal) from emp
where job = ‘MANAGER’;
(OR)