You are on page 1of 50

RDBMS-Day3

SQL
–Basic DDL statements
–DML statements
–Aggregate functions

1
SQL
SQL is a language that all commercial RDBMS implementations understand.

SQL is a non-procedural language

We would be discussing SQL with respect to oracle syntax

ER/CORP/CRS/DB07/003
Copyright © 2004, 2
Infosys Technologies Ltd Version No: 2.0

You can’t write programs like the ones you would have done using C langauge
You can only write questions in English like language called queries which will fetch some data rows
from the database.

2
Data types
Integer
Float
Char
Varchar2
Number
date

ER/CORP/CRS/DB07/003
Copyright © 2004, 3
Infosys Technologies Ltd Version No: 2.0

SQL supports various data types

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

Floating point numbers---- FLOAT

Fixed length character strings---- CHAR (len)


Fixed length character data of length len bytes. This should be used for fixed length data.

Variable length character strings --- Varchar2(len)


Variable length character string having maximum length len bytes. We must specify the size

Dates-----DATE

3
Constants/Literals
ANSI standard defines format for literals

Numeric: 21, -32, $0.75,1.2E4

String: enclosed within ‘ …’

Date : 12-mar-03*

ER/CORP/CRS/DB07/003
Copyright © 2004, 4
Infosys Technologies Ltd Version No: 2.0

•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.

4
Operators
Arithmetic operators like +,-,*,/
Logical operators: AND, OR
Relational operators: =,<=,>=, < >

ER/CORP/CRS/DB07/003
Copyright © 2004, 5
Infosys Technologies Ltd Version No: 2.0

The Arithmetic operators are used to calculate something like given in the example below:
Select * from employee where sal * 1.1 > 1000 ;

The logival operators are used to combine conditions like:

Select * from employee where (sal > 1000 AND age > 25);

The above two examples also illustrate use of relational operators

5
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

ER/CORP/CRS/DB07/003
Copyright © 2004, 6
Infosys Technologies Ltd Version No: 2.0

6
Statements
DDL
DML
DCL

ER/CORP/CRS/DB07/003
Copyright © 2004, 7
Infosys Technologies Ltd Version No: 2.0

SQL has three flavours of statements. The DDL, DML and DCL.
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
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
DCL is Data Control Language statements. Some examples:
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like what rollback segment to use

7
SQL-DDL

8
SQL - CREATE TABLE
Syntax:
CREATE TABLE tablename (column_name data_ type constraints, …)

Example:

CREATE TABLE Emp (

EmpNo short CONSTRAINT PKey PRIMARY KEY,


KEY,

EName VarChar(15),
VarChar(15),

Job Char(10)
Char(10) CONSTRAINT Unik1 UNIQUE,
UNIQUE,

Mgr short CONSTRAINT FKey1 REFERENCES EMP (EmpNo


(EmpNo),
),

Hiredate Date,
Date,

Sal single,
single,

Comm single,
single,

DeptNo short CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));


DEPT(DeptNo));

ER/CORP/CRS/DB07/003
Copyright © 2004, 9
Infosys Technologies Ltd Version No: 2.0

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.

9
SQL - ALTER TABLE
Add/Drop Column

Syntax:
ALTER TABLE tablename (ADD/DROP column_name)

ALTER TABLE EMP (ADD


ADD Grade short);

ALTER TABLE EMP (DROP


DROP Grade);

ER/CORP/CRS/DB07/003
Copyright © 2004, 10
Infosys Technologies Ltd Version No: 2.0

Used to modify the structure of a table by adding and removing columns

10
SQL - ALTER TABLE

Add/Drop Primary key

ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);

ALTER TABLE EMP DROP CONSTRAINT Pkey1;

ER/CORP/CRS/DB07/003
Copyright © 2004, 11
Infosys Technologies Ltd Version No: 2.0

11
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;

ER/CORP/CRS/DB07/003
Copyright © 2004, 12
Infosys Technologies Ltd Version No: 2.0

12
SQL - DROP TABLE
DROP TABLE
– Deletes table structure
– Cannot be recovered
– Use with caution

DROP TABLE EMP;;

ER/CORP/CRS/DB07/003
Copyright © 2004, 13
Infosys Technologies Ltd Version No: 2.0

13
Exercise

OFFICE SALESREP CUSTOMER


Works
Office in Empl-Num Has Cust_Num
City Name rep Cust_Name
Region Has Age Cust_Rep
Mgr Mgr Rep_Office Credit_Limit
Target Title
Sales Hire_Date
Manager Place
Quota d by
Taken
Sales by
ORDERS
PRODUCTS
Order_Num
Mfr_ID Order_Date
Product_ID Cust
Description Rep
Price Mfr
Is For
Qty_On_Hand Product
Qty
Amount

ER/CORP/CRS/DB07/003
Copyright © 2004, 14
Infosys Technologies Ltd Version No: 2.0

14
Exercise
Refer to the diagram in the previous slide. The relationships between entities are as
follows:

OFFICE (Mgr) -> SALESREP (Empl_Num)

SALESREP(Rep_Office)-> OFFICE ( Office)

SALESREP(Manager)-> SALESREP (Empl_Num)

CUSTOMER(Cust_Rep) -> SALESREP (Empl_Num)

ORDERS (Rep)-> SALESREP (Empl_Num)

ORDERS(Mfr)-> PRODUCTS (Mfr_ID)

ORDERS(product)-> PRODUCTS (Prod_ID)

Note: -> means “refers to “ in this context

ER/CORP/CRS/DB07/003
Copyright © 2004, 15
Infosys Technologies Ltd Version No: 2.0

Consider the two entities OFFICE and SALESREP


The Mgr column of OFFICE refers to the Empl_Num column of SALESREP and the Rep_Office column of
SALESREP refers to the Office column of the OFFICE Table.
We will not be able to define either foreign keys in the create statement because, the other table would not have
got created yet.
We would make use of the alter statement in this context

OFFICE
CREATE TABLE OFFICE (Office NUMBER, City CHAR(20), Region VARCHAR(10), Mgr NUMBER, Target
NUMBER, Sales NUMBER );

SALESREP

CREATE TABLE SALESREP ( Empl_Num NUMBER, Name VARCHAR(15), Age NUMBER,


Rep_Office NUMBER, Title VARCHAR(15), Hire_Date DATE,
Manager NUMBER CONSTRAINT FK1 REFERENCES SALESREP
(Empl_Num),
Quota NUMBER, Sales NUMBER );

To define the foreign keys:

ALTER TABLE OFFICE(ADD CONSTRAINT FK2 FOREIGN KEY(Mgr) REFERENCES SALESREP


(Empl_Num) );

ALTER TABLE SALESREP(ADD CONSTRAINT FK3 FOREIGN KEY(Rep_Office) REFERENCES


OFFICE(Office) );

15
SQL-DML

Here we will discuss about commands using which data from the tables would be extracted and
updated in different ways

16
SQL - INSERT INTO
Syntax: INSERT INTO tablename VALUES (value list)

Single-row insert

INSERT INTO S VALUES(‘S3’,’SUP3’,’BLORE’,10)


VALUES

Inserting one row, many columns at a time

INSERT INTO S (SNO, SNAME) VALUES (‘S1’


S1’, ‘Smith’
Smith’);

Inserting many rows, all/some columns at a time.

INSERT INTO NEW_SUPPLIER (SNO, SNAME)


SELECT SNO, SNAME
FROM S
WHERE CITY IN (‘BLORE’,’MADRAS’)

ER/CORP/CRS/DB07/003
Copyright © 2004, 17
Infosys Technologies Ltd Version No: 2.0

In the first format, we would pass values for all the columns in exactly the same order in which they
appear in the table

When we wish to insert values only for few selected columns. For e.g in a student table, we may
know only the name, age etc. but not the marks until the student completes the exam for the course
and receives the results. So, we may insert only values for name and age columns in this case. The
value of remaining columns will be represented as NULL by default.

Here in this third form , we copy data which is already in another table into this table as such

17
SQL - UPDATE
With or without WHERE clause
Syntax:
UPDATE tablename SET column_name =value [ WHERE condition]

Examples:

UPDATE S SET CITY = ‘KANPUR’ WHERE SNO=‘S1’

UPDATE EMP SET SAL = 1.10 * SAL

ER/CORP/CRS/DB07/003
Copyright © 2004, 18
Infosys Technologies Ltd Version No: 2.0

The examples are quite self explanatory

18
SQL - DELETE FROM
With or without WHERE clause

Syntax: DELETE FROM tablename WHERE condition

DELETE FROM SP WHERE PNO= ‘P1’

DELETE FROM SP

ER/CORP/CRS/DB07/003
Copyright © 2004, 19
Infosys Technologies Ltd Version No: 2.0

Delete all rows from Shipment table for all part number as P1

19
Supplier table - S

SNO SNAME STATUS CITY

S1 Smith 20 London
S2 Jones 10 Paris
S3 Blake 30 Paris
S4 Clark 20 London
S5 Adams 30 Athens

ER/CORP/CRS/DB07/003
Copyright © 2004, 20
Infosys Technologies Ltd Version No: 2.0

20
Product table - P

PNO PNAME COLOR WEIGHT CITY

P1 Nut Red 12 London


P2 Bolt Green 17 Paris
P3 Screw Blue 17 Rome
P4 Screw Red 14 London
P5 Cam Blue 12 Paris
P6 Cog Red 19 London

ER/CORP/CRS/DB07/003
Copyright © 2004, 21
Infosys Technologies Ltd Version No: 2.0

21
Shipment table - SP

SNO PNO QTY


S1 P1 300
S1 P2 200
S1 P3 400
S1 P4 200
S1 P5 100
S1 P6 100
S2 P1 300
S2 P2 400
S3 P2 200
S4 P2 200
S4 P4 300
S4 P5 400

ER/CORP/CRS/DB07/003
Copyright © 2004, 22
Infosys Technologies Ltd Version No: 2.0

22
Retrieving columns from a table

To select a particular column:


SELECT ColumnName FROM Tablename

To select set of column names,


SELECT column1, column2,… FROM TableName

To select all columns from a table:


SELECT * FROM TableName

ER/CORP/CRS/DB07/003
Copyright © 2004, 23
Infosys Technologies Ltd Version No: 2.0

Examples:
Get the names of all the suppliers
SELECT SNAME FROM S;

Get the names and city of all the suppliers


SELECT SNAME, CITY FROM S

Get full details for all Suppliers in S table


SELECT * FROM S

23
SQL - ALL, DISTINCT

Get all part numbers:

SELECT ALL PName FROM P

Get all distinct part numbers

SELECT DISTINCT PName FROM P

ER/CORP/CRS/DB07/003
Copyright © 2004, 24
Infosys Technologies Ltd Version No: 2.0

Distinct will filter repetitive occurrence of a particular value

24
Retrieving a subset of rows
For retrieval of rows based on some condition, the syntax is

SELECT COL1,COL2,.........

FROM TABLE NAME

WHERE < SEARCH CONDITION>

ER/CORP/CRS/DB07/003
Copyright © 2004, 25
Infosys Technologies Ltd Version No: 2.0

25
Relational operators
Get SNO for all suppliers in Paris

SELECT SNO
FROM S
WHERE CITY = ‘PARIS’

Relational = , < , > , <= , >= , != or < >


operator

ER/CORP/CRS/DB07/003
Copyright © 2004, 26
Infosys Technologies Ltd Version No: 2.0

26
Logical operators

Get SNO for all suppliers in Paris and status greater than 10

SELECT SNO
FROM S
WHERE CITY = ‘PARIS’ AND
STATUS >10

Logical operator: AND, OR, and NOT


ER/CORP/CRS/DB07/003
Copyright © 2004, 27
Infosys Technologies Ltd Version No: 2.0

27
Using logical operators..
Get PNO for parts whose weight is one of 12,16 or 17 ?

SELECT PNO
FROM P
WHERE WEIGHT=16 OR
WEIGHT =12 OR
WEIGHT = 17

ER/CORP/CRS/DB07/003
Copyright © 2004, 28
Infosys Technologies Ltd Version No: 2.0

28
Retrieval using BETWEEN

Get parts whose weight is in the range 16 to 19 (inclusive)

SELECT *
FROM P
WHERE WEIGHT BETWEEN 16
AND 19

ER/CORP/CRS/DB07/003
Copyright © 2004, 29
Infosys Technologies Ltd Version No: 2.0

29
Retrieval using IN
Get list of PNO for parts whose weight is one of 12, 16 or 17

SELECT PNO
FROM P
WHERE WEIGHT IN (12,16,17)

ER/CORP/CRS/DB07/003
Copyright © 2004, 30
Infosys Technologies Ltd Version No: 2.0

30
Retrieval using IN
Get the list of Supplier numbers in the cities ROME, PARIS ?

SELECT SNO
FROM S
WHERE CITY IN (‘PARIS’ ,’ROME’)

ER/CORP/CRS/DB07/003
Copyright © 2004, 31
Infosys Technologies Ltd Version No: 2.0

31
Retrieval using LIKE
Get all details of parts whose name begins with character C

SELECT *
FROM P
WHERE PNAME LIKE ‘C*’

SELECT *
FROM P
WHERE PNAME LIKE ‘C?’

ER/CORP/CRS/DB07/003
Copyright © 2004, 32
Infosys Technologies Ltd Version No: 2.0

32
SQL - Retrieval using IS NULL
Get PNO for parts whose weight is unknown (Blank or not added).

SELECT PNO
FROM P
WHERE WEIGHT IS NULL

ER/CORP/CRS/DB07/003
Copyright © 2004, 33
Infosys Technologies Ltd Version No: 2.0

33
SQL - Retrieval using NOT NULL

Get all details of shipments whose quantity is known

SELECT *
FROM SP
WHERE QTY IS NOT NULL

ER/CORP/CRS/DB07/003
Copyright © 2004, 34
Infosys Technologies Ltd Version No: 2.0

34
Column titles using AS

SELECT SNO AS [Supplier Number],


CITY AS [Supplier City]
FROM S

ER/CORP/CRS/DB07/003
Copyright © 2004, 35
Infosys Technologies Ltd Version No: 2.0

The name given in the square brackets will appear as title of that column in the final output.

35
SQL - Sorting your results

SELECT COL1,COL2,.......
FROM TABLE_NAME

WHERE <SEARCHCONDITION>

ORDER BY COL-NAME [DESC]

• by default the order is ASCENDING

ER/CORP/CRS/DB07/003
Copyright © 2004, 36
Infosys Technologies Ltd Version No: 2.0

36
Retrieval using ORDER BY

Get SNO and STATUS for suppliers in Paris in descending order of status

SELECT SNO, STATUS


FROM S

WHERE CITY=‘PARIS’

ORDER BY STATUS DESC

ER/CORP/CRS/DB07/003
Copyright © 2004, 37
Infosys Technologies Ltd Version No: 2.0

37
Retrieval using ORDER BY
SELECT CITY,COLOR,WEIGHT
FROM P
WHERE WEIGHT IN (12,17)
ORDER BY CITY,COLOR DESC

SELECT CITY,COLOR,WEIGHT
FROM P
WHERE WEIGHT IN (12,17)
ORDER BY 1 DESC,
DESC 2
ER/CORP/CRS/DB07/003
Copyright © 2004, 38
Infosys Technologies Ltd Version No: 2.0

When there are more than one column names specified in the ORDER BY clause, the results are sorted based on the
first column within which the rows are sorted on the second column … for example , in the query that’s given above,

ORDER BY city, color desc

Let us say the cities are like chennai, bangalore, pune, hydrabad, calcutta etc. then based on cities, the rows will be
sorted as

Bangalore
Calcutta
Chennai
Hydrabad etc.
Let us say there are 5 rows with bangalore as city and 56 rows with Calcutta as city …
Within these 5 rows, they will be arranged based on the color in descending order as say for e.g.

Yellow
Red
Green
Blue

So the display may look something like

Bangalore Yellow 87.6


Bangalore Red 45.8
Bangalore Green 32.6
Bangalore Blue 54.3
Bangalore Blue 43.2

Calcutta Yellow 34.5


….

38
Queries involving calculated values
Get PNO and WEIGHT in grams for all parts

SELECT PNO, WEIGHT*1000


FROM P

ER/CORP/CRS/DB07/003
Copyright © 2004, 39
Infosys Technologies Ltd Version No: 2.0

39
Queries involving strings
Get PNO and WEIGHT in grams for all parts

SELECT PNO AS [Part],


WEIGHT*1000 AS
[Weight in grams]
FROM P

ER/CORP/CRS/DB07/003
Copyright © 2004, 40
Infosys Technologies Ltd Version No: 2.0

40
Aggregate Functions

41
SQL - Aggregate functions

Used when information you want to extract from a table has to do with the
data in the entire table taken as a set.

Aggregate functions are used in place of column names in the SELECT


statement

The aggregate functions in sql are :

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

ER/CORP/CRS/DB07/003
Copyright © 2004, 42
Infosys Technologies Ltd Version No: 2.0

42
Aggregate function - SUM
Adds up the values in the specified column
Column must be numeric data type
Value of the sum must be within the range of that data type

Example:
Get total qty of P2 supplied

SELECT SUM (QTY)


FROM SP
WHERE PNO=‘P2’

ER/CORP/CRS/DB07/003
Copyright © 2004, 43
Infosys Technologies Ltd Version No: 2.0

43
Aggregate function - AVG
Returns the average of all the values in the specified column
Column must be numeric data type

Example:

Get average qty of shipment supplied by S1

SELECT AVG(QTY)
AVG
FROM SP
WHERE SNO=‘S1’

ER/CORP/CRS/DB07/003
Copyright © 2004, 44
Infosys Technologies Ltd Version No: 2.0

44
Aggregate function - MAX
Returns the largest value that occurs in the specified column
Column need not be numeric type

Example:

Get maximum qty of shipment supplied by S1

SELECT MAX(QTY)
MAX
FROM SP
WHERE SNO =‘S1’

ER/CORP/CRS/DB07/003
Copyright © 2004, 45
Infosys Technologies Ltd Version No: 2.0

45
Aggregate function - MIN
Returns the smallest value that occurs in the specified column
Column need not be numeric type

Get minimum qty of shipment supplied by S1

SELECT MIN(QTY)
MIN FROM SP
WHERE SNO=‘S1’

ER/CORP/CRS/DB07/003
Copyright © 2004, 46
Infosys Technologies Ltd Version No: 2.0

46
Aggregate function - COUNT
Returns the number of rows in the table

Get total number of suppliers

SELECT COUNT(*)
COUNT FROM S
Get number of shipments for P2

SELECT COUNT(Qty)
COUNT
FROM SP
WHERE PNO=‘P2’
Count(*) = No of rows
Count(QTY) = No. of rows that do not have NULL Value

ER/CORP/CRS/DB07/003
Copyright © 2004, 47
Infosys Technologies Ltd Version No: 2.0

47
Using two or more aggregate functions

SELECT MIN(Qty),
MIN MAX(QTY)
FROM SP
WHERE PNO=‘P2’

ER/CORP/CRS/DB07/003
Copyright © 2004, 48
Infosys Technologies Ltd Version No: 2.0

48
Summary of basic DDL and DML
Create , Alter and Drop are the DDL commands

Update, Insert into, Delete from are the basic DML commands that add or
remove data from tables

Select statement in its various flavours is used to retrieve information from the
table

Aggregate functions work on all the rows of the table taken as a group (based
on some condition optionally)

ER/CORP/CRS/DB07/003
Copyright © 2004, 49
Infosys Technologies Ltd Version No: 2.0

49
Thank You!

ER/CORP/CRS/DB07/003
Copyright © 2004, 50
Infosys Technologies Ltd Version No: 2.0

50

You might also like