1 / 27

IS8080 Dr. Mario Guimaraes

SQL – DDL. IS8080 Dr. Mario Guimaraes. ISO SQL Data Types. Integrity Constraints. Entity Integrity, Referential Integrity, Enterprise Constraints are typically: Created with create table or alter table command Removed with alter table or drop table command. Check Clause. Required Data

dagmar
Download Presentation

IS8080 Dr. Mario Guimaraes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SQL – DDL IS8080 Dr. Mario Guimaraes

  2. ISO SQL Data Types

  3. Integrity Constraints Entity Integrity, Referential Integrity, Enterprise Constraints are typically: Created with create table or alter table command Removed with alter table or drop table command.

  4. Check Clause • Required Data • position VARCHAR(10) NOT NULL • Domain Constraints • (a) CHECK • sex CHAR NOT NULL • CHECK (sex IN (‘M’, ‘F’))

  5. Enterprise Constraints CREATE ASSERTION AssertionName CHECK (searchCondition) Or simply CHECK (searchCondition) CREATE ASSERTION StaffNotHandlingTooMuch CHECK (NOT EXISTS (SELECT staffNo FROM PropertyForRent GROUP BY staffNo HAVING COUNT(*) > 100))

  6. Entity Integrity • Primary key of a table must contain a unique, non-null value for each row. • ISO standard supports FOREIGN KEY clause in CREATE and ALTER TABLE statements: • PRIMARY KEY(staffNo) • PRIMARY KEY(clientNo, propertyNo) • Can only have one PRIMARY KEY clause per table. Can still ensure uniqueness for alternate keys using UNIQUE: • UNIQUE(telNo)

  7. Referential Integrity • FK is column or set of columns that links each row in child table containing foreign FK to row of parent table containing matching PK. • Referential integrity means that, if FK contains a value, that value must refer to existing row in parent table. • ISO standard supports definition of FKs with FOREIGN KEY clause in CREATE and ALTER TABLE: • FOREIGN KEY(branchNo) REFERENCES Branch

  8. Referential Integrity • Any INSERT/UPDATE that attempts to create FK value in child table without matching candidate key value in parent is rejected. • Action taken that attempts to update/delete a candidate key value in parent table with matching rows in child is dependent on referential action specified using ON UPDATE and ON DELETE subclauses: • CASCADE - SET NULL • SET DEFAULT - NO ACTION

  9. Referential Integrity • CASCADE: Delete row from parent and delete matching rows in child, and so on in cascading manner. • SET NULL: Delete row from parent and set FK column(s) in child to NULL. Only valid if FK columns are NOT NULL. • SET DEFAULT: Delete row from parent and set each component of FK in child to specified default. Only valid if DEFAULT specified for FK columns. • NO ACTION: Reject delete from parent. Default. • Example: FOREIGN KEY (staffNo) REFERENCES Staff ON DELETE SET NULL FOREIGN KEY (ownerNo) REFERENCES Owner ON UPDATE CASCADE

  10. Order of Creating Tables • Creating Table with FK (DDL) • When creating a table Employee that has a FK did referencing Department, one must make sure the Department table has already been created first. • When removing the tables, the order must be the opposite order in which they were created. First remove table Employee that has a FK did referencing Department, then remove table Department. • Department – Parent Table • Employee – Child Table (FK is in the Child) • In Customers-Agents-Orders-Products what tables are parents ?

  11. Create table Example • CREATE TABLE mytable • (myID INTEGER NOT NULL, • myName VARCHAR(40), • CONSTRAINT mytablePK PRIMARY KEY (myID)); TABLE: mytable

  12. View versus Materialized Views • A View is a virtual table that is stored internally as a query. • View in Oracle = Query in MS-Access Define a query in MS-Access Open the query to see the data File Menu -> View Menu -> SQL View • Materialized View = Snapshot. Stores view • As a temporary table, redundant data • May specify a refresh rate, or may be immediately updated. Which is better for queries (SELECT) ? Which is better for INSERTS, UPDATE, and DELETES ?

  13. Views Views Advantages (simplicity, security) • Data independence • Currency • Improved security • Reduced complexity • Convenience • Customization • Data integrity Disadvantages • Update restriction • Structure restriction • Performance

  14. Create View - Example CREATE VIEW StaffPropRent(staffNo) AS SELECT DISTINCT staffNo FROM PropertyForRent WHERE branchNo = ‘B003’ AND rent > 400; CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt) AS SELECT s.branchNo, s.staffNo, COUNT(*) FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo GROUP BY s.branchNo, s.staffNo;

  15. Drop View DROP VIEW ViewName [RESTRICT | CASCADE] For example: DROP VIEW Manager3Staff; Obs. :The CASCADE option will drop all views that were created using the view being dropped.

  16. View Updatability • All updates to base table reflected in all views that encompass base table. • Similarly, may expect that if view is updated then base table(s) will reflect change.

  17. Transactions • SQL defines transaction model based on COMMIT and ROLLBACK. • Transaction is logical unit of work with one or more SQL statements guaranteed to be atomic with respect to recovery. • An SQL transaction automatically begins with a transaction-initiating SQL statement (e.g., SELECT, INSERT). • Changes made by transaction are not visible to other concurrently executing transactions until transaction completes.

  18. Transactions completes • Transaction can complete in one of four ways: - COMMIT ends transaction successfully, making changes permanent. - ROLLBACK aborts transaction, backing out any changes made by transaction. - For programmatic SQL, successful program termination ends final transaction successfully, even if COMMIT has not been executed. - For programmatic SQL, abnormal program end aborts transaction.

  19. Grant GRANT {PrivilegeList | ALL PRIVILEGES} ON ObjectName TO {AuthorizationIdList | PUBLIC} [WITH GRANT OPTION] • PrivilegeList consists of one or more of above privileges separated by commas. • ALL PRIVILEGES grants all privileges to a user. Examples Give Manager full privileges to Staff table. GRANT ALL PRIVILEGES ON Staff TO Manager WITH GRANT OPTION; Give users Personnel and Director SELECT and UPDATE on column salary of Staff. GRANT SELECT, UPDATE (salary) ON Staff TO Personnel, Director; GRANT SELECT ON Branch TO PUBLIC;

  20. Revoke Revoke privilege SELECT on Branch table from all users. REVOKE SELECT ON Branch FROM PUBLIC; Revoke all privileges given to Director on Staff table. REVOKE ALL PRIVILEGES ON Staff FROM Director;

  21. DDL Commands

  22. Hw. 2 - # 11 • List the name of each agent and the sum of orders, in dollars, that each agent ordered (Interactive SQL -> Constructing SQL Queries - advance -> Functions and Group BY) This involves a GROUP BY and a JOIN Also, note that the column you group by must be the same column you project by

  23. Hw. 2, # 16 • List the three most expensive products (one sql statement. Warning: HARD. Use NOT EXISTS) • SELECT pname FROM Products p WHERE NOT EXISTS (SELECT * FROM Products, p1, Products p2, Products p3 WHERE (p.price < p1.price … • May use rownum in ORACLE or TOP function in SQL Server. • NOT EXISTS is generic.

  24. Hw. 2, # 18 • Make cid the primary key of customers • ALTER TABLE Customers ADD CONSTRAINT pkcid primary key (cid); DROP CONSTRAINT pkcid;

  25. Hw. 2, # 19 • Make cid the foreign key of orders • ALTER TABLE Orders ADD Foreign Key (cid) References Customers;

  26. SQL web-site • http://www.w3schools.com/ • http://www.w3schools.com/sql/default.asp

  27. End of Lecture End Of Today’s Lecture.

More Related