Presentation is loading. Please wait.

Presentation is loading. Please wait.

Database Systems SQL cont. Relational algebra

Similar presentations


Presentation on theme: "Database Systems SQL cont. Relational algebra"— Presentation transcript:

1 Database Systems SQL cont. Relational algebra
Gergely Lukács Pázmány Péter Catholic University Faculty of Information Technology Budapest, Hungary

2 Overview SQL DDL DML Basics Primary key Foreign key
Basic query structure Join

3 SQL Structured Query Language
Relational Database Management Systems (RDBMS) Data Definition Language (DDL) – database schema + Data Manipulation Language (DML) – data (instances) Standard: ANSI (1986), ISO (1987) not completely portable (data types, functions, procedural extension,…) History: 1970s, IBM System R, SEQUEL (Structured Englisch QUEry Language) Renamed Structured Query Language (SQL) ANSI and ISO standard SQL: SQL-86, SQL-89 (integrity constraints), SQL-92 SQL:1999 (recursive queries, triggers, structured types,…) , SQL:2003 (XML, Window functions) , SQL:2006 (XQuery in SQL,…) , SQL:2008

4 Data Definition Language
The SQL data-definition language (DDL) allows the specification of information about relations, including: Tables name, attribute names + data types (domains) Integrity constraints Primary keys Foreign keys NOT NULL CHECK Security and authorization information Parameters for the physical level (storage, indices,…)

5 Primary key, foreign key
a set of attributes uniquely identifying the records in the table two records with same values for the primary key attribute(s) not allowed Primary key attributes automatically NOT NULL Foreign key Referencing table, referenced table An attribute in a table referencing the primary key attribute of another table (or set of attributes … referencing the set of primary key attributes…) No value allowed, for which there is no record in the referenced table

6 Data Types in SQL

7 DDL: CREATE TABLE, ALTER TABLE, DROP TABLE
CREATE TABLE student ( id NUMBER (10) NOT NULL, name VARCHAR2 (100) NOT NULL, tot_cred NUMBER (3), advisor_id NUMBER (10) ); Same effect: CREATE TABLE student ( id NUMBER (10) NOT NULL, name VARCHAR2 (100) NOT NULL, tot_cred NUMBER (3) ); ALTER TABLE student ADD advisor_id NUMBER(10); ALTER TABLE student  MODIFY (tot_cred NUMBER(4, 0)); ALTER TABLE student  DROP  advisor_id;   DROP TABLE student;

8 DDL: CREATE, ALTER TABLE – PRIMARY KEY
ALTER TABLE student ADD CONSTRAINT student_pk PRIMARY KEY ( id ); Alternatives: CREATE TABLE student ( id NUMBER (10) NOT NULL PRIMARY KEY, name VARCHAR2 (100) NOT NULL, tot_cred NUMBER (3), advisor_id NUMBER (10) ); CREATE TABLE student ( id NUMBER (10) NOT NULL, name VARCHAR2 (100) NOT NULL, tot_cred NUMBER (3), advisor_id NUMBER (10), CONSTRAINT student_pk PRIMARY KEY ( id ) );

9 PRIMARY KEY CONSTRAINT VIOLATION
CREATE TABLE student   (      id         NUMBER (10) NOT NULL PRIMARY KEY,      name       VARCHAR2 (100) NOT NULL,      tot_cred   NUMBER (3),      advisor_id NUMBER (10)    ); 

10 NOT NULL CONSTRAINT VIOLATION
CREATE TABLE student   (      id         NUMBER (10) NOT NULL PRIMARY KEY,      name       VARCHAR2 (100) NOT NULL,      tot_cred   NUMBER (3),      advisor_id NUMBER (10)    ); 

11 THE UNIVERSITY SCHEMA, FOREIGN KEY
ALTER TABLE student   ADD CONSTRAINT student_instructor_fk FOREIGN KEY ( advisor_id ) REFERENCES   instructor ( id ); 

12 FOREIGN KEY CONSTRAINT VIOLATION
Instructor

13 MORE EXAMPLES create table student ( ID varchar(5), name varchar(20) not null, dept_name varchar(20), tot_cred numeric(3,0), primary key (ID), foreign key (dept_name) references (department) ); create table takes ( ID varchar(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), grade varchar(2), primary key (ID, course_id, sec_id, semester, year), foreign key (ID) references student, foreign key (course_id, sec_id, semester, year) references section );

14 Basic Query Structure The SQL data-manipulation language (DML) provides the ability to query information, and insert, delete and update tuples A typical SQL query has the form: select A1, A2, ..., An from r1, r2, ..., rm where P; Ai : attributes Ri relations P predicates The result of an SQL query is a relation. 2

15 The select Clause The select clause list the attributes desired in the result of a query corresponds to the projection operation of the relational algebra Example: find the names of all instructors: select name from instructor; Case sensitivity: SQL keywords: case insensitive Table and column names: In Oracle case insensitive MySQL, …. 3

16 The select Clause (Cont.)
SQL allows duplicates in relations as well as in query results. To force the elimination of duplicates, insert the keyword distinct after select. Find the names of all departments with instructor, and remove duplicates select distinct dept_name from instructor; 4

17 The select Clause (Cont.)
An asterisk in the select clause denotes “all attributes” select * from instructor; The select clause can contain arithmetic expressions involving the operation, +, –, , and /, functions, … The query: select ID, name, salary/ from instructor; would return a relation that is the same as the instructor relation, except that the value of the attribute salary is divided by 12. 5

18 The where Clause The where clause specifies conditions that the result must satisfy select name from instructor where dept_name = ‘Comp. Sci.' and salary > 80000 Comparison results can be combined using the logical connectives and, or, and not. Comparisons can be applied to results of arithmetic expressions. 6

19 Joins Id User_id Name 1 2 Bella Tiger 3 Molly Id Name 1 Peter 2 Anna
Cat Person Id Name 1 Peter 2 Anna Id User_id Name 1 Max 2 Jack 3 Duke Dog

20 INNER JOIN SELECT p.id,        p.name,        c.id   AS cat_id,        c.name AS cat_name FROM   jn_person p        INNER JOIN jn_cat c                ON p.id = c.person_id; Old syntax, not recommended SELECT p.id,        p.name,        c.id   AS cat_id,        c.name AS cat_name FROM   jn_person p,        jn_cat c WHERE  p.id = c.person_id; 

21 OUTER JOIN SELECT p.id,        p.name,        c.id   AS cat_id,        c.name AS cat_name FROM   jn_person p        LEFT OUTER JOIN jn_cat c                     ON p.id = c.person_id; 

22 LEFT / RIGHT / FULL OUTER JOIN

23 The Rename Operation The SQL allows renaming relations and attributes using the as clause: old-name as new-name E.g. select ID, name, salary/12 as monthly_salary FROM instructor; Find the names of all instructors who have a higher salary than some instructor in ‘Comp. Sci’. select distinct T. name from instructor as T, instructor as S where T.salary > S.salary and S.dept_name = ‘Comp. Sci.’; Keyword as is optional and may be omitted instructor as T ≡ instructor T Keyword as to be omitted in Oracle 9

24 The Rename Operation + Multiple References to Single Table
select c. name as course_name, pc.name as precondition_name from course c, prereg p, course pc where c.course = p.course_id and p.prereq_id = pc.course_id; Note also the renaming of the result attributes. 9

25 String Operations (useful!)
SQL includes a string-matching operator for comparisons on character strings. The operator “like” uses patterns that are described using two special characters: percent (%). The % character matches any substring. underscore (_). The _ character matches any character. Find the names of all instructors whose name includes the substring “dar”. select name from instructor where name like '%dar%'; Match the string “100 %” like ‘100 \%'

26 String Operations (Cont.)
Patterns are case sensitive. Pattern matching examples: ‘Intro%’ matches any string beginning with “Intro”. ‘%Comp%’ matches any string containing “Comp” as a substring. ‘_ _ _’ matches any string of exactly three characters. ‘_ _ _ %’ matches any string of at least three characters. SQL supports a variety of string operations such as Concatenation converting from upper to lower case (and vice versa) finding string length, extracting substrings, etc. Functions – string, date, …. – very useful in SQL! Differences between DBMS systems.

27 Ordering the Display of Tuples
List in alphabetic order the names of all instructors select distinct name from instructor order bY name; We may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default. Example: order by name desc Can sort on multiple attributes Example: order by dept_name, name

28 Where Clause Predicates
SQL includes a between comparison operator Example: Find the names of all instructors with salary between $90,000 and $100,000 (that is,  $90,000 and  $100,000) select name from instructor where salary between and ; Tuple comparison select name, course_id from instructor, teaches where (instructor.ID, dept_name) = (teaches.ID, ’Biology’); 7

29 Oracle: MINUS, other DBMSs: EXCEPT
Set Operations Find courses that ran in Fall 2009 or in Spring 2010 (select course_id from section where sem = ‘Fall’ and year = 2009) union (select course_id from section where sem = ‘Spring’ and year = 2010) Find courses that ran in Fall 2009 and in Spring 2010 (select course_id from section where sem = ‘Fall’ and year = 2009) INTERSECT (select course_id from section where sem = ‘Spring’ and year = 2010) Find courses that ran in Fall 2009 but not in Spring 2010 (select course_id from section where sem = ‘Fall’ and year = 2009) MINUS (select course_id from section where sem = ‘Spring’ and year = 2010) Oracle: MINUS, other DBMSs: EXCEPT

30 Set Operations Set operations union, intersect, and except
Each of the above operations automatically eliminates duplicates To retain all duplicates use the corresponding multiset versions union all, intersect all and except all.

31 Null Values select name from instructor where salary is null
It is possible for tuples to have a null value, denoted by null, for some of their attributes null signifies an unknown value or that a value does not exist. The result of any arithmetic expression involving null is null Example: 5 + null returns null The predicate is null can be used to check for null values. Example: Find all instructors whose salary is null. select name from instructor where salary is null NULLs are tricky!

32 Null Values and Three Valued Logic
Any comparison with null returns unknown Example: 5 < null or null <> null or null = null Three-valued logic using the truth value unknown: OR: (unknown or true) = true, (unknown or false) = unknown (unknown or unknown) = unknown AND: (true and unknown) = unknown, (false and unknown) = false, (unknown and unknown) = unknown NOT: (not unknown) = unknown “P is unknown” evaluates to true if predicate P evaluates to unknown Result of where clause predicate is treated as false if it evaluates to unknown Functions also for handling the NULL value! E.g.,

33 Relational algebra

34 Relational algebra (1) Relational algebra (RA) is a query language for the relational model with a solid theoretical foundation. Relational algebra is not visible at the user interface level (not in any commercial RDBMS, at least). However, almost any RDBMS uses RA to represent queries internally (for query optimization and execution). Knowledge of relational algebra will help in understanding SQL and relational database systems in general.

35 Relational algebra (2) In mathematics, an algebra is a
set (carrier) and operations that are closed with respect to the set. Example: (N,{∗,+} ) forms an algebra. In case of relational algebra, the carrier is the set of all finite relations.

36 Relation Schema and Instance
A1, A2, …, An are attributes R = (A1, A2, …, An ) is a relation schema Example: instructor = (ID, name, dept_name, salary) Formally, given sets D1, D2, …. Dn a relation r is a subset of D1 x D2 x … x Dn Thus, a relation is a set of n-tuples (a1, a2, …, an) where each ai  Di The current values (relation instance) of a relation are specified by a table An element t of r is a tuple, represented by a row in a table

37 Relations are Unordered
Order of tuples is irrelevant (tuples may be stored in an arbitrary order) Example: instructor relation with unordered tuples

38 Database A database consists of multiple relations
Information about an enterprise is broken up into parts instructor student advisor

39 Select tuples with A=B and D > 5
Selection of tuples Relation r Select tuples with A=B and D > 5 σ A=B and D > 5 (r)

40 Selection of Columns (Attributes)
Relation r: Select A and C Projection Π A, C (r)

41 Joining two relations – Cartesian Product
Relations r, s: r x s:

42 Union of two relations Relations r, s: r  s:

43 Set difference of two relations
Relations r, s: r – s:

44 Set Intersection of two relations
Relation r, s: r  s

45 Joining two relations – Natural Join
Let r and s be relations on schemas R and S respectively. Then, the “natural join” of relations R and S is a relation on schema R  S obtained as follows: Consider each pair of tuples tr from r and ts from s. If tr and ts have the same value on each of the attributes in R  S, add a tuple t to the result, where t has the same value as tr on r t has the same value as ts on s

46 Natural Join Example Relations r, s: Natural Join r s

47


Download ppt "Database Systems SQL cont. Relational algebra"

Similar presentations


Ads by Google