SQL Concepts: Krishnadas Manakotte Vivek Verma
SQL Concepts: Krishnadas Manakotte Vivek Verma
Krishnadas Manakotte
Vivek Verma
Basic Structure
Set Operations
Aggregate Functions
Null Values
Nested Subqueries
Views
Derived Relations
Modification of the Database
Joined Relations
Data Definition Language
Links
SQL Concepts
Schema Used in Examples
customer
PK customer_name
customer_street
customer_city
loan borrower
PK loan_number
SQL Concepts
SQL What/Where ?
SQL Concepts
Basic Structure
SQL is based on set and relational operations with certain modifications and
enhancements
A typical SQL query has the form:
SQL Concepts
The select Clause
SQL Concepts
The select Clause (Cont.)
SQL Concepts
The select Clause (Cont.)
The select clause can contain arithmetic expressions involving the operation,
+, –, ∗, and /, and operating on constants or attributes of tuples.
The query:
select loan-number, branch-name, amount ∗ 100
from loan
would return a relation which is the same as the loan relations, except that
the attribute amount is multiplied by 100.
SQL Concepts
The where Clause
SQL Concepts
The where Clause (Cont.)
SQL Concepts
The from Clause
SQL Concepts
The Rename Operation
The SQL allows renaming relations and attributes using the as clause:
old-name as new-name
Find the name, loan number and loan amount of all customers; rename the
column name loan-number as loan-id.
SQL Concepts
Tuple Variables
Tuple variables are defined in the from clause via the use of the as clause.
Find the customer names and their loan numbers for all
customers having a loan at some branch.
select customer-name, T.loan-number, S.amount
from borrower as T, loan as S
where T.loan-number = S.loan-number
Find the names of all branches that have greater assets than some branch
located in Bangalore.
select distinct T.branch-name
from branch as T, branch as S
where T.assets > S.assets and S.branch-city = ‘BANGALORE’
SQL Concepts
String Operations
select customer-name
from customer
where customer-street like ‘%MAIN%’
SQL Concepts
Ordering the Display of Tuples
List in alphabetic order the names of all customers having a loan in Jayanagar
branch
select distinct customer-name
from borrower, loan
where borrower loan-number = loan.loan-number and
branch-name = ‘JAYANAGAR’
order by customer-name
We may specify desc for descending order or asc for ascending order, for
each attribute; ascending order is the default.
E.g. order by customer-name desc
SQL Concepts
Set Operations
The set operations union, intersect, and except operate on relations and
correspond to the relational algebra operations
∪, ∩, −.
Each of the above operations automatically eliminates duplicates; to retain all
duplicates use the corresponding multiset versions union all, intersect all
and except all.
Suppose a tuple occurs m times in r and n times in s, then, it
occurs:
m + n times in r union all s
min(m,n) times in r intersect all s
max(0, m – n) times in r except all s
SQL Concepts
Set Operations
SQL Concepts
Aggregate Functions
SQL Concepts
Aggregate Functions (Cont.)
SQL Concepts
Aggregate Functions – Group By
SQL Concepts
Aggregate Functions – Having Clause
Find the names of all branches where the average account balance is more
than Rs.5,000.
select branch-name, avg (balance)
from account
group by branch-name
having avg (balance) > 5000
Note: predicates in the having clause are applied after the
formation of groups whereas predicates in the where clause are applied
before forming groups
SQL Concepts
Aggregate Functions – Having Clause
Find the names of all branches where the average account balance is more
than Rs.1,200 except Jayanagar branch.
select branch-name, avg (balance)
from account
where branch-name <> ‘JAYANAGAR’
group by branch-name
having avg (balance) > 1200
SQL Concepts
Null Values
SQL Concepts
Null Values and Three Valued Logic
SQL Concepts
Null Values and Aggregates
SQL Concepts
Example NULL value
Select all branches who has not achieved the monthly target of Rs.1000. All
the branches with ‘NIL’ transaction should be displayed.
Select branch-name,sum(nvl(amount,0))
from loan
group by branch-name
having sum(nvl(amount,0))<1000
SQL Concepts
Nested Subqueries
SQL Concepts
Example Query (subqueries)
Find all customers who have both an account and a loan at the bank.
select distinct customer-name
from borrower
where customer-name in (select customer-name from depositor)
Find all customers who have a loan at the bank but do not have an account at
the bank
select distinct customer-name
from borrower
where customer-name not in (select customer-name from
depositor)
SQL Concepts
Views
Provide a mechanism to hide certain data from the view of certain users. To
create a view we use the command:
create view v as <query expression>
where:
<query expression> is any legal expression
The view name is represented by v
SQL Concepts
Example Query
SQL Concepts
Derived Relations
Find the average account balance of those branches where the average
account balance is greater than Rs.4000.
select branch-name, avg-balance
from (
select branch-name, avg (balance)
from account
group by branch-name) as result (branch-name, avg-
balance
)
where avg-balance > 4000
Note that we do not need to use the having clause, since we
compute the temporary (view) relation result in the from clause,
and the attributes of result can be used directly in the where
clause.
SQL Concepts
Modification of the Database – Deletion
SQL Concepts
Example Query
Delete the record of all accounts with balances below the average at the bank.
Problem: as we delete tuples from deposit, the average balance
changes
delete from account
where balance < (select avg (balance)
from account)
Solution used in SQL:
1. First, compute avg balance and find all tuples to delete
2. Next, delete all tuples found above (without recomputing avg
or retesting the tuples)
SQL Concepts
Modification of the Database – Insertion
SQL Concepts
Modification of the Database – Insertion
Provide as a gift for all loan customers of the Jayanagar branch, a Rs.200
savings account. Let the loan number serve as the account number for the
new savings account
insert into account
select loan-number, branch-name, 200
from loan
where branch-name = ‘JAYANAGAR’
insert into depositor
select customer-name, loan-number
from loan, borrower
where branch-name = ‘JAYANAGAR’
and loan.account-number = borrower.account-number
The select from where statement is fully evaluated before any of its results are
inserted into the relation (otherwise queries like
insert into table1 select * from table1
would cause problems)
SQL Concepts
Modification of the Database – Updates
Increase all accounts with balances over Rs.6,000 by 6%, all other accounts
receive 5%.
Write two update statements:
update account
set balance = balance ∗ 1.06
where balance > 6000
update account
set balance = balance ∗ 1.05
where balance ≤ 6000
The order is important
Can be done better using the case statement (next slide)
SQL Concepts
Case Statement for Conditional Updates
Same query as before: Increase all accounts with balances over Rs.6,000 by
6%, all other accounts receive 5%.
update account
set balance=
case
when balance <= 6000 then balance *1.05
else balance * 1.06
end
SQL Concepts
Transactions
SQL Concepts
Joined Relations
• Join operations take two relations and return as a result another relation.
• These additional operations are typically used as subquery expressions in the
from clause
• Join condition – defines which tuples in the two relations match,and what
attributes are present in the result of the join.
• Join type – defines how tuples in each relation that do not match any tuple in
the other relation (based on the join condition) are treated.
Join Types
– inner join
– left outer join
– right outer join
– full outer join
SQL Concepts
Joined Relations – Datasets for Examples
SQL Concepts
Joined Relations – Examples
SQL Concepts
Joined Relations – Examples
SQL Concepts
Joined Relations – Examples Examples
SQL Concepts
Data Definition Language (DDL)
SQL Concepts
Create Table Construct
SQL Concepts
Integrity Constraints in Create Table
• not null
• primary key (A1, ..., An)
• check (P), where P is a predicate
Example: Declare branch-name as the primary key for branch and ensure that
the values of assets are nonnegative.
create table branch
(branch-name char(15),
branch-city char(30)
assets integer,
primary key (branch-name),
check (assets >= 0))
primary key declaration on an attribute automatically ensures not null in
SQL-92 onwards, needs to be explicitly stated in SQL-89 (NB Exams)
SQL Concepts
Drop and Alter Table Constructs
The drop table command deletes all information about the dropped relation
from the database.
The after table command is used to add attributes to an existing relation. All
tuples in the relation are assigned null as the value for the new attribute. The
form of the alter table command is
alter table r add A D
where A is the name of the attribute to be added to relation r
and D is the domain of A.
The alter table command can also be used to drop attributes of a relation
alter table r drop A
where A is the name of an attribute of relation r
Dropping of attributes not supported by many databases (Supported from
Oracle 8i onwards)
SQL Concepts
Procedural Extensions and Stored Procedures
SQL Concepts
Links
• http://www.ilook.fsnet.co.uk/ora_sql/sqlmain.htm
• http://www.db.cs.ucdavis.edu/teaching/sqltutorial/
• http://www.sql-tutorial.net/
• http://www.firstsql.com/tutor.htm
SQL Concepts
Reference
• www.oracle.com
• www.csee.umbc.edu
• www.wiscorp.com
SQL Concepts
Contact Information
Vivek Verma
[email protected]
THANK YOU
SQL Concepts
Primary Key
• What is a primary key?
• A primary key is a single field or combination of fields that uniquely defines a record.
None of the fields that are part of the primary key can contain a null value. A table can
have only one primary key.
• Note: In Oracle, a primary key can not contain more than 32 columns.
• A primary key can be defined in either a CREATE TABLE statement or an ALTER
TABLE statement.
•
Using a CREATE TABLE statement
• The syntax for creating a primary key using a CREATE TABLE statement is:
• CREATE TABLE table_name
(column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, . column_n)
);
•
For example:
• CREATE TABLE supplier
(supplier_idnumeric(10)not null,
supplier_namevarchar2(50)not null,
contact_namevarchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id));
SQL Concepts
Foreign Key
• What is a foreign key?
• A foreign key means that values in one table must also appear in another table.
• The referenced table is called the parent table while the table with the foreign key is called the child
table. The foreign key in the child table will generally reference a primary key in the parent table.
• A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
•
Using a CREATE TABLE statement
• The syntax for creating a foreign key using a CREATE TABLE statement is:
• CREATE TABLE table_name
(column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
);
•
For example: CREATE TABLE
• CREATE TABLE supplier( products(product_idnumeric(10)not
supplier_idnumeric(10)not null, null,supplier_idnumeric(10)not null,CONSTRAINT
supplier_namevarchar2(50)not null, fk_supplier FOREIGN KEY (supplier_id)
contact_namevarchar2(50),
CONSTRAINT supplier_pk REFERENCES supplier(supplier_id));
PRIMARY KEY (supplier_id));
SQL Concepts