Presentation is loading. Please wait.

Presentation is loading. Please wait.

Relational Database Constraints & Structured Query Language.

Similar presentations


Presentation on theme: "Relational Database Constraints & Structured Query Language."— Presentation transcript:

1 Relational Database Constraints & Structured Query Language

2 2 Schema based constraints Constraints are conditions that must hold on all valid relation instances. Why needed? It is a requirement of E.F. Codd’s rules These include: 1.Domain constraints 2.Key constraints 3.Entity integrity constraints 4.Referential integrity constraints

3 3 Domain Constraint Within each tuple, the value of each attribute A must be an atomic value from the domain dom(A). Or it could be null, if allowed for that attribute If cust_id was defined to be 6 digit no and a given 4 digit no violates domain constraint)

4 4 Key Constraints Superkey of R: A set of attributes SK of R such that no two tuples in any valid relation instance r(R) will have the same value for SK. That is, for any distinct tuples t1 and t2 in r(R), t1[SK]  t2[SK]. Key of R: A "minimal" superkey; that is, a superkey K such that removal of any attribute from K results in a set of attributes that is not a superkey. Example: The CAR relation schema: CAR(State, Reg#, SerialNo, Make, Model, Year) has two keys Key1 = {State, Reg#}, Key2 = {SerialNo}, both are also superkeys. {SerialNo, Make} is a superkey but not a key.

5 5 In general a relation schema may have more than one key. In this case each of the keys is called candidate keys. If a relation has several candidate keys, one is chosen arbitrarily to be the primary key. The primary key attributes are underlined. If key values are duplicated it violates Key Constraints.

6 6 Entity Integrity Entity Integrity: The primary key attributes PK of each relation schema R in S cannot have null values in any tuple of r(R). This is because primary key values are used to identify the individual tuples. t[PK]  null for any tuple t in r(R) Note: Other attributes of R may be similarly constrained to disallow null values, even though they are not members of the primary key.

7 7 Referential Integrity A constraint involving two relations (the previous constraints involve a single relation). Used to specify a relationship among tuples in two relations: the referencing relation and the referenced relation. Tuples in the referencing relation R 1 have attributes FK (called foreign key attributes) that reference the primary key attributes PK of the referenced relation R 2. A tuple t 1 in R 1 is said to reference a tuple t 2 in R 2 if t 1 [FK] = t 2 [PK]. Note: the domain of FK has the same domain as the primary key attributes PK. A referential integrity constraint can be displayed in a relational database schema as a directed arc from R 1.FK to R 2.PK.

8 8 Referential Integrity Constraint Statement of the constraint The value in the foreign key column (or columns) FK of the the referencing relation R 1 can be either: (1) a value of an existing primary key value of the corresponding primary key PK in the referenced relation R 2,, or.. (2) a null. In case (2), the FK in R 1 should not be a part of its own primary key.

9 9 Other Types of Constraints Semantic Integrity Constraints: -based on application semantics and cannot be expressed by the model. -E.g., “the max. no. of hours per employee for all projects he or she works on is 56 hrs per week”

10 10

11 11

12 12 Update Operations on Relations INSERT a tuple. DELETE a tuple. MODIFY a tuple. Integrity constraints should not be violated by the update operations. Updates may propagate to cause other updates automatically. This may be necessary to maintain integrity constraints.

13 13 Update Operations on Relations In case of integrity violation, several actions can be taken: Cancel the operation that causes the violation (REJECT option) Perform the operation but inform the user of the violation Trigger additional updates so the violation is corrected (CASCADE option, SET NULL option)

14 14 Insert operation Insert into EMPLOYEE (PK is null-violating Entity Integrity constraint) Insert into EMPLOYEE (value already exists- violating Key Constraint) Insert into EMPLOYEE (value does not exists in dept table-violating Referential Integrity constraint)

15 15 Delete operation Delete the WORKS_ON tuple with ESSN = ‘999887777’ and PNO = 10 (Record should exists in the works_on table) Delete the EMPLOYEE tuple with SSN = ‘999887777’ (Violating Referential Integrity constraint – This employee is referencing by other relations) Delete the EMPLOYEE tuple with SSN = ‘333445555’ (Violating Referential Integrity constraint- This employee is referencing by other relations)

16 16 Update operation Update the SALARY of the EMPLOYEE tuple with SSN = ‘999887777’ to 30000 (Provided that domain not violated salary range) Update the DNO of the EMPLOYEE tuple with SSN = ‘999887777’ to 7. (Violating Referential Integrity constraint) Update the SSN of the EMPLOYEE tuple with SSN = ‘999887777’ to ‘987654321’. (Violating Key Constraint / Referential Integrity constraint)

17 Structured Query Language

18 First introduced by E.F Codd in his rules for relational database. SQL is pronounced as “See –que - el” It has many parts Data Definition Language Used to manage database objects, including databases, tables & views Data Manipulation Language Used for inserting, updating, deleting as well as select Data Control Language Manages security part of it. Grant, revoke & deny permissions, to users or groups on single objects or multiple objects (like all tables on a particular schema) Transaction Control Language Begin, commit & Rollback Transaction statements Generally DDL is used by database administrators and database architects & DCL is purely by database administrators DML & TCL are used by all including database users, developers, database administrators and database architects Standard SQL is controlled by ANSI. There are many standards

19 1986: SQL-87. 1989: SQL-89 or FIPS 127-1. 1992: ANSI/ISO SQL-92 or SQL 2, which were stricter than SQL 1, adding some new features and levels of compliance. 1999: SQL3, or ANSI/ISO SQL 1999, with new features, like support for objects. The replaced the levels of compliance with core specifications, as well as additional specifications for nine more packages. 2003: SQL 2003, introducing standardized sequences, XML-related features and identity columns 2006: SQL 2006, defining how to use SQL with XML and enabling applications to integrate XQuery into their existing SQL code. 2008: SQL 2008, introducing INSTEAD OF triggers, as well as the TRUNCATE statement. 2011: SQL 2011 or ISO/IEC 9075:2011, the seventh revision of the ISO (1987) and ANSI (1986) standard for the SQL database query language.

20 Almost ALL major databases support SQL at various levels, but some have their own extensions too. SourceCommon nameFull name ANSI/ISO StandardSQL/PSMSQL/Persistent Stored Modules InterbaseInterbase / FirebirdFirebirdPSQLProcedural SQL IBM DB2SQL PLSQL Procedural Language (implements SQL/PSM) IBM InformixSPLStored Procedural Language IBM NetezzaNetezzaNZPLSQL [2][2](based on Postgres PL/pgSQL) MicrosoftMicrosoft / SybaseSybaseT-SQLTransact-SQL Mimer SQLSQL/PSMSQL/Persistent Stored Module (implements SQL/PSM) MySQLSQL/PSMSQL/Persistent Stored Module (implements SQL/PSM) MonetDBSQL/PSMSQL/Persistent Stored Module (implements SQL/PSM) NuoDBSSPStarkey Stored Procedures OraclePL/SQLProcedural Language/SQL (based on Ada)Ada PostgreSQLPL/pgSQL Procedural Language/PostgreSQL Structured Query Language (implements SQL/PSM) SybaseWatcom-SQLSQL Anywhere Watcom-SQL Dialect TeradataSPLStored Procedural Language SAPSAP HANASQL Script

21 Data Definition Language CREATE DROP ALTER Each statement may have its own additional specifications based on type of object TRUNCATE TABLE RENAME The syntax may differ based on the actual implementation

22 Create database MeetingManagement USE MeetingManagement Create table Room ( RoomID int Identity (1,1) NOT NULL PRIMARY KEY, Room_Name varchar(100) NOT NULL, Capacity int not null, Has_Projector bit not null, Has_SpPhone bit not null ) ALTER TABLE Room ADD IsActive bit not null DEFAULT(1) DROP DATABSE MeetingManagement

23 Data Manipulation language (DML) Used to manage data including retrieving data In contains mainly 4 types of statements, SELECT, INSERT, UPDATE, DELETE MERGE is an additional one combining INSERT, UPDATE & DELETE Using the first letters of CREATE, RETRIEVE, UPDATE & DELETE the word CRUD is used, to describe operations on a Primary Key value SELECT * FROM TABLE WHERE PK = x DELETE TABLE WHERE PK = y SELECT * FROM TABLE WHERE PK in (x1, x2) is a valid SQL statement but not a CRUD operation. Some call SELECT as part of DQL (Data Query Language) and the rest as DML

24 Select Statement SELECT [DISTINCT] [ INTO ] [FROM ] [join specification] [WHERE [ AND | OR | NOT ]] [GROUP BY ] [HAVING [ AND | OR | NOT ]] [ORDER BY ] Except SELECT all parts are optional. If calculation is an aggregation, GROUP BY is applicable

25 Examples: SELECT FName, LName, NICNo, JoinedDate FROM dbo.Employee WHERE JoinedDate >'2003-03-31'

26 INSERT Statement INSERT [INTO]. [(Column List)] VALUES ( ) INSERT [INTO]. [(Column List)] INSERT INTO dbo.Employee SELECT E.NationalIDnumber, P.FirstName, P.LastName, E.Hiredate FROM AdventureWorks2012.HumanResources.Employee E INNER JOIN AdventureWorks2012.Person.Person P ON E.BusinessEntityID=P.BusinessEntityID

27 UPDATE statement UPDATE [..][.] table_name SET { column_name = { expression | NULL } } [,...n ] [ FROM from_clause ] [ WHERE ] UPDATE Employee SET LName ='Balendra' WHERE EmployeeID =291

28 UPDATE Employee SET LName = LastName FROM AdventureWorks2012.HumanResources.Employee E INNER JOIN AdventureWorks2012.Person.Person P ON E.BusinessEntityID=P.BusinessEntityID WHERE Employee.NICNo =E.NationalIDNumber AND Employee.NICNo ='295847284'

29 DELETE Statement DELETE [TOP (n) [PERCENT]] [FROM] WHERE DELETE [TOP (n) [PERCENT]] FROM | [ON ] | WHERE DELETE FROM Employee FROM AdventureWorks2012.HumanResources.Employee E WHERE E.BusinessEntityID=1 and E.NationalIDNumber = Employee.NICNo

30 MERGE statement MERGE [ TOP ( expression ) [ PERCENT ] ] [ INTO ] [ [ AS ] table_alias ] USING ON [ WHEN MATCHED [ AND ] THEN ] [...n ] [ WHEN NOT MATCHED [ BY TARGET ] [ AND ] THEN ] [ WHEN NOT MATCHED BY SOURCE [ AND ] THEN ] [...n ]

31 MERGE Employee AS Target USING ( SELECT E.NationalIDNumber,P.FirstName, P.LastName, E.Hiredate FROM AdventureWorks2012.HumanResources.Employee E INNER JOIN AdventureWorks2012.Person.Person P ON E.BusinessEntityID=P.BusinessEntityID) AS Source (NationalIDNumber, FirstName, LastName, Hiredate) ON Source.NationalIDNumber = Target.NICNo WHEN MATCHED THEN UPDATE SET FName=FirstName,LName=Lastname,JoinedDate=HireDate WHEN NOT MATCHED BY TARGET THEN INSERT (NICNo, FName, LName, JoinedDate) VALUES (NationalIDnumber, FirstName, LastName, Hiredate);

32 Data Control Language GRANT DENY REVOKE GRANT ON [ :: ] ] TO [,...n ] [ WITH GRANT OPTION ] GRANT SELECT ON dbo.Employee TO testuser DENY [ GRANT OPTION FOR ] ON [ class :: ] ] TO [,...n ] [ CASCADE] DENY ALTER ON dbo.Employee TO testuser CASCADE REVOKE [ GRANT OPTION FOR ] ON [ class :: ] ] TO [,...n ] [ CASCADE] REVOKE GRANT OPTION FOR DELETE ON dbo.Employee TO testuser CASCADE

33 Transaction Control Language Transaction is a block on operations which form an atomic nature Generally all DML (including DQL) & DCL can be part of a transaction Most of the DCL too could be part of it, except a few Some Admin features cannot be part of Transactions Major parts of Transactioning… BEGIN TRAN[saction] [ ] COMMIT TRAN ROLLBACK TRAN

34 Transaction management When multiple statements are enclosed with “BEGIN TRANSACTION” and “COMMIT TRANSACTION”: It is called explicit transaction block all the rows affected by those statements behave as part of one atomic unit. When even a single row fails to execute, the whole transaction fails, irrespective of the statement which affected the particular row. When the word “TRANSACTION” is not used, each statement is considered as a separate transaction and independent of other statements (transactions) Each statement is part of separate implicit transaction block If any row fails to execute only the statement which tried the execution will fail. The rest of the statements will execute unless additional error handling statements are included.


Download ppt "Relational Database Constraints & Structured Query Language."

Similar presentations


Ads by Google