Anda di halaman 1dari 102

Relational Database Management Systems

SQL(Structured Query
Language)

What is it ? What does it do ? How is it used ?

What is SQL
SQL is the language RDBMS understands. It helps us to: Create tables Make changes in the tables Impose relationships between tables Enter, delete, update & retrieve data.

SQL - Background
Conceived in mid-1970s as a database language for the relational model Developed by IBM First standardized in 1986 by ANSI Enhanced in 1989 Revised again in 92 Non Procedural language Number of commercial products

Subdivision of SQL
Interactive SQL is used to operate directly on a DB to produce output Embedded SQL consists of SQL commands put inside the programs that are mostly written in high language (COBOL, C, ..). This makes the program more powerful and efficient.

SQL Data types


Numeric Character Date

SQL
SQL - DDL, DML, DCL DDL
CREATE ALTER DROP

DML
SELECT INSERT DELETE UPDATE

DCL
GRANT REVOKE COMMIT ROLLBACK

SQL - ANSI/ISO Keywords


ALL AND AVG BETWEEN CHAR COMMIT COUNT CREATE DECIMAL DELETE DISTINCT DROP FETCH GRANT GROUP BY HAVING IN INSERT MAX MIN NOT NULL OR PRIVILEGE REFERENCES REVOKE SELECT SUM TABLE UPDATE VIEW WHERE

SQL - CREATE TABLE CREATE TABLE


Constraints
Primary Key Foreign Key Unique

SQL DDL

SQL - CREATE TABLE


CREATE TABLE EMP ( EmpNo short CONSTRAINT PKey PRIMARY KEY, EName VarChar(15), Job Char(10) CONSTRAINT Unik1 UNIQUE, Mgr short CONSTRAINT FKey1 REFERENCES EMP(EmpNo), Hiredate Date, Sal single, Comm single, DeptNo short CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));

Create a Supplier-Parts database


Supplier (S) table [S#, SName, Status, City] Parts (P) table [P#, PName, Color, Wt, City] Shipment (SP) table [S#, P#, Qty]

Exercise...

SQL - ALTER TABLE


Add/Drop Column

ALTER TABLE EMP (ADD Grade short); ALTER TABLE EMP (DROP Grade);

SQL - ALTER TABLE


Add/Drop Primary key

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

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;

SQL - DROP TABLE


DROP TABLE
Deletes table structure Cannot be recovered Use with caution

DROP TABLE EMP;

SQL -DML

SQL - INSERT INTO


Single-row insert Multi-row insert
INSERT INTO S VALUES(S3,SUP3,BLORE,10)

SQL - INSERT INTO


Inserting one row, many columns at a time.
Insert values SNO=S1 and SNAME=Smith to the existing supplier table.

INSERT INTO S (SNO, SNAME) VALUES (S1, Smith);

SQL - INSERT INTO


Inserting many rows, all/some columns at a time. Ex: Copy list of Suppliers to New_Suppliers
INSERT INTO NEW_SUPPLIER (SNO, SNAME) SELECT SNO, SNAME FROM S WHERE CITY IN (BLORE,MADRAS)

SQL - UPDATE
With or without WHERE clause
Update city of supplier table for supplier as S1 to KANPUR

UPDATE S SET CITY = KANPUR WHERE SNO=S1

UPDATE EMP SET SAL = 1.10 * SAL

SQL - DELETE FROM


Used to delete data from tables Even if all data is deleted the table is not NOT deleted.

SQL - DELETE FROM


With or without WHERE clause
Delete from Shipment table for all part number as P1

DELETE FROM SP WHERE PNO= P1 DELETE FROM SP

Supplier table - S
SNO SNAME S1 S2 S3 S4 S5 Smith Jones Blake Clark Adams STATUS 20 10 30 20 30 CITY London Paris Paris London Athens

Product table - P
PNO PNAME P1 P2 P3 P4 P5 P6 Nut Bolt Screw Screw Cam Cog COLOR Red Green Blue Red Blue Red WEIGHT CITY 12 17 17 14 12 19 London Paris Rome London Paris London

Shipment table - SP
SNO S1 S1 S1 S1 S1 S1 S2 S2 S3 S4 S4 S4 PNO P1 P2 P3 P4 P5 P6 P1 P2 P2 P2 P4 P5 QTY 300 200 400 200 100 100 300 400 200 200 300 400

Retrieving a column from table


Get the names of all the suppliers
SELECT SNAME

FROM S

Retrieving multiple columns


Get the names and city of all the suppliers

SELECT SNAME, CITY


FROM S

Retrieving all columns


Get full details for all Suppliers in S table
SELECT *
FROM S

SQL - ALL, DISTINCT


Get all part numbers SELECT ALL PName FROM P Get all distinct part numbers

SELECT DISTINCT PName FROM P

Find the difference in output


SELECT SNO FROM S SELECT DISTINCT SNO FROM S

Assumption: SNO is Primary Key

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>

Get SNO for all suppliers in Paris

Relational operators

SELECT SNO FROM S WHERE CITY = PARIS


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

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

Logical operators

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


Logical operator: AND, OR, and NOT

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

Retrieval using Comparison operators


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

SELECT * FROM P WHERE WEIGHT BETWEEN 16 AND 19


BETWEEN operator can be modified using AND

Get list of PNO for parts whose weight is one of 12, 16 or 17

Retrieval using IN

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


IN operator can be modified using OR

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

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

Get all details of parts whose name begin with character C

Retrieval using LIKE


SELECT * FROM P WHERE PNAME LIKE C% In Oracle SELECT * FROM P WHERE PNAME LIKE C?

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

NULL Get all details of shipments whose quantity is known

SQL - Retrieval using NOT

SELECT * FROM SP WHERE QTY IS NOT NULL

Column titles using AS


SELECT SNO AS Supplier_Number, CITY AS Supplier_City FROM S
SUPPLIER_NUMBER SUPPLIER_CITY --------------- -------------------2 Osaka 3 Aichi 4 Kyoto 5 Kobe 6 Kanagawa

SQL - Sorting your results


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

WHERE <SEARCH CONDITION>

ORDER BY COL-NAME [DESC]


by default the order is ASCENDING

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

Retrieval using ORDER BY

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, 2


P# PNAME COLOR WEIGHT CITY --------- -------------------- ---------- --------- ---------1 Nut Red 12 Osaka 2 Bolt Green 18 Shizuoka 3 Screw Blue 17 Shizuoka 4 Screw Red 15 Aich 5 Cam Blue 20 Kobe 6 Cog red 15 Osaka 7 Cans Yellow 12 Osaka

CITY COLOR WEIGHT -------------------- ---------- --------Shizuoka Blue 17 Osaka Red 12 Osaka Yellow 12

Queries involving calculated values Get PNO and WEIGHT in grams for all parts
SELECT PNO, SELECT PNO, WEIGHT*1000 WEIGHT*1000 AS FROM P Weight_grams FROM P
PNO
Weight_grams WEIGHT*1000 ?

SQL - Aggregate functions


Used when information you want to extract from a table does not relate to what is contained in the individual rows, but has to do with the data in the entire table taken as a set.

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

SQL - Aggregate functions


Each of these functions performs an action that draws data from a set of rows rather than only from a single row. Aggregate functions are used in place of column names in the SELECT statement.

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

Get total qty of P2 supplied

SELECT SUM (QTY) FROM SP WHERE PNO=P2

Aggregate functionCOUNT
Get number of shipments for P2

SELECT COUNT(Qty) FROM SP WHERE PNO=P2


Count(*) = No of rows Count(QTY) = No. of rows that do not have NULL Value

Using two or more aggregate functions


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

SQL - Using GROUP BY


Related rows can be grouped together by GROUP BY clause by specifying a column as a grouping column. In the output table all the rows with an identical value in the grouping column will be grouped together. GROUP BY is associated with an aggregate function

Retrieval using GROUP BY


For each part supplied get the part number and the total shipment quantity
SELECT PNO, SUM(QTY) FROM SP GROUP BY PNO
SNo PNo QTY --------- --------- --------2 3 200 PNo SUM(QTY) 6 6 400 --------- --------5 4 600 1 500 4 6 400 2 600 2 1 500 3 1200 5 5 700 4 1600 4 3 1000 5 700 3 2 600 6 800 5 4 600 2 4 400

Retrieval using GROUP BY


Get SNO, PNO, total qty for each part supplied

SELECT SNO, PNO, SUM(QTY) FROM SP GROUP BY PNO PNO Wrong SNO,
SNo PNo QTY --------- --------- --------2 3 200 6 6 400 5 4 600 4 6 400 2 1 500 5 5 700 4 3 1000 3 2 600 5 4 600 2 4 400 SNo PNo SUM(QTY) ------- --------- --------2 1 500 2 3 200 2 4 400 3 2 600 4 3 1000 4 6 400 5 4 1200 5 5 700 6 6 400

Retrieval using HAVING


Used to specify condition on group

Get PNO for parts which have more than two shipments SELECT PNO,COUNT(*) FROM SP GROUP BY PNO HAVING COUNT(*)>2

Retrieval using UNION


Get a list of all the parts cities and supplier cities
SELECT CITY FROM P UNION SELECT CITY FROM S

Get a list of all common parts and supplier cities


SELECT CITY FROM P INTERSECT SELECT CITY FROM S

Retrieval using INTERSECT

Correlated, Nested Queries Joins Index

Independent sub-queries
Inner query is independent of outer query. Inner query is executed first and the results are stored. Outer query then runs on the stored results.

Get supplier names for all suppliers who supply part P2 SELECT SNAME FROM S WHERE SNO IN (SELECT SNO FROM SP WHERE PNO =P2)

Retrieval using SUB QUERIES

Retrieval using SUB QUERIES


Get SNO for suppliers who supply at least one part supplied by S2 SELECT SNO FROM SP WHERE PNO IN (SELECT PNO FROM SP WHERE SNO=S2)

Retrieval using SUB QUERIES


Get SNO who have status less than the status of S1 SELECT SNO FROM S WHERE STATUS < (SELECT STATUS FROM S WHERE SNO=S1)

Correlated Sub Queries


While using sub-queries in SQL, you can refer in the inner query to the table in the FROM clause of the outer query using Correlated subqueries. The inner query is executed separately for each row of the outer query.

Correlated Sub Queries


Get PNO for all parts supplied by more than one supplier

SELECT PNO FROM SP X WHERE PNO IN (SELECT PNO FROM SP Y WHERE Y.SNO<>X.SNO)

Correlated Sub Queries...


Get SNO for suppliers supplying some project with P1 in a quantity greater than the average qty of P1 supplied to that project SELECT DISTINCT SNO FROM SPJ X WHERE PNO=P1 AND QTY> (SELECT AVG(QTY) FROM SPJ Y WHERE PNO=P1 AND X.JNO=Y.JNO)

JOIN
Inner join Outer join
Left-outer join Right-outer join

Self join

Inner Joins
Commonly type of join Combine records from two tables with matching values.

Retrieval from Multiple tables


Get all combinations of supplier and part information such that the supplier and part are co-located. SELECT S.*, P.* FROM S, P WHERE S.CITY=P.CITY

Retrieval from Multiple tables


Get SNO,PNO combinations where the parts city follows the suppliers alphabetically SELECT SNO, PNO FROM S, P WHERE S.CITY<P.CITY

Retrieval from Multiple tables


Get SNO and PNO for co-located suppliers and parts omitting suppliers with status<20

SELECT P.PNO, S.SNO FROM P, S WHERE S.CITY = P.CITY AND S.STATUS > = 20

Outer join
Retrieve all rows that match the WHERE clause and those that have a NULL

Left/Right-Outer join
Left outer joins include all records from the first (left) of two tables, A(+)=B Right outer joins include all records from the second (right) of two tables, A=B(+)

Example of left-join
List all SNO with QTY supplied or SNO which have not yet supplied any QTY
SELECT S.SNO, SP.QTY FROM S, SP WHERE S.SNO (+)= SP.SNO;
All unmatched rows of S are also selected

Self join-Joining a table with itself


Get all pairs of SNO who are co-located SELECT FIRST.SNO, SECOND.SNO FROM S FIRST, S SECOND WHERE FIRST.CITY=SECOND.CITY

Retrieval using EXISTS


Get all part names from parts table which have been shipped

SELECT PNAME FROM P WHERE EXISTS (SELECT * FROM SP WHERE SP.PNO=P.PNO)

Retrieval using NOT EXISTS


Get the list of all prospective suppliers, i. e., suppliers for whom no shipments exist yet.

SELECT SNAME FROM S WHERE NOT EXISTS (SELECT * FROM SP WHERE SP.SNO=S.SNO)

Index Views Security using DCL

Index
Index can be created and dropped. By default RDBMS creates index on Primary Key

CREATE UNIQUE INDEX Sup_Index ON Supplier (SName) ; DROP INDEX Sup_Index;

Views
Base tables. Views are like windows. Views are operated on by queries/DML. A view is actually a query that is executed whenever the view is subject to a command.

Creating a VIEW
Create a view from Supplier table

CREATE VIEW ViewSupplier AS SELECT * FROM Supplier;

Creating a VIEW
Create a view from Supplier table for City in BHU

CREATE VIEW ViewSupplier AS SELECT S.SNO, S.SName, S.City FROM Supplier S WHERE City = BHU;

Naming columns in a View


CREATE VIEW ViewSupplier (Supp#, Name) AS SELECT S.SNO, S.SName FROM Supplier S WHERE City = BHU;

Often we do not specify new field names, but if we do, we will have to do so for every field in the view.

Working with a View


SELECT * FROM ViewSupplier;

Grouped Views
CREATE VIEW ViewSupplier (Supp#, Name) AS SELECT S.SNO, S.SName FROM Supplier S WHERE City = BHU GROUP BY status;

Updation is not possible in case of Grouped views, Joined views & other complicated views.

Dropping Views
Views are dropped similar to the way in which the tables are dropped. However, you must own a view in order to drop it. DROP VIEW <view name>;

DROP VIEW ViewSupplier;

Checking values placed in view


CREATE VIEW ViewSupplier AS SELECT S.SNO, S.SName, S.City FROM Supplier S WHERE City = BHU;

Let us update the ViewSupplier view


INSERT INTO ViewSupplier VALUES (S5,Tom,LONDON);
Is this a legal insert?

Check Option
CREATE VIEW ViewSupplier AS SELECT S.SNO, S.SName, S.City FROM Supplier S WHERE City = BHU WITH CHECK OPTION;

Let us update the ViewSupplier view


INSERT INTO ViewSupplier VALUES (S5,Tom,LONDON); Will the update be successful?

Security Concepts
User Authentication Database Objects Privileges

Data Control Language


Full control: table creators. Privilege

GRANT .. TO REVOKE .. FROM ...

Forms of GRANT syntax


Privileges on a specified database Privileges on specified tables or views System privileges

1. GRANT . database
GRANT { [DBADM[, ]] - Database administrator authority [DBCTRL[,]] - Database control authority [DBMAINT[, ]] - Database maintenance authority [CREATETAB[,]] - Privilege to create table [DROP[, ]] - Privilege to DROP/ALTER [STARTDB[, ]] - Start database [STOPDB[, ]] } - Stop database ON DATABASE database-name[,...] TO [AuthID][,...] [PUBLIC] [WITH GRANT OPTION]

2. GRANT . Tables or views


GRANT { [ALTER[, ]] [DELETE[, ]] [INDEX[, ]] [INSERT[, ]] [SELECT[, ]] [UPDATE [(column-name[,...])][, ]] [REFERENCES[, ]] | ALL [PRIVILEGES] } ON [TABLE] {table-name[,...] | view-name[,...]} TO [AuthID][,...] [PUBLIC [AT ALL LOCATIONS]] [WITH GRANT OPTION]

3. GRANT .. System privileges


GRANT { [CREATEALIAS[, ]] - create alias [CREATEDBA[, ]] - create DB to get DBADM authority [CREATEDBC[, ]] - create DB to get DBCTRL authority [CREATESG[, ]] - to create new storage group [SYSADM[, ]] - to provide system ADM authority [SYSCTRL[, ]] - to provide system control authority } TO [AuthID][,...] [PUBLIC] [WITH GRANT OPTION]

GRANT . TO .
Used to grant access to new users; Permission can be granted for all DML commands; Permission is granted on a database/table/view; Permission for further grant.

GRANT Select On
User1 is an owner of Customer table. User1 wants User2 perform queries on it. User1 issues following command:

GRANT SELECT ON Customer to User2;

GRANT INSERT ON
User1 issues the command GRANT INSERT ON Customer to User2; GRANT SELECT, INSERT ON Customer to User2; GRANT INSERT ON Customer to User2, User3;

Restricting Privileges
GRANT SELECT, UPDATE ON Customer to User2 GRANT UPDATE(Comm) ON Customer to User2 GRANT UPDATE(CName,City) ON Customer to User2;

ALL & PUBLIC arguments


GRANT ALL PRIVILEGES ON Customer to User2 GRANT ALL ON Customer to PUBLIC; GRANT SELECT ON Customer to PUBLIC;

Granting with GRANT option


GRANT SELECT ON Customer To User2 WITH GRANT OPTION GRANT SELECT ON User1.Customer To User3; GRANT SELECT ON User1.Customer To user3 WITH GRANT OPTION;

Taking PRIVILIGES away


The syntax of REVOKE command is patterned after GRANT, but with a reverse meaning. REVOKE{ [ALTER[, ]] [DELETE[, ]] [INDEX[, ]] [INSERT[, ]] [SELECT[, ]] [UPDATE [(column-name[,...])][, ]] | ALL [PRIVILEGES] } ON [TABLE] {table-name[,...] | view-name [,...]} FROM AuthID[,...][PUBLIC [AT ALL LOCATIONS]] [BY {AuthID[,...] | ALL}]

Example of REVOKE
REVOKE INSERT ON Customer FROM User2;

REVOKE SELECT, INSERT ON Customer FROM User2, User3;

Anda mungkin juga menyukai