Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Part I
Deleting a table
drop table t;
drop table customer;
truncate table t;
truncate table customer;
/* delete all records in the table but not the field definitions */
Add A Column
alter table t add (fx fd_type, fy fd_type);
alter table customer add (zip char(5), phone char(10));
Delete Records
delete from t where [conditions];
Update Records
update t set f1=newvalue, f2=newvalue where [conditions];
* from t;
* from t where [conditions];
f1, f2, ...from t;
f1, f2, ...from t where [conditions];
Conditions
Mathematical and Logical operators
=, <>, >, <, >=, <=, and, or, not
ex:
ex:
Wildcard
like
Order by
default is ascending.
Views
ex:
price>50;
select * from invent_2;
3
in
select sname from student where major in (IS,Finance);
Exercise 1.1
Write the SQL code to ...
1. Create a table named S with the following columns
S#
char(2)
SNAME
char(10)
STATUS
number(3,0)
2. Insert a supplier record into the S table. The suppliers s# is S1, SNAME is Smith, and
Status is 20.
3. Save the record to the S table.
4. Display all records of the S table.
5. Display the sname and status columns of the S table.
6. Insert another supplier record into the S table. The suppliers s# is S2, SNAME is
Jones, and Status is 10.
7. Display all records of the S table.
8. Undo the action of problem 6. (That is, un-insert S2.)
9. Display all records of the S table. What should you see?
10. Add a new column CITY to the S table. Its column definition is char(10).
11. Update supplier S1s city to be London and S2s city to be Paris. (Can you do it
in one SQL statement, or you need to write 2?)
12. Delete the record of supplier s2.
13. Undo the action of problem 12.
(Assume now that all three tables, S, P, and SP are in place, and they have records as
above.)
S
S
#
S
1
S2
S3
S4
S5
SNA
ME
Smit
h
Jones
Blake
Clark
Adam
s
STAT
US
20
10
30
20
30
CITY
Londo
n
Paris
Paris
London
Athens
P
P
#
P
1
P2
P3
P4
P5
P6
PNA
ME
Nut
Bolt
Scre
w
Scre
w
Cam
Cog
COL
OR
Red
Gree
n
Blue
Red
Blue
Red
WEIG
HT
12
17
17
14
12
19
CITY
Lond
on
Paris
Rome
Londo
n
Paris
Londo
n
SP
S# P#
QTY
S1
S1
S1
S1
S1
S1
S2
S2
S3
S4
S4
S4
300
200
400
200
100
100
300
400
200
200
300
400
P1
P2
P3
P4
P5
P6
P1
P2
P2
P2
P4
P5
DROP constraints:
alter table t2 drop primary key (f1,f2);
INSTRUCTOR
ssn char(9)
name
char(10)
primary key:
ssn
SECTIONS
call# char(5)
dept char(4)
code char(3)
sec# char(2)
i_ssn char(9)
7
(1) Write SQL statement to create the above 3 tables in sequence with proper
primary key and foreign key declarations.
(2) Write SQL statements to delete the above 3 tables in sequence.
...
...
...
...
...
...
count(field)
sum(field)
avg (field)
distinct(field)
max(field)
min(field)
Example:
Examples
SN COUNT(QTY)
-- ---------S1
6
S2
2
S3
1
S4
3
SQL> select snum, count(qty) from sp
2 group by snum
3 order by count(qty);
SN COUNT(QTY)
-- ---------S3
1
S2
2
S4
3
S1
6
SQL> select snum, sum(qty) from sp
2 group by snum;
SN SUM(QTY)
-- --------S1
1300
S2
700
S3
200
S4
900
SQL> select snum, sum(qty) from sp
2 group by snum
3 having count(qty)>=2;
SN SUM(QTY)
-- --------S1
1300
S2
700
S4
900
Exercise 3.1
1. Display the number of times each supplier supplies parts, sorted by the highest
number to the lowest.
2. Display the number of times each supplier supplies parts, sorted by the
supplier's number.
3. Display the average quantity each supplier supplies parts.
4. Display the total quantity each supplier supplies parts.
10
5. Display the total quantity each supplier supplies parts for suppliers who have
placed 3 or more times of orders
6. Display the number of times each part has been supplied.
Display the number of times each part has been supplied, sorted by the highest
number to the lowest.
7. Display the average quantity that each part has been supplied.
8. Display the total quantity each part has been supplied, sorted by part number.
9. Display the average quantity that each part has been supplied for parts which
average quantity order is less than 300.
10. Display the total quantity supplied by S1.
11. Display the overall average quantity supplied.
12. Display the highest and lowest quantity supplied by each supplier.
13. Display suppliers whose average quantity is less or equal to 250.
14. Display suppliers who have the highest average quantity.
11
The USER_TAB_COLUMNS
SQL> SELECT table_name, column_name, data_type from
user_tab_columns;
Table
Name
COLUMN_NAM DATA_TYPE
---------- ---------- --------C
CALL#
CHAR
C
DEPT
CHAR
C
CODE
CHAR
C
TITLE
CHAR
COUNTER TYPE
CHAR
COUNTER MAXNUM
NUMBER
ENG
SNUM
CHAR
ENG
SNAME
CHAR
G
S#
CHAR
G
CALL#
CHAR
G
GRADE
CHAR
G
GRADEPT NUMBER
.....
column
column
column
column
column
column
SQL>
SQL> select owner, constraint_name, constraint_type, table_name,
r_owner,
2
r_constraint_name from user_constraints;
R
Cons
Cons
Table
Cons
OWNER
Name
Type
Name
R_OWNER Name
---------- --------------- --------------- ---------- ---------- --------------SOPHIE
SYS_C00403
P
ORD
SOPHIE
ORDER_PS
R
ORD
SOPHIE
SYS_C00400
SOPHIE
SYS_C00374
P
P
SOPHIE
SYS_C00398
P
PRODUCT
SOPHIE
SYS_C00400
P
SP
SOPHIE
SP_P
R
SP
SOPHIE
SYS_C00398
SOPHIE
SP_S
R
SP
SOPHIE
SYS_C00399
SOPHIE
SYS_C00399
P
SUPPLIER
8 rows selected.
Note: P=Primary Key; R=Foreign Key
13
press [tab]
press [tab]
press [enter]
14
NAME
---------Andy
Betty
MAJOR
---------IS
finance
SQL>
SQL> Input truncated to 9 characters
spool off
Your execution should look similar to this. Scroll the window up or [PageUp] to
check your execution. If you do not see any problems, thats great! You can go
directly to Step 5. Otherwise, you need to debug your program. Go to Step 4.
16
now choose File - Save. Specify the new file name to be a:myprog2.sql.
Go back to Oracle SQL*Plus.
To run your program, at the SQL prompt, enter
SQL> start a:myprog2.sql
Note: Usually people write commands in a text file so they can be executed
together. The program is sometimes called a "script". If you have several
commands that you are likely to rerun them in your future, it is better to write
them in a script file so you do not have to type them over and over again.
However, if you just want to check something quickly, you can enter the
command directly at the SQL> prompt.
Exercise 5.1
Make sure you can do the following without any problem.
1. Write the following SQL codes in a myprog3.sql file. Make sure you have set
echo on in the beginning of the file. Also, spool your output to a file named
myprog3.txt.
select * from stu;
select * from stu where ssn=333;
select ssn, name from stu where ssn=333;
Exercise 5.2
Copy the SUPPLIER, PARTS, and SP tables from my account by the following
commands:
SQL> create table supplier as select * from sophie.supplier;
Table created.
SQL> create table parts as select * from sophie.parts;
Table created.
SQL> create table sp as select * from sophie.sp;
Table created.
19
ex.
prompt
prompt Processing.... please wait....
prompt ----------- Please Detach Along This Line ----------------
pause prompt
ex.
pause Please press [Enter] to continue ...
accept variable prompt 'prompt';
ex.
'&variable'
&variable
select 'text', f1, f2, ... from t where [conditions];
select text from t where [conditions];
ex. select 'Customer Name: ', cname from customer where cnum='&cnum';
ex.
is not null;
select The Order Has Been Processed! from transaction where tran#
File Structure
SQL> select * from s;
S# SNAME
STATUS
--- ---------- ---------001 John
Senior
002 Mary
Junior
003 Joe
Senior
004 Jim
Sophomore
20
Oracle Code
set
set
set
set
feedback of
echo of
verify of
heading of
prompt
prompt *--- Welcome to the Student Information Program ---*
prompt
prompt
accept xsnum prompt 'Please Enter the Student ID: ';
select 'The Student Name is: ', sname from s
where s#='&xsnum';
select 'The Student is a ', status from s
where s#='&xsnum';
pause Press [Enter] to continue...
21
Exercise 6.1
Write the SQL code to do the following:
1. System prompts
Welcome to the Registration System
2. System prompts
Please enter the Student's ID:
3. System displays the student's name according to the sid entered by the user.
5. System prompts
Are you sure? ** Press [Enter] to continue or [ctrl][c] twice to abort...
and pause
Exercise 5.2
1. System prompts
New Student ID:
2. System prompts
New Student Name:
22
3. System inserts new ID and new name into the STUDENT table
23
Character Functions
A||B or concat(A,B)
ex:
select Student Name is: ||sname from STUDENT;
initcap(gOOd morNING) returns
lower(gOOd morNING) returns
ltrim(0011-12110, 0) returns
rtrim(0011-12110) returns
rtrim(0011-12110, 0) returns
substr(0011-12110,5,3) returns
instr(0011-12110,-) returns
length(0011-12110) returns
Numeric Functions
ceil(3.45) returns
floor(3.45) returns
mod(9/4) returns
round(123.45) returns
round(123.65) returns
round(123.45,1) returns
Date Functions
sysdate returns
24
sysdate - 1 returns
sysdate + 1 returns
to_date(10/01/2000,mm/dd/yyyy) returns
to_date(10/01/2000,dd/mm/yyyy) returns
Other Functions
decode(grade,A,4,B,3,C,2,D,1,F,1,Not a Valid Grade)
Others
rownum
select * from transaction
where rownum < 10
order by amount desc;
in
select sname from student where major in (IS,Finance);
25
Create Sequence
create sequence transaction_number start with 10000;
insert into trans values (transaction_number.nextval, ......);
select Transaction_Number.currval from dual;
Exercise 7.1
1. What does the following code return?
SELECT decode (Core_Num, 00000000, NULL, Core_Num) from Product;
4. Write one SQL statement to display the last character of a students last name.
(LASTNAME is a column of the STUDENT table).
5. The student table has three columns: SSN, LASTNAME, and USERNAME. A
students username starts with the letter Z, followed by the first 2 letters of his
last name, and the last 4 digits of his SSN. Currently the USERNAME column is
null. Write one SQL statement to populate the USERNAME column.
6. (In addition to requirements of the previous question) If a student does not
have a SSN, then leave the USERNAME value NULL. Write one SQL statement to
populate the USERNAME column.
7. Write one SQL statement to display the last 2 digits of Prod_Number; if
Prod_Number is NULL, then display XX.
8. The CUSTOMER table has three columns: ACCOUNT_NUMBER, PREFIX, and
SUFFIX. There is always a - in the account number, but the position differs by
customer. Prefix is the portion of the account number before the - and suffix is
the portion after the -. Write one SQL command to populate the prefix and
suffix columns.
26
27
Topic 8. Subqueries
SELECT...
UPDATE...
DELETE...
where snum = (select snum from .... where....);
SELECT...
UPDATE...
DELETE...
where snum in (select snum from .... where....);
Exercise 8.2
1. Upgrade supplier status to 30 for suppliers who have supplied more than 500
units of parts.
2. Upgrade supplier status by 5 (i.e., if it was 10 before, than upgrade it to 15; if it
was 15 before than upgrade it to 20, etc.) for suppliers who have supplied more
than 500 units of parts.
3. Upgrade supplier status to 5 for suppliers who have supplied parts to 2 or
more cities.
4. Display the total quantity each supplier supplies parts for suppliers who have
placed 3 or more times of orders
5. Display supplier who supplies the most average quantity.
28
STUDENT
SNU
M
1111
2222
3333
SNAM
E
Andy
Betty
Cinty
ENROLL
SNU
M
....
1111
1111
2222
2222
1111
1111
1111
2222
....
CALLNU
M
....
10110
10125
10110
10130
10135
10140
10155
10160
....
COURSE
GRAD
E
....
F
F
A
A
CALLNU
M
10110
10115
10120
10125
10130
10135
10140
10150
10155
10160
COURS
E
IS 380
IS 380
IS 480
IS 385
IS 385
IS 380
IS 380
IS 380
IS 385
IS 480
SECTIO
N
1
2
1
1
2
1
2
3
1
1
SEMESTE
R
Sp 2000
Sp 2000
Sp 2000
Sp 2000
Sp 2000
Fa 2000
Fa 2000
Fa 2000
Fa 2000
Fa 2000
Exercise 8.3
30
Part I.
1. Identify the Primary Key and Foreign Keys of the STUDENT, ENROLL, and
COURSE tables.
2. Write a program create.sql that creates the three tables STUDENT, ENROLL,
and COURSE in the correct sequence with appropriate primary key and foreign
key declaration.
3. Make sure you set echo on and spool. Run create.sql until there is no error.
Turn in a print out of your spool file.
Part II.
Assume you have entered data in the three tables.
3. Write a program query.sql that answers the questions
Exercise 5.3.
of
4. Make sure you set echo on and spool. Run query.sql until there is no error. Turn
in a print out of your spool file.
31