SQL PDF
SQL PDF
Agenda
What is SQL?
SQL Terminology
Creating and Deleting Tables
Select Statement for querying
Join Statement
Aliases
Sub-query
Comparison, Character match, Numerical
expression
Insert, Update, Delete
SQL Data-types
What is SQL?
What is SQL?
SQL provides a way to retrieve and
manipulate data in a relational database
SQL is used for all relational database
operations, including administration,
schema creation and data retrieval
Data definition
Data manipulation
Case Sensitivity
SQL is not case sensitive
SQL Terminology
SQL Terms
Table
A set of rows
Analogous to a file
Column
A column is analogous to a field of a record
Each column in a given row has a single value
Primary Key
One of more columns whose contents are
unique within a table and thus can be used to
identify a row of that table
10
CREATE TABLE
create table store
(store_id NUMERIC,
name VARCHAR(25),
city VARCHAR(25),
state VARCHAR(2),
zip VARCHAR(25));
13
ALTER TABLE
ALTER TABLE store ADD UNIQUE (C1);
ALTER TABLE store ADD ORDER_NUM INT;
ALTER TABLE store ADD CONSTRAINT
constraint_0 FOREIGN KEY (C1)
REFERENCES T1 (C1);
ALTER TABLE store DROP ORDER_NUM
CASCADE;
ALTER TABLE store RENAME TO T1;
14
DROP TABLE
DROP TABLE store;
15
16
CREATE/ALTER/DROP USER
CREATE USER PoInT PASSWORD BaSE;
CREATE USER "PoInT" PASSWORD "BaSE";
ALTER USER Scott PASSWORD lion;
ALTER USER Scott DEFAULT ROLE CEO;
DROP USER ENGINEERING_MANAGER
CASCADE;
17
CREATE/DROP VIEW
CREATE VIEW customer_order
AS select
order_num,order_tbl.customer_num,customer
_tbl.name
FROM order_tbl,customer_tbl
WHERE product_num = 10;
DROP VIEW customer_order;
18
CREATE/DROP TRIGGER
CREATE TRIGGER trigger2
BEFORE UPDATE ON product_tbl
REFERENCING NEW AS NEWROW
FOR EACH ROW
WHEN (NEWROW.qty_on_hand < 0)
SET NEWROW.qty_on_hand = 0;
DROP TRIGGER trigger2
19
Select Statement
20
SELECT Statement
SELECT [ DISTINCT | ALL ]
column_expression1, column_expression2, ....
[ FROM from_clause ]
[ WHERE where_expression ]
[ GROUP BY expression1, expression2, .... ]
[ HAVING having_expression ]
[ ORDER BY {column | expression} [asc | desc] ]
distinct keyword eliminates duplicates
21
SELECT Statement
Select * from customer_tbl;
22
FROM Clause
Comma delimited list of tables to retrieve
data from
With or without aliases
23
WHERE Clause
Determines exactly which rows are
retrieved
Qualifications in the where clause
Comparison operators (=,>,<, >=,<=)
Ranges (between and not between)
Character matches (like and not like)
Unknown values (is null and is not null)
Lists (in and not in)
Combinations of the above (and, or)
24
WHERE Clause
(Continued)
Not negates any Boolean expressions
and keywords such as like, null, between
and in
25
26
GROUP BY Clause
The group by function organises data into
groups based on the contents of a column(s)
Usually used with an aggregate function in the select
list
The aggregate is calculated for each group
All null values in the group by column are treated as
one group
Example: GROUP BY
Clause
select customer_num,
count(customer_num),
sum(quantity)
from order_tbl
group by customer_num
29
HAVING Clause
Set conditions on groups
Restricts groups
30
31
ORDER BY Clause
The order by clause sorts the query
results (in ascending order by default)
Items named in an order by clause need
not appear in the select list
When using order by, nulls are listed first
32
ORDER BY Clause
Example
select product_num,
quantity,
shipping_cost
from order_tbl
group by product_num,
quantity,
shipping_cost
having shipping_cost >
250
order by quantity,
shipping_cost;
33
Join Statement
34
Join Statement
Retrieves data from two or more tables
Combines tables by matching values
from rows in each table
Joins are done in the where clause
Columns in join don't have to be in select
35
36
37
Outer Joins
With a join, if one row of a table is
unmatched, row is omitted from result
table.
The outer join operations retain rows
that do not satisfy the join condition
List branches and properties that are in same
city along with any unmatched branches.
SELECT b.*, p.*
FROM branch1 b LEFT JOIN
property_for_rent1 p ON b.bcity = p.pcity;
38
Alias
40
Alias
Use of temporary names for tables
within a query
Can be used anywhere in query
Reduces amount of typing
ex. select pub_name, title_id
from titles t, publishers p
where t.pub_id = p.pub_id
41
Example: Alias
select type_code,
city,
region
from office_tbl;
42
43
Sub-Query
44
Sub-Queries
A select statement, used as an
expression in part of another select,
update, insert or delete
The sub-query is resolved first and the
results are substituted into the outer
query's where clause
Used because it can be quicker to understand
than a join
Perform otherwise impossible tasks (i.e. using
an aggregate)
45
Example: Sub-Query
select product_num,
description,
purchase_cost
from product_tbl
group by product_num,
description,
purchase_cost
having purchase_cost >
(select avg
(shipping_cost)
from order_tbl);
46
EXISTS cont.
select o.city,
s.first_name || ' '||
s.last_name
from sales_rep_tbl s,
office_tbl o
where s.office_num =
o.office_num
and exists
(select 1
from manufacture_tbl m
where m.city = o.city);
48
Union, Intersection
49
50
Union cont.
Difference is table containing all rows in
A but not in B.
Two tables must be union compatible.
(SELECT area
FROM branch
WHERE area IS NOT NULL) UNION
(SELECT area
FROM property_for_rent
WHERE area IS NOT NULL);
51
Comparison,
Character match,
Numerical Expression
52
Comparison Operators
=
equal to
> greater than
< less than
!=
not equal
<> not equal
53
Character Matches
Use to select rows containing field that
match specified portions of character
string
Use with character data only
Can use wildcards
%
Numerical Expressions
Numerical expressions can be used in
any numeric column or in any clause
that allows an expression
+
*
/
%
addition
subtration
multiplication
division
modulos
55
Aggregate
Functions
56
Aggregate Functions
count(*)
count(col_name)
max(col_name)
min(col_name)
sum(col_name)
avg(col_name)
57
NULL Values
A null value is an unknown value
null is a special value which means no
information available
is null should be used to match columns
contains null values
= null can also be used, but is not
recommended
One null value is never equal to another null
value
null's sort and group together
Some columns are defined to permit null
values
59
Insert, Update,
Delete
60
INSERT
INSERT INTO table_name [ ( col_name1, col_name2, .... ) ]
VALUES ( expression1_1, expression1_2, .... ),
( expression2_1, expression2_2, .... ), ....
INSERT INTO table_name [ ( col_name1, col_name2, .... ) ]
SELECT ...
INSERT INTO table_name
SET col_name1 = expression1, col_name2 = expression2, ....
61
INSERT cont.
The column list is optional.
If omitted, SQL assumes a list of all
columns in their original CREATE
TABLE order.
Any columns omitted must have been
declared as NULL when table was
created, unless DEFAULT was specified
when creating column.
62
INSERT cont.
Data value list must match column list as
follows:
Number of items in each list must be the same.
Must be direct correspondence in position of items
in two lists.
Data type of each item in data_value_list must be
compatible with data type of corresponding column.
63
INSERT Examples
Not specifying column names:
INSERT INTO Dept VALUES (1, 'Engineering', ProjectSet());
Specifying column names:
INSERT INTO staff (sno, fname, lname, position, salary, bno)
VALUES ('SG44', 'Anne', 'Jones', 'Assistant', 8100, 'B3');
Insert using a select statement
INSERT INTO stores (store_name, total_sales)
SELECT ...
64
UPDATE
UPDATE table_name
SET col_name1 = expression1, col_name2 = expression2, ....
[ WHERE expression ]
[ LIMIT limit_amount ]
SET clause specifies names of one or more columns that are to
be updated.
Where clause is optional.
If omitted, named columns are updated for all rows in
table.
65
Update Example
UPDATE emp
SET sal = sal * 1.1
WHERE empno NOT IN (SELECT empno FROM bonus);
UPDATE staff
SET salary = salary*1.05
WHERE position = 'Manager';
66
DELETE
DELETE FROM table_name
[ WHERE expression ]
[ LIMIT limit_amount ]
where is optional; if omitted, all rows are deleted from table. This
does not delete table. If the where is specified, only those rows
that satisfy condition are deleted.
67
DELETE examples
delete from store where store_num = 221;
Delete all information from the store table:
delete from store;
68
69
Declaration
character
CHAR, VARCHAR
bit
numeric
approx. numeric
datetime
70
Passion!
71