0% found this document useful (0 votes)
8 views99 pages

Ivy Ms-Access SQL Slides v6

The document provides an overview of SQL, detailing different types of SQL statements including DDL, DML, and DCL. It explains the basic structure of SQL queries, including how to create, modify, and delete database structures, as well as how to manipulate data. Additionally, it includes examples of SQL queries and important points regarding syntax and data types.

Uploaded by

coderdnk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views99 pages

Ivy Ms-Access SQL Slides v6

The document provides an overview of SQL, detailing different types of SQL statements including DDL, DML, and DCL. It explains the basic structure of SQL queries, including how to create, modify, and delete database structures, as well as how to manipulate data. Additionally, it includes examples of SQL queries and important points regarding syntax and data types.

Uploaded by

coderdnk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

SQL QUERY

1
SQL Agenda
What is SQL?

Different SQL Statement Types

• DDL Statements
• DML Statement
• DCL Statements

DML Statements

• Basic SQL Query Structure


• Comparison, Grouping, Ordering, Joins
• Multiple Tables

DDL Statements

• CREATE, ALTER, DROP

2
SQL Overview
Creating CREATE
Structure

Modifying
DDL ALTER
Structure

Delete DROP
Structure

Populate INSERT

SQL UPDATE / UPDATE Student SET FullName =


DML Manipulate DELETE ‘Amit Kr’ WHERE ID = 3

SELECT FullName FROM Student


Query SELECT
WHERE Mtest>90

GRANT
DCL Access
REVOKE

3
1 Introduction to SQL
What is SQL?
– When a user wants to get some information
from a database file, he can issue a query.
– A query is a user–request to retrieve data or
information with a certain condition.
– SQL is a query language that allows user to
specify the conditions. (instead of algorithms)

4
1 Introduction to SQL
Concept of SQL

– The user specifies a certain condition.


– The program will go through all the records
in the database file and select those records
that satisfy the condition.(searching).
– Statistical information of the data.

5
1 SQL Statement Types
• Data Definition Lang. (DDL) for defining
relations, views, integrity constraints
• Data Manipulation Lang. (DML) for
updating and querying
• Database Control Lang. (DCL) for
defining access rights, concurrency
control, etc.

6
DATA MANIPULATION LANG.

7
2 Basic structure of an SQL
query
General SELECT, ALL / DISTINCT, *,
Structure AS, FROM, WHERE

Comparison IN, BETWEEN, LIKE "% _"

Grouping GROUP BY, HAVING,


COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )

Display Order ORDER BY, ASC / DESC

Logical AND, OR, NOT


Operators

Output INTO TABLE / CURSOR


TO FILE [ADDITIVE], TO PRINTER, TO SCREEN

Union UNION

8
Important Points
• Ideal Steps to Write the SQL SELECT Stmt
1. Visualize the Final Report (answer)
2. Think of the Execution Sequence
3. Then, Write the SQL SELECT Statement

• SQL is NOT Case-Sensitive

9
Important Points
• SQL is not Case-Sensitive, but spelling sensitive
• You can’t write more than ONE SQL Stmt in one
window (in Access)
• Any function –
– A function looks like -> funcName()
– It will always return something
– Some functions accept parameters or arguments. Eg.
Round(8.89, 1) -> 8.9
– Please note – a function will have always have a pair
of bracket as suffix
10
Important Point – Contd.
• How to handle cell values in SQL –
– Numbers – directly without quotes
– Text / Char – with a pair of single or double quotes
(ex – FullName = ‘Matt Haden’)
– Date – with a pair of # (ex: DOB = #01/12/2008#)
– Boolean (Yes/No)– Compare Boolean fields with
Yes/No or True/False or 1/0. Don’t use quotes.
(Wrong -> Remission = ‘No’)
– Please note – Don’t address a field (column name.
ex: FullName) with any quotes or #. (Wrong - #DOB#
= #01/12/2008#)
11
2 The Situation:
Student Particulars
field type width contents
id numeric 4 student id number
name character 10 name
dob date 8 date of birth
sex character 1 sex: M / F
class character 2 class
hcode character 1 house code: R, Y, B, G
dcode character 3 district code
remission logical 1 fee remission
mtest numeric 2 Math test score

12
Try these..
1. List the female students who have scored less
than 92 in Maths
2. List the students who were born before
01/01/2000 (hint: use # for date values)
3. List the students who have not paid their fees
4. List the students who come from district YMT
5. Find the age of students (hint: use date()
function)
6. Show the age in the following format: years in
one column and the month in another. (HW)
13
I General Structure

SELECT ...... FROM ...... WHERE ......


SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
FROM tablename WHERE condition

14
I General Structure
SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
FROM tablename WHERE condition
– The query will select rows from the source tablename
and output the result in table form.
– Expressions expr1, expr2 can be :
• (1) a column, or
• (2) an expression of functions and fields.

– And col1, col2 are their corresponding column names


in the output table.

15
I General Structure
SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
FROM tablename WHERE condition
– DISTINCT will eliminate duplication in the output
while ALL will keep all duplicated rows.
– condition can be :
• (1) an inequality, or
• (2) a string comparison
• using logical operators AND, OR, NOT.

16
I General Structure

eg. 1 List all the student records.


SELECT * FROM student

id name dob sex class mtest hcode dcode remission


Result 9801 Peter 06/04/86 M 1A 70 R SSP .F.
9802 Mary 01/10/86 F 1A 92 Y HHM .F.
9803 Johnny 03/16/86 M 1A 91 G SSP .T.
9804 Wendy 07/09/86 F 1B 84 B YMT .F.
9805 Tobe 10/17/86 M 1B 88 R YMT .F.
: : : : : : : : :
17
I General Structure
eg. 2 List the names and house code of 1A students.

SELECT name, hcode, class FROM student


WHERE class="1A"

Class Class
1A  1A
1A
class="1A"
 1A
1A  1A
1B  1B
1B  1B
: :

18
I General Structure
eg. 2 List the names and house code of 1A students.

Result name hcode class


Peter R 1A
Mary Y 1A
Johnny G 1A
Luke G 1A
Bobby B 1A
Aaron R 1A
: : :

19
I General Structure
eg. 3 List the residential district of the Red House
members.
SELECT DISTINCT dcode FROM student
WHERE hcode="R"
dcode
Result
HHM
KWC
MKK
SSP
TST
YMT
20
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.

1B Girls ?

21
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.

Condition for "1B Girls":


1) class = "1B"
2) sex = "F"
3) Both ( AND operator)
22
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.

What is "age"?

23
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.

Functions:
# days : DATE( ) – dob
# years :(DATE( ) – dob) / 365
1 d.p.: ROUND(__ , 1)

24
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.

SELECT name, ROUND((DATE( )-dob)/365,1) AS age


FROM student WHERE class="1B" AND sex="F"

Result name age


Wendy 12.1
Kitty 11.5
Janet 12.4
Sandy 12.3
Mimi 12.2

25
I General Structure
eg. 5 List the names, id of 1A students with no fee
remission.
SELECT name, id, class FROM student
WHERE class="1A" AND Remission=False
name id class
Result Peter 9801 1A
Mary 9802 1A
Luke 9810 1A
Bobby 9811 1A
Aaron 9812 1A
Ron 9813 1A
Gigi 9824 1A
: 26 : :
II Comparison
expr IN ( value1, value2, value3)
expr BETWEEN value1 AND value2
expr LIKE “*P“
expr NOT LIKE “*P“

27
Try these..
1. Find the students who have IDs in the
following set – 1,5,9
2. List the names of the students who are
playing a musical instrument (Hint: refer
to Music and Student tables both)

28
II Comparison
eg. 6 List the students who were born on Wednesday
or Saturdays.
SELECT name, class,WeekdayName(weekday(dob),1) AS
bdate FROM student
WHERE WeekDayname(WeekDay(dob)) IN (‘Wednesday’,
‘Saturday’)
name class bdate
Result Peter 1A Wednesday
Wendy 1B Wednesday
Kevin 1C Saturday
Luke 1A Wednesday
Aaron 1A Saturday
: : :
29
II Comparison
eg. 7 List the students who were not born in January,
March, June, September.
SELECT name, class, MonthName(Month(DOB))
FROM student
WHERE MONTH(dob) NOT IN (1,3,6,9)
name class dob
Result Wendy 1B July
Tobe 1B October
Eric 1C May
Patty 1C August
Kevin 1C November
Bobby 1A February
Aaron 1A August
: : :

30
II Comparison

eg. 8 List the 1A students whose Math test score is


between 80 and 90 (incl.)
SELECT name, mtest FROM student
WHERE class="1A" AND
mtest BETWEEN 80 AND 90

Result name mtest


Luke 86
Aaron 83
Gigi 84

31
II Comparison
eg. 9 List the students whose names start with "T".

SELECT name, class FROM student


WHERE name LIKE "T*"

Result name class


Tobe 1B
Teddy 1B
Tim 2A

32
II Comparison

eg. 10 List the Red house members whose names contain


"a" as the 2nd letter.

SELECT name, class, hcode FROM student ;


WHERE name LIKE ‘?a*’ AND hcode=‘R’

name class hcode


Result
Aaron 1A R
Janet 1B R
Paula 2A R

33
Practice Like Queries
1. List the students whose names contain E
2. List the students who come from Districts ending
with T
3. List the students whose names contain B as the
second last letter
4. List the students who come from districts with M as
the third character
5. List the students who don’t contain ‘A’ and ‘R’ in
their names.
6. List the students who contain only “A” or “B” or “C”
or “D”
34
III Grouping
SELECT ...... FROM ...... WHERE condition ;
GROUP BY groupexpr [HAVING requirement]

Group functions:
COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )

– groupexpr specifies the related rows to be grouped


as one entry. Usually it is a column.
– WHERE condition specifies the condition of
individual rows before the rows are group.
HAVING requirement specifies the condition
involving the whole group.
35
III Grouping
eg. 11 List the number of students of each class.

36
Group By Class
class
1A

1A 1A
1A
COUNT( )

1B
1B
1B COUNT( )
1B 1B
1B
1B
1C

1C 1C
1C
COUNT( )

Student
37
III Grouping
eg. 11 List the number of students of each class.
SELECT class, COUNT(*) FROM student
GROUP BY class
class cnt
Result 1A 10
1B 9
1C 9
2A 8
2B 8
2C 6
38
III Grouping
eg. 12 List the average Math test score of each class.

39
Group By Class
class
1A

1A 1A AVG( )
1A
1B
1B

1B
1B AVG( )
1B
1B
1B
1C

1C 1C AVG( )
1C
Student
40
III Grouping
eg. 12 List the average Math test score of each class.

SELECT class, AVG(mtest) FROM student


GROUP BY class

class avg_mtest
Result 1A 85.90
1B 70.33
1C 37.89
2A 89.38
2B 53.13
2C 32.67
41
III Grouping
eg. 13 List the number of girls of each district.

SELECT dcode, COUNT(*) FROM student ;


WHERE sex="F" GROUP BY dcode

Result dcode cnt


HHM 6
KWC 1
MKK 1
SSP 5
TST 4
YMT 8
42
III Grouping
eg. 14 List the max. and min. test score of Class 1
students of each district.
SELECT MAX(mtest), MIN(mtest), dcode
FROM student
WHERE class LIKE ‘1[a-z]’ GROUP BY dcode
max_mtest min_mtest dcode
Result 92 36 HHM
91 19 MKK
91 31 SSP
92 36 TST
75 75 TSW
88 43 38 YMT
III Grouping
eg. 15 List the average Math test score of the boys in
each class. The list should not contain class with
less than 3 boys.
SELECT AVG(mtest), class FROM student
WHERE sex="M" GROUP BY class
HAVING COUNT(*) >= 3
Result avg_mtest class
86.00 1A
77.75 1B
35.60 1C
86.50 2A
56.50
44
2B
IV Display Order
SELECT ...... FROM ...... WHERE ......
GROUP BY ..... ;
ORDER BY colname ASC / DESC

45
IV Display Order
eg. 16 List the boys of class 1A, sorted by their names.

SELECT name, id FROM student ;


WHERE sex="M" AND class="1A" ORDER BY name

name id Result name id


Peter 9801 Aaron 9812
Johnny 9803 ORDER BY Bobby 9811
Luke 9810 Johnny 9803
name
Bobby 9811 Luke 9810
Aaron 9812 Peter 9801
Ron 9813 Ron 9813

46
IV Display Order
eg. 17 List the 1B students by their residential district.
SELECT name, id, class, dcode FROM student ;
WHERE class=“1B" ORDER BY dcode
Jimmy 9712 1B HHM
Result Tim 9713 1B HHM
Samual 9714 1B SHT
Rosa 9703 1B SSP
Helen 9702 1B TST
Joseph 9715 1B TSW
Paula 9701 1B YMT
Susan 9704 1B YMT

47
IV Display Order
eg. 18 List the number of students of each district
(in desc. order).
SELECT COUNT(*) AS Cnt, dcode FROM student
GROUP BY dcode ORDER BY COUNT(*) DESC

Result
cnt docode
11 YMT
10 HHM
10 SSP
9 MKK
5 TST
2 TSW
1 KWC
1 MMK
1 SHT
48
IV Display Order
eg. 19 List the boys of each house sorted by the
classes. (2-level ordering)

SELECT name, class, hcode FROM student ;


WHERE sex="M" ORDER BY hcode, class

49
IV Display Order
Result
name hcode class
Blue
Bobby B 1A
House Teddy B 1B Order
Joseph B 2A by
Zion B 2B class
Order
Leslie B 2C
by Johnny G 1A
hcode Luke G 1A
Kevin G 1C
Green
House George G 1C
: : :
:
:
50
V Top
SELECT TOP 2 * FROM ... WHERE .....
SELECT TOP 10 Percent * FROM ...

• The TOP clause is used to specify the number of records to


return.
• The TOP clause can be very useful on large tables with
thousands of records. Returning a large number of records
can impact on performance.

51
V TOP
eg. 20 List the girls students who are in the top 10% in
class 1A

SELECT Top 10 Percent *


FROM Student WHERE Class = '1A' and Sex = 'F‘
ORDER BY ((MTest + PTest) / 2) DESC

52
Home Work
H/W Find the second rank holder.
H/W How many students have unique names? (Not,
who have unique names)

53
VI Mid()
SELECT MID(col_name, start [,length])
FROM ...

• The MID() function is used to extract characters from a


text field.

col_name Required. The field to extract characters from


start Required. Specifies the starting position (starts at 1)
length Optional. The number of characters to return. If omitted,
the MID() function returns the rest of the text

54
V MID()
eg. 21 List the fist initial of all the students coming from
YMT

SELECT MID(FullName, 1, 1) AS FirstCharacter,


Dcode FROM Student WHERE Dcode = ‘YMT’

55
Some More Text Functions
• UCASE(textField1) : Will change the field1 to Upper case
• LCASE(textField1) : Will change the textField1 to Lower
Case
• LEN(textField1) : Will give you the length of a text field
• RIGHT(textField1, position) : Will return right characters
from the position
• LEFT(textField1, position) : Will return left characters from
the position
• REPLACE(textField,”string_to_replace”,”replacement_strin
g”,[Start_Position],[Occurances_To_Replace])
• INSTR([Start Position], TextField, “StringToFind”) – Finds
the position of a char in a string.
56
Text Exercises

1. Display the entire name but the last character


of students
2. Display the last two characters of the students’
name
3. Do the first question using Mid function
4. Do the second question using Mid function
5. Show the fullname in Upper Case
6. Select students whose name contain a single
“e”.
57
3 Union, Intersection and
Difference of Tables
The union of A and B (AB)

A B

A table containing all the rows from A and B.


58
3 Union, Intersection and
Difference of Tables
The intersection of A and B (AB)

A B

A table containing only rows that appear in both A and B.


59
3 Union, Intersection and
Difference of Tables
The difference of A and B (A–B)

A B

A table containing rows that appear in A but not in B.


60
Some more..
• Exists
• Not Exists
• IIF(condition, Value_if_True,Value_if_False)
– Eg: Select FullName, IIF(Mtest>90,
“Scholar”,”Dumb”) FROM Student
• Case and When
– Eg: proc sql;
– select *, case
when degrees 80 then 'Hot'
when degrees < 40 then 'Cold'
else 'Mild'
end
from temperatures;
61
3 The Situation:
Bridge Club & Chess Club
Consider the members of the Bridge Club and
the Chess Club. The two tables have the same
structure:

field type width contents


id numeric 4 student id number
name character 10 name
sex character 1 sex: M / F
class character 2 class

62
Try these..
1. Students who are playing either Chess or
Bridge or both
2. Students who are playing both – Chess
and Bridge
3. Students who are playing only Chess
4. Students who are playing either Chess or
Bridge, but not both

63
3 Union, Intersection and
Difference of Tables
Bridge [A] Chess [B]
id name sex class id name sex class
1 9812 Aaron M 1A 1 9802 Mary F 1A
2 9801 Peter M 1A 2 9801 Peter M 1A
3 9814 Kenny M 1B 3 9815 Eddy M 1B
4 9806 Kitty F 1B 4 9814 Kenny M 1B
5 9818 Edmond M 1C 5 9817 George M 1C
: : : : : : : :

64
3 Union, Intersection and
Difference of Tables
SELECT ...... FROM ...... WHERE ......
UNION
SELECT ...... FROM ...... WHERE ......

eg. 22 The two clubs want to hold a joint party.


Make a list of all students. (Union)
SELECT * FROM bridge
Result
UNION
SELECT * FROM chess
ORDER BY class, name

65
3 Union, Intersection and
Difference of Tables
SELECT ...... FROM table1 ;
WHERE col IN ( SELECT col FROM table2 )

eg. 23 Make a list of students who are members of both


clubs. (Intersection)

Result SELECT * FROM bridge


WHERE id IN ( SELECT id FROM chess ) ;

66
3 Union, Intersection and
Difference of Tables
SELECT ...... FROM table1 ;
WHERE col NOT IN ( SELECT col FROM table2 )

eg. 24 Make a list of students who are members of the


Bridge Club but not Chess Club. (Difference)

Result SELECT * FROM bridge ;


WHERE id NOT IN ( SELECT id FROM chess ) ;

67
H/W Exercise
• List the students who are playing only one
of the games

68
Multiple IN Statements Problem
• Select PubID, PubName From Publisher WHERE PubID
IN (SELECT PID From Books WHERE ISBN IN
(SELECT ISBN from Auth_Books WHERE AID IN
(Select AID From Authors WHERE AName =
‘Ramesh’)))

69
4 Multiple Tables:
• SQL provides a convenient operation to
retrieve information from multiple tables.

• This operation is called join.

• The join operation will combine the tables into


one large table with all possible combinations
(Math: Cartesian Product), and then it will filter
the rows of this combined table to yield useful
information.

70
4 Multiple Tables:

field1 field2
A 1
field1 field2
A 2
A 1
A 3
B 2
B 1
3
B 2
B 3

71
4 The Situation:
Music Lesson
Each student should learn a musical instrument.
Two tables: student & music
The common field: student id

field type width contents


id numeric 4 student id number
type character 10 type of the music instrument

72
4 Natural Join
A Natural Join is a join operation that joins two
tables by their common column. This operation
is similar to the setting relation of two tables.

SELECT a.comcol, a.col1, b.col2, expr1, expr2


FROM table1 a, table2 b
WHERE a.comcol = b.comcol

73
4
eg. 25
Natural Join
Make a list of students and the instruments they
learn. (Natural Join)
id name class id type

Same id 9801
9801

Join
Student Music

id name class type

9801
74
Product
4
eg. 25
Natural Join
Make a list of students and the instruments they
learn. (Natural Join)
SELECT s.class, s.name, s.id, m.type ;
FROM student s, music m ;
WHERE s.id=m.id ORDER BY class, name
class name id type
Result 1A Aaron 9812 Piano
1A Bobby 9811 Flute
1A Gigi 9824 Recorder
1A Jill 9820 Piano
1A Johnny 9803 Violin
1A Luke 9810 Piano
1A Mary 9802 Flute
: : : :
75
4 Natural Join
eg. 26 Find the number of students learning piano in
each class.

Three Parts :
(1) Natural Join.
(2) Condition: m.type="Piano"
(3) GROUP BY class

76
4 Natural Join
eg. 26

Student Join Condition Group By


m.type= "Piano" class
Product

Music

77
4 Natural Join
eg. 26 Find the number of students learning piano in
each class.
SELECT s.class, COUNT(*) ;
FROM student s, music m ;
WHERE s.id=m.id AND m.type="Piano" ;
GROUP BY class ORDER BY class
class cnt
Result 1A 4
1B 2
1C 1

78
H/W
• List the pair of students from the same
class (without any repetitions of the pairs).
(Hint: Inner Join the Student table with
itself)

79
4 Outer Join
An Outer Join is a join operation that includes
rows that have a match, plus rows that do not
have a match in the other table.

80
4 Outer Join
eg. 27 List the students who have not yet chosen an
instrument. (No match)

id name class id type

9801
No match

Student Music

81
4 Outer Join
eg. 27 List the students who have not yet chosen an
instrument. (No match)
SELECT class, name, id FROM student
WHERE id NOT IN ( SELECT id FROM music )
ORDER BY class, name
class name id
Result 1A Mandy 9821
1B Kenny 9814
1B Tobe 9805
1C Edmond 9818
1C George 9817
: : :
82
4 Outer Join
eg. 28 Make a checking list of students and the
instruments they learn. The list should also
contain the students without an instrument.
(Outer Join)

83
4 Outer Join
eg. 28

Natural Join

Outer Join

No Match

84
4 Outer Join
eg. 28 SELECT s.class, s.name, s.id, m.type
FROM student s, music m
WHERE s.id=m.id
UNION
SELECT class, name, id, ""
FROM student
WHERE id NOT IN ( SELECT id FROM music )
ORDER BY 1, 2;

85
4
class
Outer Join
name id type
class name id type
1A Aaron 9812 Piano
1A Bobby 9811 Flute 1A Aaron 9812 Piano
1A Gigi 9824 Recorder 1A Bobby 9811 Flute
1A Jill 9820 Piano 1A Gigi 9824 Recorder
1A Johnny 9803 Violin 1A Jill 9820 Piano
1A Luke 9810 Piano 1A Johnny 9803 Violin
1A Mary 9802 Flute 1A Luke 9810 Piano
: : : : 1A Mandy 9821
Natural Join 1A Mary 9802 Flute
1A Peter 9801 Piano
class name id
1A Mandy 9821
1A Ron 9813 Guitar empty
1B Eddy 9815 Piano
1B Kenny 9814
1B Tobe 9805 1B Janet 9822 Guitar
1C Edmond 9818 1B Kenny 9814
1C George 9817 1B Kitty 9806 Recorder
: : : : : : :
No Match 86 Outer Join
Try this.. (Full Join)
• List all the students and all the musical
instruments (Hint: Left Join Union Right
Join)

87
Union Exercise Answer:
• List the students who are playing only one
sport (either Chess or Bridge)
SELECT ID, FullName
FROM Chess
WHERE ID NOT IN (SELECT ID FROM Bridge)
UNION
SELECT ID, FullName
FROM Bridge
WHERE ID NOT IN (SELECT ID FROM CHESS)

88
INSERT, UPDATE, DELETE – DML
CREATE, ALTER, DROP - DDL

89
DDL Statements
• CREATE
• ALTER
• DROP

DML Statements

• INSERT
• UPDATE
• DELETE
90
Important Points
• Unlike DML stmts, you can’t hit-and-try
with DDL
• A DDL stmt, if successfully runs, doesn’t
give a warning
• A DDL stmt makes irreversible change to
the design of the database

91
CREATE (various ways)
• CREATE TABLE branch
(fname char(10),
city char(20),
director char(20),
assets integer,
Constraint CKFnameCity PRIMARY KEY (fname, city));
• CREATE TABLE AuthorsISBN
(AuthorsID INTEGER REFRENCES Authors(ID),
ISBN INTEGER REFRENCES Titles);
• CREATE TABLE Music
(ID INTEGER PRIMARY KEY,
Mtype CHAR(10),
StudID INTEGER,
CONSTRAINT FKSid FOREIGN KEY (StudID) REFRENCES Students(ID));

92
CREATE (One More Method)
• CREATE Table Student2
(ID Integer CONSTRAINT PkID PRIMARY
KEY,
StudRegn Integer CONSTRAINT
PKStudRegn PRIMARY KEY,
StudName Char(10) NOT NULL,
StudGPA Integer
)
93
CREATE (Yet Another Method)
• CREATE Table Student3
(ID Integer,
StudRegn Integer,
StudName Char(10) CONSTRAINT Snn
NOT NULL,
StudGPA Integer,
CONSTRAINT PKStudRegnID PRIMARY
KEY(ID, StudRegn)
) 94
SELECT INTO
• SELECT field1[, field2[, …]] INTO
newtable [IN externaldatabase] FROM
source
• Newtable – name of the new table that will be created
• Source – source table from where the columns and data will be
exported

95
Alter
• ALTER TABLE Student3 DROP Constraint
FKSid;

96
ALTER, DROP, INSERT,
UPDATE
• ALTER TABLE branch ADD zip INTEGER

• DROP TABLE branch

• INSERT INTO branch (name, director, city, assets)


VALUES (‘Clementi’, ‘Ng Wee Hiong’, ‘Singapore’,
3000000)

• UPDATE branch
Set city=‘New York’, Director =‘Peter’
Where director=‘Amit’;

97
INSERT INTO
• INSERT INTO target [(field1[, field2[, …]])]
[IN externaldatabase] SELECT
[source.]field1[, field2[, …] FROM
tableexpression

• INSERT INTO target [(field1[, field2[, …]])]


VALUES (value1[, value2[, …])

98
DELETE
• DELETE *
FROM Student
WHERE DOB < #01/01/1980#

• Remove the students who have scored


lesser among the same named
students. (HW)

99

You might also like