Presentation is loading. Please wait.

Presentation is loading. Please wait.

Database technology Lecture 2: Relational databases and SQL Jose M. Peña

Similar presentations


Presentation on theme: "Database technology Lecture 2: Relational databases and SQL Jose M. Peña"— Presentation transcript:

1 Database technology Lecture 2: Relational databases and SQL Jose M. Peña

2 Database design process

3 3 EMPLOYEE Relational model concepts FNAMEMLNAMESSNBDATEADDRESSSSALARYSUPERSSNDNO RameshKNarayan …M JoyceAEnglish …F AhmadVJabbar …M JamesEBorg …M55000 null1 Tuples... Relation: Set of tuples, i.e. no duplicates are allowed. Database: Collection of relations. Attributes... Relation schema EMPLOYEE ( FNAME, M, LNAME, SSN, BDATE, ADDRESS, S, SALARY, SUPERSSN, DNO)

4 4 Relational model concepts EMPLOYEE FNAMEMLNAMESSNBDATEADDRESSSSALARYSUPERSSNDNO RameshKNarayan …M JoyceNullEnglish …F AhmadVJabbar …M JamesNullBorg …M55000Null1 Domain String shorter than 30 chars Integer 400 < x < 8000 Character M or F yyyy-mm-dd NULL value

5 5 Relational model constraints EMPLOYEE Entity integrity constraint FNAMEMLNAMESSNBDATEADDRESSSSALARYSUPERSSNDNO RameshKNarayan …M JoyceNullEnglish …F AhmadVJabbar …M JamesNullBorg …M55000 Null1

6 6 DEPARTMENT Relational model constraints EMPLOYEE FNAMEMLNAMESSNBDATEADDRESSSSALARYSUPERSSNDNO RameshKNarayan …M JoyceAEnglish …F AhmadVJabbar …M JamesEBorg …M55000 Null1 DNAMEDNUMBERMGRSSNMGRSTARTDATE Research Administration Headquarters Foreign keys Referential integrity constraint

7 7 Relational model constraints (Atomic) domain (or NULL). Key. Entity integrity: A PK cannot take NULL values. Referential integrity: A FK in a relation can only refer to the PK of another relation, and the domains of the FK and PK must coincide, and the FK takes NULL value or values that exist for the PK.

8 8 SQL relational data model SQL relation table attribute column tuple row Used in many DBMSs. Declarative (what data to get, not how). DDL (Data Definition Language)  CREATE, ALTER, DROP Queries  SELECT DML (Data Manipulation Language)  INSERT, DELETE, UPDATE …

9 9 COMPANY schema EMPLOYEE (FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS, SEX, SALARY, SUPERSSN, DNO) DEPT_LOCATIONS (DNUMBER, DLOCATION) DEPARTMENT (DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) WORKS_ON (ESSN, PNO, HOURS) PROJECT (PNAME, PNUMBER, PLOCATION, DNUM) DEPENDENT (ESSN, DEPENDENT-NAME, SEX, BDATE, RELATIONSHIP)

10 10 Create tables CREATE TABLE ( [ ], …, [ ], … );  Data types: Integer, decimal, number, varchar,char, etc.  Constraints: Not null, primary key, foreign key, unique, etc.

11 11 Create tables CREATE TABLE WORKS_ON ( ESSN integer, PNO integer, HOURS decimal(3,1), constraint pk_workson primary key (ESSN, PNO), constraint fk_works_emp FOREIGN KEY (ESSN) references EMPLOYEE(SSN), constraint fk_works_proj FOREIGN KEY (PNO) references PROJECT(PNUMBER) );

12 12 Modify tables Change the definition of a table: Add, delete and modify columns and constraints. ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12); ALTER TABLE EMPLOYEE DROP COLUMN ADDRESS CASCADE; ALTER TABLE WORKS_ON DROP FOREIGN KEY fk_works_emp; ALTER TABLE WORKS_ON ADD CONSTRAINT fk_works_emp FOREIGN KEY (ESSN) REFERENCES EMPLOYEE(SSN); Delete a table and its definition DROP TABLE EMPLOYEE;

13 13 SELECT FROM WHERE ; Attribute list: A 1, …, A r Attributes whose values are required. Table list: R 1, …, R k Relations to be queried Condition: Boolean expression It identifies the tuples that should be retrieved. It may include comparison operators(=, <>, >, >=, etc.) and/or logical operators (and, or, not). Query tables

14 14 FROM EMPLOYEE; SELECT SSN Simple query List the SSN for all employees. SELECT FROM SSN

15 15 FROM EMPLOYEE WHERE DNO = 5; SELECT FNAME, MINIT, LNAME,SSN, BDATE, ADDRESS, SEX, SALARY, SUPERSSN, DNO Use of * List all information about the employees of department 5. SELECT FROM WHERE SELECT * FROM EMPLOYEE WHERE DNO = 5; or Comparison operators {=, <>, >, =>, etc.}

16 16 List the last name, birth date and address for all employees whose name is `Alicia J. Zelaya‘. Simple query SELECT FROM EMPLOYEE WHERE LNAME BDATE ADDRESS Zelaya Castle, Spring, TX FNAME = ‘Alicia’ AND MINIT = ‘J’ AND LNAME = ‘Zelaya’; LNAME, BDATE, ADDRESS Logical operators {and, or, not}

17 17 Pattern matching List the birth date and address for all employees whose last name contains the substring ‘aya’. SELECT BDATE, ADDRESS FROM EMPLOYEE WHERE LNAME LIKE ‘%aya%’; LIKE comparison operator % replaces 0 or more characters _ replaces a single character LNAME BDATE ADDRESS Zelaya Castle, Spring, TX Narayan Fire Oak, Humble, TX

18 18 Tables as sets List all salaries. SELECT SALARY FROM EMPLOYEE; SALARY

19 19 Tables as sets SQL considers a table as a multi-set (bag), i.e. tuples can occur more than once in a table. This is different in a relational model. Why?  Removing duplicates is expensive.  User may want information about duplicates.  Aggregation operators.

20 20 Example List all salaries. SELECT SALARY FROM EMPLOYEE; SALARY SALARY List all salaries without duplicates. SELECT DISTINCT SALARY FROM EMPLOYEE;

21 21 Retrieve the first names of all people in the database. SELECT FNAME FROM EMPLOYEE UNION SELECT DEPENDENT_NAME FROM DEPENDENT; Which department managers have dependents? Show their SSN. SELECT MGRSSN FROM DEPARTMENT INTERSECT SELECT ESSN FROM DEPENDENT; Set operations Queries can be combined by set operations: UNION, INTERSECT, EXCEPT (MySQL only supports UNION) Duplicate tuples are removed. E D M DE

22 22 Ambiguous names: Aliasing What if the same attribute name is used in different relations ?  No alias SELECT NAME, NAME FROM EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER;  Whole name SELECT EMPLOYEE.NAME, DEPARTMENT.NAME FROM EMPLOYEE, DEPARTMENT WHERE EMPLOYEE.DNO=DEPARTMENT.DNUMBER;  Alias SELECT E.NAME, D.NAME FROM EMPLOYEE E, DEPARTMENT D WHERE E.DNO=D.DNUMBER;

23 23 Join: Cartesian product List all employees and the names of their departments. SELECT LNAME, DNAME FROM EMPLOYEE, DEPARTMENT; LNAME DNAME Smith Research Wong Research Zelaya Research Wallace Research Narayan Research English Research Jabbar Research Borg Research Smith Administration Wong Administration Zelaya Administration Wallace Administration Narayan Administration English Administration Jabbar Administration Borg Administration Smith Headquarters Wong Headquarters Zelaya Headquarters Wallace Headquarters Narayan Headquarters English Headquarters Jabbar Headquarters Borg Headquarters Research Administration headquarters DNAMEDEPARTMENTDNUM Smith Wong Zelaya Wallace Narayan English Jabbar Borg LNAMEEMPLOYEEDNO

24 24 Join: Equijoin Equijoin List all employees and the names of their departments. SELECT LNAME, DNAME FROM EMPLOYEE, DEPARTMENT WHERE DNO = DNUMBER; Thetajoin {=, <>, >, =>, <=, !=} LNAME DNO DNAME DNUMBER Smith5 Research 5 Wong5 Research 5 Zelaya4 Research 5 Wallace4 Research 5 Narayan5 Research 5 English 5 Research 5 Jabbar 4 Research 5 Borg 1 Research 5 Smith 5 Administration 4 Wong 5 Administration 4 Zelaya 4 Administration 4 Wallace4 Administration 4 Narayan5 Administration 4 English 5 Administration 4 Jabbar 4 Administration 4 Borg 1 Administration 4 Smith 5 Headquarters 1 Wong 5 Headquarters 1 Zelaya 4 Headquarters 1 Wallace 4 Headquarters 1 Narayan 5 Headquarters 1 English 5 Headquarters 1 Jabbar 4 Headquarters 1 Borg 1 Headquarters 1 Primary key in DEPARTMENT Foreign key in EMPLOYEE Cartesian product

25 25 Join: Self-join List the last name for all employees together with the last names of their bosses. SELECT E.LNAME “Employee”, S. LNAME “Boss” FROM EMPLOYEE E, EMPLOYEE S WHERE E.SUPERSSN = S.SSN; Employee Boss Smith Wong Wong Borg Zelaya Wallace Wallace Borg Narayan Wong English Wong Jabbar Wallace

26 26 Join: Inner join List the last name for all employees together with the last names of their bosses. SELECT E.LNAME “Employee”, S.LNAME “Boss” FROM EMPLOYEE E, EMPLOYEE S WHERE E.SUPERSSN = S.SSN; SELECT E.LNAME “Employee”, S.LNAME “Boss” FROM EMPLOYEE E INNER JOIN EMPLOYEE S ON E.SUPERSSN = S.SSN;

27 27 Join: Outer join List the last name for all employees and, if available, show the last names of their bosses. SELECT E.LNAME “Employee”, S. LNAME “Boss” FROM EMPLOYEE E LEFT JOIN EMPLOYEE S ON E.SUPERSSN = S.SSN; LEFT JOIN, RIGHT JOIN, FULL JOIN Employee Boss Smith Wong Wong Borg Zelaya Wallace Wallace Borg Narayan Wong English Wong Jabbar Wallace Borg NULL

28 28 Joins revisited A1A2 100A nullB 300C nullD B1B2 100W 200X nullY Z AB Cartesian product SELECT * FROM a, b; Equijoin, natural join, inner join SELECT * from A, B WHERE A1=B1; A2A1B1B2 A100 W Bnull100W C300100W Dnull100W A 200X Bnull200X C300200X Dnull200X A100nullY B Y C300nullY D Y A100nullZ B Z C300nullZ D Z A2A1B1B2 A100 W A2A1B1B2 C300100W C300200X Thetajoin SELECT * from A, B WHERE A1>B1;

29 29 Outer joins revisited A1A2 100A nullB 300C nullD B1B2 100W 200X nullY Z AB Full outer join (union of right+left) SELECT * FROM A FULL JOIN b on A1=B1; Left outer join SELECT * FROM A LEFT JOIN B on A1=B1; A2A1B1B2 A100 W C300null B D Right outer join SELECT * FROM A RIGHT JOIN B on A1=B1; A2A1B1B2 A100 W null 200X null Y Z A2A1B1B2 A100 W null 200X null Y Z C300null B D

30 30 Subqueries List all employees that do not have any project assignment with more than 10 hours.  SELECT LNAME FROM EMPLOYEE, WORKS_ON WHERE SSN = ESSN AND HOURS <= 10.0; SELECT LNAME FROM EMPLOYEE WHERE SSN NOT IN (SELECT ESSN FROM WORKS_ON WHERE HOURS > 10.0); Or SELECT LNAME FROM EMPLOYEE WHERE NOT EXISTS (SELECT * FROM WORKS_ON WHERE SSN = ESSN AND HOURS > 10.0); {>, >=, } + {ANY, SOME, ALL} EXISTS

31 31 Extended SELECT syntax SELECT FROM [ WHERE ] [ GROUP BY ] [ HAVING ] [ ORDER BY ];

32 32 Aggregate functions Built-in functions: AVG(), SUM(), MIN(), MAX(), COUNT() They appear only in SELECT and HAVING clauses. NULL values are not considered in the computations. List the total number of employees. SELECT COUNT(*) FROM EMPLOYEE; Null AVG()

33 33 Grouping Used to apply an aggregate function to subgroups of tuples in a relation.  GROUP BY: Grouping attributes.  HAVING: Condition that a group has to satisfy. List, for each department with more than two employees, the department number, the number of employees and the average salary. SELECT DNO, COUNT(*), AVG(SALARY) FROM EMPLOYEE GROUP BY DNO HAVING COUNT(*) > 2; DNO COUNT(*) AVG(SALARY)

34 34 Sort query results Show the department names and their locations in alphabetical order. SELECT DNAME, DLOCATION FROM DEPARTMENT D, DEPT_LOCATIONS DL WHERE D.DNUMBER = DL.DNUMBER ORDER BY DNAME ASC, DLOCATION DESC; DNAME DLOCATION Administration Stafford Headquarters Houston Research Sugarland Research Houston Research Bellaire

35 35 Null values List all employees that do not have a boss. SELECT FNAME, LNAME FROM EMPLOYEE WHERE SUPERSSN IS NULL; ‘ SUPERSSN = NULL’ and ‘SUPERSSN <> NULL’ will not return any matching tuples, because NULL is incomparable to any value, including another NULL.

36 36 Insert data INSERT INTO (,…) VALUES (, …) ; INSERT INTO (, …) ; Store information about how many hours an employee works for the project ’1' into WORKS_ON. INSERT INTO WORKS_ON VALUES ( , 1, 32.5); Integrity constraint! Referential integrity constraint!

37 37 Update data UPDATE SET =,… WHERE ; UPDATE SET (, ….) = ( ) WHERE ; Give all employees in the ‘Research’ department a 10% raise in salary. UPDATE EMPLOYEE SET SALARY = SALARY*1.1 WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME = ‘Research’); Integrity constraint! Referential integrity constraint!

38 38 DEPARTMENT Headquarters Administration Research MGRSSNDNUMBERDNAME Foreign key Delete data DELETE FROM WHERE ; Delete the employees having the last name ‘Borg’ from the EMPLOYEE table. DELETE FROM EMPLOYEE WHERE LNAME = ‘Borg’; EMPLOYEE FNAMEMLNAMESSN RameshKNarayan JoyceAEnglish AhmadVJabbar JamesEBorg ON DELETE SET NUL / DEFAULT / CASCADE ? Referential integrity constraint!

39 39 Views A virtual table derived from another (possibly virtual) tables, i.e. always up-to-date.  CREATE VIEW dept_view AS SELECT DNO, COUNT(*), AVG(SALARY) FROM EMPLOYEE GROUP BY DNO; Why?  Simplify query commands.  Provide data security.  Enhance programming productivity. Update problems.


Download ppt "Database technology Lecture 2: Relational databases and SQL Jose M. Peña"

Similar presentations


Ads by Google