rdbms_day 3
TRANSCRIPT
1
RDBMS-Day3 SQL
–Basic DDL statements–DML statements–Aggregate functions
2
ER/CORP/CRS/DB07/003
Version No: 2.02Copyright © 2004,
Infosys Technologies Ltd
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
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.
3
ER/CORP/CRS/DB07/003
Version No: 2.03Copyright © 2004,
Infosys Technologies Ltd
Data types
IntegerFloatCharVarchar2Numberdate
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
4
ER/CORP/CRS/DB07/003
Version No: 2.04Copyright © 2004,
Infosys Technologies Ltd
Constants/Literals
ANSI standard defines format for literals
Numeric: 21, -32, $0.75,1.2E4
String: enclosed within ‘ …’
Date : 12-mar-03*
•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.
5
ER/CORP/CRS/DB07/003
Version No: 2.05Copyright © 2004,
Infosys Technologies Ltd
Operators
Arithmetic operators like +,-,*,/Logical operators: AND, ORRelational operators: =,<=,>=, < >
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
6
ER/CORP/CRS/DB07/003
Version No: 2.06Copyright © 2004,
Infosys Technologies Ltd
NULL
Missing/unknown/inapplicable data represented as a null valueNULL is not a data value. It is just an indicator that the value is unknown
7
ER/CORP/CRS/DB07/003
Version No: 2.07Copyright © 2004,
Infosys Technologies Ltd
Statements
DDLDMLDCL
SQL has three flavours of statements. The DDL, DML and DCL.DDL is Data Definition Language statements. Some ex amples: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 examp les: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
8
SQL-DDL
9
ER/CORP/CRS/DB07/003
Version No: 2.09Copyright © 2004,
Infosys Technologies Ltd
Example:Example:
CREATE TABLECREATE TABLE Emp (Emp (
EmpNoEmpNo short short CONSTRAINTCONSTRAINT PKeyPKey PRIMARY KEYPRIMARY KEY ,,
ENameEName VarCharVarChar (15),(15),
Job Job CharChar (10) (10) CONSTRAINTCONSTRAINT Unik1 Unik1 UNIQUEUNIQUE,,
Mgr Mgr short short CONSTRAINTCONSTRAINT FKey1 FKey1 REFERENCESREFERENCES EMP (EMP (EmpNoEmpNo),),
HiredateHiredate DateDate ,,
Sal Sal singlesingle ,,
Comm Comm singlesingle ,,
DeptNoDeptNo short short CONSTRAINTCONSTRAINT FKey2 FKey2 REFERENCESREFERENCES DEPT(DeptNoDEPT(DeptNo));));
SQL - CREATE TABLE
Syntax:
CREATE TABLE tablename (column_name data_ type constraints, …)
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.
10
ER/CORP/CRS/DB07/003
Version No: 2.010Copyright © 2004,
Infosys Technologies Ltd
ALTER TABLEALTER TABLE EMP (ADDADD Grade short);
ALTER TABLEALTER TABLE EMP (DROPDROP Grade);
SQL - ALTER TABLE
Add/Drop Column
Syntax:
ALTER TABLE tablename (ADD/DROP column_name)
Used to modify the structure of a table by adding and removing columns
11
ER/CORP/CRS/DB07/003
Version No: 2.011Copyright © 2004,
Infosys Technologies Ltd
ALTER TABLEALTER TABLE EMP ADD CONSTRAINTADD CONSTRAINT Pkey1 PRIMARY KEYPRIMARY KEY (EmpNo);
ALTER TABLEALTER TABLE EMP DROPDROP CONSTRAINTCONSTRAINT Pkey1;
SQL - ALTER TABLE
Add/Drop Primary key
12
ER/CORP/CRS/DB07/003
Version No: 2.012Copyright © 2004,
Infosys Technologies Ltd
ALTER TABLEALTER TABLE EMP ADD CONSTRAINTADD CONSTRAINT Fkey1 FOREIGN KEYFOREIGN KEY (Mgr) REFERENCESREFERENCES EMP (EName);
ALTER TABLEALTER TABLE EMP DROPDROP CONSTRAINTCONSTRAINT Fkey1;
SQL - ALTER TABLE
Add/Drop Foreign key
13
ER/CORP/CRS/DB07/003
Version No: 2.013Copyright © 2004,
Infosys Technologies Ltd
DROP TABLEDROP TABLE EMP;;
SQL - DROP TABLE
DROP TABLE– Deletes table structure– Cannot be recovered– Use with caution
14
ER/CORP/CRS/DB07/003
Version No: 2.014Copyright © 2004,
Infosys Technologies Ltd
Exercise
Office
City
Region
Mgr
Target
Sales
Empl-Num
Name
Age
Rep_Office
Title
Hire_Date
Manager
Quota
Sales
Cust_Num
Cust_Name
Cust_Rep
Credit_Limit
OFFICE SALESREP
Mfr_ID
Product_ID
Description
Price
Qty_On_Hand
PRODUCTS
CUSTOMER
Order_Num
Order_Date
Cust
Rep
Mfr
Product
Qty
Amount
ORDERS
Taken by
Has Mgr
Works in
Is For
Placed by
Has rep
15
ER/CORP/CRS/DB07/003
Version No: 2.015Copyright © 2004,
Infosys Technologies Ltd
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
Consider the two entities OFFICE and SALESREPThe 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
OFFICECREATE 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) );
16
SQL-DML
Here we will discuss about commands using which data from the tables would be extracted and updated in different ways
17
ER/CORP/CRS/DB07/003
Version No: 2.017Copyright © 2004,
Infosys Technologies Ltd
SQL - INSERT INTO
Single-row insert
INSERT INTO INSERT INTO S VALUESVALUES(‘S3’,’SUP3’,’BLORE’,10)
Syntax: INSERT INTO tablename VALUES (value list)
Inserting one row, many columns at a time
INSERT INTOINSERT INTO S (SNO, SNAME) VALUESVALUES ((‘‘S1S1’’, , ‘‘SmithSmith’’););
Inserting many rows, all/some columns at a time.
INSERT INTOINSERT INTO NEW_SUPPLIER (SNO, SNAME)
SELECTSELECT SNO, SNAME
FROMFROM S
WHEREWHERE CITY ININ (‘BLORE’,’MADRAS’)
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
18
ER/CORP/CRS/DB07/003
Version No: 2.018Copyright © 2004,
Infosys Technologies Ltd
Examples:Examples:
UPDATEUPDATE S SETSET CITY = ‘KANPUR’ WHEREWHERE SNO=‘S1’
UPDATEUPDATE EMP SETSET SAL = 1.10 * SAL
SQL - UPDATE
With or without WHERE clause
Syntax:
UPDATE tablename SET column_name =value [ WHERE condition]
The examples are quite self explanatory
19
ER/CORP/CRS/DB07/003
Version No: 2.019Copyright © 2004,
Infosys Technologies Ltd
DELETE DELETE FROM FROM SP WHEREWHERE PNO= ‘P1’
DELETE FROMDELETE FROM SP
SQL - DELETE FROM
With or without WHERE clause
Syntax: DELETE FROM tablename WHERE condition
Delete all rows from Shipment table for all part number as P1
20
ER/CORP/CRS/DB07/003
Version No: 2.020Copyright © 2004,
Infosys Technologies Ltd
SNO SNAME STATUS CITY
S1 Smith 20 LondonS2 Jones 10 ParisS3 Blake 30 ParisS4 Clark 20 LondonS5 Adams 30 Athens
Supplier table - S
21
ER/CORP/CRS/DB07/003
Version No: 2.021Copyright © 2004,
Infosys Technologies Ltd
Product table - P
PNO PNAME COLOR WEIGHT CITY
P1 Nut Red 12 LondonP2 Bolt Green 17 ParisP3 Screw Blue 17 RomeP4 Screw Red 14 LondonP5 Cam Blue 12 ParisP6 Cog Red 19 London
22
ER/CORP/CRS/DB07/003
Version No: 2.022Copyright © 2004,
Infosys Technologies Ltd
Shipment table - SP
SNO PNO QTYS1 P1 300S1 P2 200S1 P3 400S1 P4 200S1 P5 100S1 P6 100S2 P1 300S2 P2 400S3 P2 200S4 P2 200S4 P4 300S4 P5 400
23
ER/CORP/CRS/DB07/003
Version No: 2.023Copyright © 2004,
Infosys Technologies Ltd
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
Examples:
Get the names of all the suppliers
SELECTSELECT SNAME FROMFROM S;
Get the names and city of all the suppliersSELECTSELECT SNAME, CITY FROMFROM S
Get full details for all Suppliers in S tableSELECTSELECT * FROMFROM S
24
ER/CORP/CRS/DB07/003
Version No: 2.024Copyright © 2004,
Infosys Technologies Ltd
SQL SQL -- ALL, DISTINCTALL, DISTINCT
SELECT ALL SELECT ALL PNamePName FROM PFROM P
Get all part numbers:
Get all distinct part numbers
SELECT DISTINCT SELECT DISTINCT PNamePName FROM PFROM P
Distinct will filter repetitive occurrence of a particular value
25
ER/CORP/CRS/DB07/003
Version No: 2.025Copyright © 2004,
Infosys Technologies Ltd
SELECT SELECT COL1,COL2,.........
FROMFROM TABLE NAME
WHEREWHERE < SEARCH CONDITION>
Retrieving a subset of rowsRetrieving a subset of rows
For retrieval of rows based on some condition, the syntax is
26
ER/CORP/CRS/DB07/003
Version No: 2.026Copyright © 2004,
Infosys Technologies Ltd
SELECTSELECT SNOFROMFROM SWHEREWHERE CITY = ‘PARIS’
Relational operator
= , < , > , <= , >= , != or < >
Get SNO for all suppliers in Paris
Relational operators
27
ER/CORP/CRS/DB07/003
Version No: 2.027Copyright © 2004,
Infosys Technologies Ltd
SELECT SELECT SNOFROM FROM SSWHERE WHERE CITY = CITY = ‘‘PARISPARIS’’ AND AND
STATUS >10STATUS >10
Logical operator: AND, OR, and NOT
Get SNO for all suppliers in Paris and status greater than 10
Logical operators
28
ER/CORP/CRS/DB07/003
Version No: 2.028Copyright © 2004,
Infosys Technologies Ltd
Get PNO for parts whose weight is one of 12,16 or 17 ?
SELECTSELECT PNOFROMFROM PWHEREWHERE WEIGHT=16 OROR
WEIGHT =12 OR OR WEIGHT = 17
Using logical operators..
29
ER/CORP/CRS/DB07/003
Version No: 2.029Copyright © 2004,
Infosys Technologies Ltd
Get parts whose weight is in the range 16 to 19 (inclusive)
SELECTSELECT *FROMFROM PWHEREWHERE WEIGHT BETWEENBETWEEN 16 ANDAND 19
Retrieval using BETWEEN
30
ER/CORP/CRS/DB07/003
Version No: 2.030Copyright © 2004,
Infosys Technologies Ltd
Get list of PNO for parts whose weight is one of 12, 16 or 17
SELECTSELECT PNOFROMFROM PWHEREWHERE WEIGHT ININ (12,16,17)
Retrieval using IN
31
ER/CORP/CRS/DB07/003
Version No: 2.031Copyright © 2004,
Infosys Technologies Ltd
Get the list of Supplier numbers in the cities ROME , PARIS ?
SELECTSELECT SNOFROMFROM SWHEREWHERE CITY ININ (‘PARIS’ ,’ROME’)
Retrieval using IN
32
ER/CORP/CRS/DB07/003
Version No: 2.032Copyright © 2004,
Infosys Technologies Ltd
SELECTSELECT *FROMFROM PWHEREWHERE PNAME LIKELIKE ‘C*’
Get all details of parts whose name begins with cha racter C
SELECTSELECT *FROMFROM PWHEREWHERE PNAME LIKELIKE ‘C?’
Retrieval using LIKE
33
ER/CORP/CRS/DB07/003
Version No: 2.033Copyright © 2004,
Infosys Technologies Ltd
Get PNO for parts whose weight is unknown (Blank or not added).
SELECTSELECT PNOFROM FROM PWHERE WHERE WEIGHT IS NULLIS NULL
SQL - Retrieval using IS NULL
34
ER/CORP/CRS/DB07/003
Version No: 2.034Copyright © 2004,
Infosys Technologies Ltd
Get all details of shipments whose quantity is kno wn
SELECTSELECT *FROMFROM SPWHEREWHERE QTY IS NOT NULLIS NOT NULL
SQL SQL -- Retrieval using NOT NULLRetrieval using NOT NULL
35
ER/CORP/CRS/DB07/003
Version No: 2.035Copyright © 2004,
Infosys Technologies Ltd
Column titles using AS
SELECTSELECT SNO AS [Supplier Number],CITY AS [Supplier City]FROMFROM S
The name given in the square brackets will appear as title of that column in the final output.
36
ER/CORP/CRS/DB07/003
Version No: 2.036Copyright © 2004,
Infosys Technologies Ltd
SELECTSELECT COL1,COL2,.......FROMFROM TABLE_NAME
WHEREWHERE <SEARCHCONDITION>
ORDER BY ORDER BY COL-NAME [DESC][DESC]
• by default the order is ASCENDING
SQL - Sorting your results
37
ER/CORP/CRS/DB07/003
Version No: 2.037Copyright © 2004,
Infosys Technologies Ltd
Get SNO and STATUS for suppliers in Paris in desce nding order of status
SELECTSELECT SNO, STATUSFROMFROM S
WHEREWHERE CITY=‘PARIS’
ORDER BY ORDER BY STATUS DESCDESC
Retrieval using ORDER BY
38
ER/CORP/CRS/DB07/003
Version No: 2.038Copyright © 2004,
Infosys Technologies Ltd
SELECTSELECT CITY,COLOR,WEIGHTFROMFROM PWHEREWHERE WEIGHT IN (12,17)ORDER BY ORDER BY CITY,COLOR DESCDESC
SELECTSELECT CITY,COLOR,WEIGHTFROMFROM PWHEREWHERE WEIGHT IN (12,17)ORDER BY ORDER BY 1 DESCDESC, 2
Retrieval using ORDER BY
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
BangaloreCalcuttaChennaiHydrabad 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.
YellowRedGreenBlue
So the display may look something like
Bangalore Yellow 87.6Bangalore Red 45.8Bangalore Green 32.6Bangalore Blue 54.3Bangalore Blue 43.2
Calcutta Yellow 34.5….
39
ER/CORP/CRS/DB07/003
Version No: 2.039Copyright © 2004,
Infosys Technologies Ltd
SELECTSELECT PNO, WEIGHT*1000FROMFROM P
Queries involving calculated values
Get PNO and WEIGHT in grams for all parts
40
ER/CORP/CRS/DB07/003
Version No: 2.040Copyright © 2004,
Infosys Technologies Ltd
Get PNO and WEIGHT in grams for all parts
SELECTSELECT PNO AS [Part], WEIGHT*1000 AS[Weight in grams]
FROM FROM P
Queries involving strings
41
Aggregate Functions
42
ER/CORP/CRS/DB07/003
Version No: 2.042Copyright © 2004,
Infosys Technologies Ltd
SUM( ) , AVG( ) , MAX( ) , MIN( ), COUNT( )
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 :
43
ER/CORP/CRS/DB07/003
Version No: 2.043Copyright © 2004,
Infosys Technologies Ltd
Get total qty of P2 supplied
SELECT SELECT SUM SUM (QTY)FROMFROM SPWHEREWHERE PNO=‘P2’
Aggregate function - SUM
Adds up the values in the specified columnColumn must be numeric data type Value of the sum must be within the range of that data type
Example:
44
ER/CORP/CRS/DB07/003
Version No: 2.044Copyright © 2004,
Infosys Technologies Ltd
Example:
Get average qty of shipment supplied by S1
SELECTSELECT AVGAVG(QTY)FROMFROM SPWHEREWHERE SNO=‘S1’
Aggregate function - AVG
Returns the average of all the values in the specified columnColumn must be numeric data type
45
ER/CORP/CRS/DB07/003
Version No: 2.045Copyright © 2004,
Infosys Technologies Ltd
Get maximum qty of shipment supplied by S1
SELECT SELECT MAXMAX(QTY)FROMFROM SPWHERE WHERE SNO =‘S1’
Aggregate function Aggregate function -- MAXMAX
Returns the largest value that occurs in the specified columnColumn need not be numeric type
Example:
46
ER/CORP/CRS/DB07/003
Version No: 2.046Copyright © 2004,
Infosys Technologies Ltd
Get minimum qty of shipment supplied by S1
SELECT SELECT MINMIN(QTY) FROMFROM SPWHERE WHERE SNO=‘S1’
Aggregate function - MIN
Returns the smallest value that occurs in the specified columnColumn need not be numeric type
47
ER/CORP/CRS/DB07/003
Version No: 2.047Copyright © 2004,
Infosys Technologies Ltd
Get total number of suppliers
SELECTSELECT COUNTCOUNT(*) FROMFROM S
Aggregate function - COUNT
Returns the number of rows in the table
Get number of shipments for P2
SELECTSELECT COUNTCOUNT(Qty)FROMFROM SPWHEREWHERE PNO=‘P2’
Count(*) = No of rowsCount(QTY) = No. of rows that do not have NULL Value
48
ER/CORP/CRS/DB07/003
Version No: 2.048Copyright © 2004,
Infosys Technologies Ltd
SELECTSELECT MINMIN(Qty), MAX(QTY)FROMFROM SPWHEREWHERE PNO=‘P2’
Using two or more aggregate functions
49
ER/CORP/CRS/DB07/003
Version No: 2.049Copyright © 2004,
Infosys Technologies Ltd
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)
50
ER/CORP/CRS/DB07/003
Version No: 2.050Copyright © 2004,
Infosys Technologies Ltd
Thank You!