dbms lesson1.1

41
Lecture by Prof.Dr .S.Sridhar 1 DataBase Technology by Dr.S.Sridhar, Ph.D. (JNUD), RACI(Paris, NICE), RMR(USA), RZFM(Germany) DIRECTOR ARUNAI ENGINEERING COLLEGE TIRUVANNAMALAI

description

dbms lesson1.1

Transcript of dbms lesson1.1

  • DataBase Technologyby

    Dr.S.Sridhar, Ph.D.(JNUD), RACI(Paris, NICE), RMR(USA), RZFM(Germany) DIRECTOR ARUNAI ENGINEERING COLLEGE TIRUVANNAMALAI

    Lecture by Prof.Dr.S.Sridhar

  • DBMS CONCEPTS Data Base Management Systems Examples of DatabasesFiles & DB SystemsAdvantages of DBMSAttributes / EntitiesNormalization in RDBMSRDBMS & ExamplesSQL in DB & ExamplesEntity-relationship model3NFStudents/s DB Case StudyData Base Security / Backups

    Lecture by Prof.Dr.S.Sridhar

  • Whats Database System ?- It is nothing but a computerized record keeping system.- The DB itself can be regarded as electronic filing cabinet.- It is a collection of files.The user of the system will have the following facilities :Adding New, empty files to the DB.Inserting new data into existing files.Retrieving data from existing files.Deleting data from existing files.Removing existing files, empty or otherwise, from the DBData base is a collection of files.Data base is a collection of records.Data base is a collection of fields.

    Lecture by Prof.Dr.S.Sridhar

  • The above file is referred as Table in RDBMS Sense.Call this table as CELLARThis contains many records.Each record has fields.Here

    is a record The values inside the tableare called Field values

    Fields

    BINWINEPRODUCERYEARBOTTLESREADY2ChardonnaryBuena Vista1992119943ChardonnaryGeyser Peak1992519946ChardonnaryStonestreet19914199312Jo.RieslingJekel19931199421Fune BlancCh.St.Jean19924199422Fune BlancGeyser Peak19912199330Cab.SaurignonJekel198612199543Cab.SaurignonJekel19902199345Pinot NoirBuena Vista19899199850Pinrot NoirBuena Vista199021998

    BINWINEPRODUCERYEARBOTTLESREADY

    Lecture by Prof.Dr.S.Sridhar

  • Retrieve Data (Query Language)SELECT WINE, BIN, PRODUCERFROM CELLARWHERE READY = 1995 ; RESULT

    is the command used to Retrivefrom which table ( file )ConditionINSERT:INSERTINTO CELLAR ( BIN, WINE, PRODUCER )VALUES ( 53, Pinot Noir, Saintsbury);UPDATE:UPDATE CELLARSET BOTTLES = 4WHERE BIN = 3;

    WINECab.SaurignonBIN30PRODUCERJEKEL

    Lecture by Prof.Dr.S.Sridhar

  • DELETEDELETEFROM CELLARWHERE BIN = 2;Thus, the commands like, SELECT, INSERT, UPDATE and DELETE are actually the examples of Database Query Language.SQL Structured Query Language

    Remarks :- One should be very careful. Whenever DELETE or UPDATE operations are done in the DB.Here, - Retrieving any amount of fields for a particular record is done .- Inserting into file for a particular field(s) with values is done.- Updating is for a particular field in a record is done.- Deleting is done for a record under a matching condition.

    Lecture by Prof.Dr.S.Sridhar

  • (DBMS)Data Base Management System

    Application ENDPrograms USERS

    Major Components:* Data* HardwareSimplified View * Software of Data base System* UsersAn Overview of Database Management

    Data Base

    Lecture by Prof.Dr.S.Sridhar

  • Examples of Data Bases:Financial DatabasePersonnel Database ( Employee)Payroll DatabaseAccounting DatabaseInventory DatabaseManagement Information DatabaseLibrary Databaseand so on.Examples of DBMS (Data Base Management System)ORACLEINFORMIXINGRESSSYBASEand so on.What s Data ?It is the meaning full information stored in computer system.Two KindsIntegratedSharedIntegrated, means that the Database can be thought of as a unification of several otherwise distinct data files, with any redundancy among those files wholly or partially.

    Lecture by Prof.Dr.S.Sridhar

  • ExampleA Database containing both the files.EMPLOYEEIDNONameAddressDepartmentSalariesPhone No.Permanent Addressand a training file.TRAININGIDNOCourse a HeadedCourse DetailsCourse FeesLocation of CourseFeedbackGrade OfferedShared Database means that individual pieces of data in the database can be shared by several different users. For example from the file EMPLOYEE,The general details can be utilised by Personnel department.The salary details may be utilized by Financial department. All done in shared manner.and so on.

    Lecture by Prof.Dr.S.Sridhar

  • Hardware Consisting ofSecondary storage volumes that are used to hold the stored data with associated I/O devices(Disk drives etc), Devices Controllers, I/O channels,etc.The Processors and associated main memory that are used to support the execution of the Database system software. Software Consisting ofDatabase Manager (DB Manager) or more commonly used term as DBMS, Data Base Management System.Additional utilities like Application development tools, design aids, report writers and so on.Example: Oracle, Informix, Sybase,etc.UsersApplication Programmers, who are responsible for writing programs to access the Database for Insert, Update, Delete, Query, Reports etc.End users who are really accessing the database for queries / data entry / report generation etc.

    Lecture by Prof.Dr.S.Sridhar

  • What is Database ?It is a collection of Persistent data that is used by the application systems of some given enterprise.Input data : refers the information entered into the systems for the very first time ( typically from a terminal or workstation). It may be part of persistent data but it is not initially part of the databases Output Data : refers for messages and results coming out from the system ( typically printed or displayed on a screen). Again such information is derived from persistent data but it is not itself considered to the part of the database.

    Enterprise (Egs)Persistent Data (Egs)****************************A Manufacturing * Product DataCompanyA Bank* Account DataA Hospital* Patient DataA UniversityA govt. Dept.

    Lecture by Prof.Dr.S.Sridhar

  • Advantages of DatabasesCompactness ( No read for Voluminous papers)Speed ( for retrieval of Queries / Reports etc)Currency (Accurate, up-to-date information is available on demand anytime )Centralized control of data.The foregoing benefits apply even more force in multi user environment, of course, where the database is likely to be much larger and much more complex then in the single-user-case.

    Redundancy of data can be avoided.In consistency can be avoided to some extent.The data can be shared by many users.Standards can be enforced.Security restrictions can be applied.Integrity can be maintained.Conflicting requirement can be balanced.

    Lecture by Prof.Dr.S.Sridhar

  • RDBMS (Relational Data Base Mgmt. System)Relational Systems are such that1. The data perceived by users as tables.2. The operators are at users disposal.(eg) Data retrieval are operators that qurerate new tables from old and those operators include atleast SELECT, PROJECT and JOIN.EXAMPLE :DEPT

    EMP

    DEPT#DNAMEBUDGETD1D2D3MarketingDevelopmentResearch10M12M5M

    EMP#ENAMEDEPTSalaryE1E2E3E4JohnMarsalLemarkChengD1D1D2D240k25k42k35k

    Lecture by Prof.Dr.S.Sridhar

  • SELECT Operation extracts specified rows from a table.PROJECT - Operation extracts specified columns from a tableJOIN - Operation joins together two tables on the basis of common values in a common column.Apply the above operations on DEPT & EMP TablesSELECT DEPTs WHERE BUDGET > 8MResult(Specified Rows)

    PROJECT DEPTs OVER DEPT#, BUDGETResult(Specified Columns)

    JOIN DEPTs and EMPs OVER DEPT#ResultCommonRowsCommonColumns

    DEPT#DNAMEBUDGETD1D2MarketingDevelopment10M12M

    DEPT#BUDGETD1D2D310M12M5M

    DEPT#DNAMEBUDGETEMP#ENAMESALD1D1D2D2MarketingMarketingDevelopment Development10M10M12M12ME1E2E3E4JohnMarsalLemarkCherq40K25K42K35K

    Lecture by Prof.Dr.S.Sridhar

  • Entity Attributes Relationship modelsConceptInformationExamplesDefinition

    ENTITYA Distinguishable- Supplierobject- Part- Person- Purchase Orderand so on

    PROPERTYA piece of information- Supplier number to describe an entity- Shipment Qty- Person height- P.O.data etc.

    RELATIONSHIP An entity that serves to- Shipment interconnect 2 or more (Supplier-part)entities- Assignment (Emp-Dept.)Here Note1) Shipment is RELATIONSHIP between supplier and part.R

    RSimilarly for Assignment.SupplierPart

    Lecture by Prof.Dr.S.Sridhar

  • Entity / Relationship diagram (Example)-----*---------*----------*--------*---------*Entities : Department, Employee, DependentRelations : Dept-Emp, Emp-depAttributes : ( to employee) Emp#, Ename,Salary FirstMNLast (Group item)DepartmentDept-EmpEmployeeEmpEnameFirstMNLastSalaryEmp-DepDependent

    Lecture by Prof.Dr.S.Sridhar

  • Properties:Entities have properties : (Known as attributes). Take the case of Employee whose properties are Emp#, Ename and Salary. (all these are attributes).

    Simple a Composite: Emp# is simpleBut Ename contains First, MN and Last, three simple items groped together to address Ename. Such type of attributes are Composite.Key :It is one of the uniquely defined attributes. For eg. Emp# is unique and that is called key to access the other properties of the entity employee, like Ename and Salary.

    Key

    Emp#EnameSalary

    Lecture by Prof.Dr.S.Sridhar

  • Types of Relations1 1 (One to One)1 M (One to Many)M 1(Many to One)M M )(Many to Many)Examples ( 1-1)For every employee there is only one seatR

    (1-1)In an organization.(1-M) R;.;(M-1) R::;(M M)EmpSeatSupplierCustomer1Customer-mStudent1Student-mTeacherSuplier1.mCustomer11m

    Lecture by Prof.Dr.S.Sridhar

  • Many Examples of Attributes / Entities & RelationsExample 1:Book Student BOOK-STD R > R R< STD -BOOK

    Entities : Book, StudentRelation : BOOK-STD and STD-BOOK

    Attributes of BookAttributes of StudentAuthor RollNoTitle ExamNoPublisher NameYear ClassISBN Number AddressNumber of pages Phone NoPrice RemarksPrinterLocation of printingEdition-NatureRemarks

    BookStudent

    Lecture by Prof.Dr.S.Sridhar

  • Example 2 ( R )Part-Sup

    ( R )

    Sub-part ( R )Entities : Part, SupplierRelations: Part-Sup and Sub-part

    Attributes of partAttributes of Supplier

    PartNo Supplier codeDescription Supplier addressQty Supplier phoneUnit price Supplier locationOpening balance Delivery timeParts-new Address demandNet balance Warranty PeriodRemarks Remarks

    PartSupplier

    Lecture by Prof.Dr.S.Sridhar

  • Example 3:Stud-fac R R RFac-stud

    Entities : Student and FacultyRelations : Stud-fac and Fac-stud

    Attributes of StudentAttributes of FacultyRollNo Facuty IDExamNo NameName Classes HandlingClass QualificationAddress DesignationPhoneNo AddressFaculty Division Phone NoRemarks Students Related for Advising

    StudentFaculty

    Lecture by Prof.Dr.S.Sridhar

  • NORMALIZATION in RDBMSThe logical design considered are:S ( S#, SNAME, STATUS, CITY)PRIMARY KEY ( S#)P (P#, PNAME,COLOR, WEIGHT, CITY)PRIMARY KEY (P#)SP (S#, p#,QTY)PRIMARY KEY (S#, P#)FOREIGN KEY ( S#) REFERENCE SFOREIGN KEY (P#) REFERENCE PSCP (Relation) Table

    S#CITYP#QTYS1S1S1S1S1S1S2S2S3S4S4S4LondonLondonLondonLondonLondonLondonParisParisParisLondonLondonLondonP1P2P3P4P5P6P1P2P2P2P4P5300200400200100100300400200200300400

    Lecture by Prof.Dr.S.Sridhar

  • From the table we find Redundancy of data. So a good design principle is One fact in one place ((ie) avoid redundancy). How to do this ? That process is known as Normalization. There are 3NF (Normal forms NF).NamelyFirst NF (1NF)Second NF (2NF)Third NF (3NF)1NF:Every Normalized relation is in 1NF if and only if, if satisfied the condition that it contains scalar values ONLY.ExampleFIRST (S#, STATUS, CITY, P#, QTY)PRIMARY KEY (S#, P#)Functional Dependencies in relation FIRST

    QTYCITYSTATUSS#P#

    Lecture by Prof.Dr.S.Sridhar

  • Sample Tabulation of FIRST

    Now problems, We face with

    INSERTDELETEUPDATE

    S#STATUSCITYP#QTYS1S1S1S1S1S1S2S2S3S4S4S4202020202020101010202020LondonLondonLondonLondonLondonLondonParisParisParisLondonLondonLondonP1P2P3P4P5P6P1P2P2P2P4P5300200400200100100300400200200300400

    Lecture by Prof.Dr.S.Sridhar

  • Problems with INSERT- For examples, while inserting S5 after S! or S2 or S3 or S4, Confusion arises, Where to insert ?!- Insert a status after 20 problem ! - Insert a city after LONDON problem !- Insert P# after P2 Problem !

    DELETEWhile deleting some record,One should be more careful. Now delete a record corresponding to S# = 1.This will delete all records corresponding to S# = 1, whereas user may NOT mean this !

    Similarly,

    UPDATE :Update city for S# = 2This will update all city values, corresponding to S# = 2, whereas user does not mean this !

    Lecture by Prof.Dr.S.Sridhar

  • Second Normal Form :A relation is in 2NF if and only if is in !NF and every non-key attribute is irreducibly dependent on the primary key.ExampleSECOND (S#, STATUS, CITY)and SP(S#, P#, OTY)

    Functional Dependencies in relationSECOND AND SPSECOND

    SAMPLE TABULATION OF SECOND AND SP

    CITYS#STATUSQTYS#P#

    S#StatusCityS1S2S3S4S52010102030LondonParisParisLondonAthens

    S#P#QTYS1S1S1S1S1S1S2S2S3S4S4S4P1P2P3P4P5P6P1P2P2P2P4P5300200400200100100300400200200300400

    Lecture by Prof.Dr.S.Sridhar

  • INSERT :Eventhough S5 is not supplying any parts, we can insert the information that S5 is located in Athens, in SECOND.

    DELETE : While deleting the shipment connecting S3 and P2 in SP, we do NOT loose information that S3 is located in PARIS.UPDATE :In the revised structure, the city for given supplier appears once not many times. Thus S# CITY redundancy is eliminated. For example we can change for S1, the city as Amsterdam from London. This way updation is also possible in 2NF.

    Third Normal Form (3NF):A relation is in 3NF if it is in 2NF and every non-key attribute is non-transitively dependent on the primary key.This increases the data independance,.

    Lecture by Prof.Dr.S.Sridhar

  • Example:KeyKey

    Sample Tabulation of SC and CSThe above relation SC and CS are in 3NF.Whereas, SECOND is not in 3NF.

    SECOND

    Thus SECOND (S#, STATUS, CITY) is tabulated in 3NF asSC(S#, CITY) and CS (CITY, STATUS)

    S#CITYS1S2S3S4S5LondonParisParisLondonAthens

    CITYSTATUSAnthenLondonParisRome30201050

    S#STATUSCITYS1S2S3S4S52010102030LondonParisParisLondonAthens

    Lecture by Prof.Dr.S.Sridhar

  • Database Security & Back-upsSecurity problems :Legal, Social and ethical aspects Eg : does a person making the request say for customers credit- have a legal right to the requested information.

    Physical ControlsEg : Computer or Terminal room locked ! Or otherwise guarded ? !

    Policy QuestionsWho should have access ? !To what level ? !

    Operational Problems - Password is used. Then - How are the passwords Rept secrete ?- How often they are changed ?

    Lecture by Prof.Dr.S.Sridhar

  • Hardware Control- Whether the processing unit has any security measures,such as storage protection keys or privileged operation mode ?

    Operating System Security- Whether the O /S erase the contents of storage ? ! and Data files ? !

    Issues Concerned with DBMS- Whether the DBMS has the concept of ownership ?

    Examples of Discretionary Access control Create Security Rule SR3GRANT RETRIEVE (S#, SNAME, CITY),DELETE ON S WHERES.CITY = LONDONTO JIM, FRED, MARYON ATTEMPTED VIOLATION REJECT;

    Lecture by Prof.Dr.S.Sridhar

  • CREATE SECURITY RULE EX1:GRANT RETRIVE (S#, SNAME, CITY)ON STO JAC, ANNE, CHARLEY; CREATE SECURITY RULE EX4: GRANT RETRIVE (S#, SNAME)ON S WHERE S. STATUS > 50TO JAC, PAVL;CREATE VIEW SSS AS(S.S#, S.NAME) WHERES.STATUS > 50;

    Request Modification :

    DEFINE PERMIT RETRIEVE ON P TO U WHERE P.CITY = London

    RETRIEVE (P.P#, P.WEIGHT)WHERE P.COLOR = Red

    RETRIEVE (P.P#, P.WEIGHT)WHERE P.CITY = London

    Lecture by Prof.Dr.S.Sridhar

  • Back ups:Daily Back-upAfter the day work of all transactions, copying the entire system files / data files on a floppy, disk (CD), or a tape depending on the size of total volume.

    Weekly back-upMonthly back-upYearly back-upIn DBMS Mirroring concept as back up.Stand-by server as back-upCD- Server as back upSoftware, specially in Oracle like RDBMS, auto back-up and retrieval systems.

    Lecture by Prof.Dr.S.Sridhar

  • SQL Language

    CREATE TABLE( S# S# NOT NULL, P# P# NOT NULL, QTY QTY NOT NULL, PRIMARY KEY (S#) REFERENCE SON DELETE CASECADEON UPDATE CASCADE,CHECK(QTY > 0 AND QTY < 5001));

    This is to create a table with attributes S#, P#, QTY, all NOT NULL values and the primary key is S# also, check the condition while creating the table itself whether QTY is > 0 and QTY < 5001.Here CASCADE is used as an Option.ALTER TABLE S ADD COLUMN DISCOUNT INTEGERDEFAULT 1;Here we can alter the table S by adding a new column namely DISCOUNT which is an integer quantity with default value = -1.

    Lecture by Prof.Dr.S.Sridhar

  • DROP TABLE S;This will drop the created table S from the database.Data Manipulation (Retrieval operations)(called DML)SELECT P.COLOR, P.CITYFROM PWHERE P.CITY < >PARISAND P.WEIGHT > 10;-------------------------------------------------------------------SELECT DISTINCT P.COLOR, P.CITYFROM PWHERE P.CITY < > PARISAND P.WEIGHT > 10;------------------------------------------------------------------

    SELECT P.COLOR, P.CITYFROM PWHERE P.CITY < >PARISAND P.WEIGHT > 10;ORDER BY CITY DESC;

    Lecture by Prof.Dr.S.Sridhar

  • SELECT P.P#, P.WEIGHT * 454 AS GMNTFrom P;-------------------------------------------------------------------SELECT * FROM S;-------------------------------------------------------------------SELECT S.S#, S.NAME, S.STATUS, S.CITY,P.P#, P.NAME, P.COLOR, P. WEIGHT,FROM S, PWHERE S.CITY = P.CITY;-----------------------------------------------------------------S JOIN P USING CITY------------------------------------------------------------------SELECT DISTINCT S.CITY AS SCITY, P. CITY AS PCITYFROM S JOIN SP USING S# JOIN P USING P#;-------------------------------------------------------------------SELECT COUNT(*) AS NFROM S;-------------------------------------------------------------------SELECT MAX (SP.QTY)AS MAXQ,MIN (SP.QTY)AS MINQFROM SPWHERE SP.P# = P2;

    Lecture by Prof.Dr.S.Sridhar

  • Update OperationsINSERTINTO P (P#, PNAME, COLOR, CITY)VALUES (P8, Sprocket,pink, Nice);-------------------------------------------------------------------INSERT INTO TEMP(S#, CITY)SELECT S.S#, S.CITYFROM SWHERE S.STATUS > 15;-------------------------------------------------------------------DELETEFROM SPWHERE London = (SELECT S.CITYFROM SWHERE S.S# = SP. S#);-------------------------------------------------------------------All or Any conditionsSELECT DISTINCT PX.NAMEFROM P AS PXWHERE PX.WEIGHT > ALL ( SELECT PY.WEIGHTFROM P AS PYWHERE PY.COLOR = Blue);

    Lecture by Prof.Dr.S.Sridhar

  • Exercises ON SQLCREATE TABLE ( S# S# NOT NULL,P# P# NOT NULL, QTY QTY NOT NULL)Ans

    2) CREATE TABLE ( S# S# NOT NULL,P# P# NOT NULL, QTY QTY NOT NULL)PRIMARY KEY (S#) REFERENCE SCHECK (QTY >0 NAD QTY

  • 3) ALTER TABLE S ADD COLUMN DISCOUNT INTEGER DEFAULT 1;Ans

    4) DROP TABLE S;( Then the table S will NOT be in DB)DATA MANIPULATION1) SELECT S.P#, S.QTY FROM SWHERE S.QTY < > 20AND S.P# > 500 ;Ans

    2) SELECT DISTINCT S.S#, S.P#, S.QTYFROM SWHERE S.QTY < > 20AND S,P# > 500;Ans

    S#P#QtyDiscount45324533453512323456710205-1105

    S#P#QTY45355675

    S#P#QTY45355675

    Lecture by Prof.Dr.S.Sridhar

  • 3) SELECT DISTINCT S.S#, S.P#, S.QTY S. Discount FROM SWHERE S.QTY < 5AND S,P# > 125ORDER BY S# DESC;Ans

    4) SELECT S.S#, S.P#, S.QTY * 10 AS QTY2 FROM SWHERE DISCOUNT > 0;Ans

    5) SELECT * FROM S;Ans

    S#P#QTYDiscount45332342010

    S#P#QTYQTY24533453523456720520050

    S#P#QtyDiscount45324533453512323456710205-1105

    Lecture by Prof.Dr.S.Sridhar

  • 6) SELECT S.S#, S.P#, S.QTY,P. P#, P.NAMEFROM S, PWHERE S.P# = P.P# ; SAns ( input)

    Answer

    S JOIN P USING P#Answer is the same as 6..X. in this case only

    S#P#QtyDiscount45324533453445351232343455671020405-110-15

    P#PNAME4532455545354534NUTBOLTSCREENROD

    S.S#S.P#S.QTY45324534453512334556710405

    P#PNAME453245344535NUTROD SCREEN

    Lecture by Prof.Dr.S.Sridhar

  • 8) SELECT COUNT ( * ) AS N FORM S;Ans Count = N = 49) SELECT MAX ( S.QTY) AS MAXQ, MIN (S.QTY) AS MINQFROM SWHERE S. DISCOUNT = -1;Answer MAXQ = 40MINQ = 1010) UPDATE Operations:INSERT INTO P ( P#, PNMAE)VALUES (4536, STRING);

    ?

    Ans DELETE FROM P WHERE P.PNAME = ROD;

    P#PNAME45324555453545344536NUTBOLTSCREENRODSTRING

    P#PNAME4532455545354536NUTBOLTSCREENSTRING

    Lecture by Prof.Dr.S.Sridhar