SQL Part 1 Much of the material presented

  • Slides: 27
Download presentation
SQL - Part 1 Much of the material presented in these slides was developed

SQL - Part 1 Much of the material presented in these slides was developed by Dr. Ramon Lawrence at the University of Iowa

SQL History n n 1970 - Codd invents relational model and relational algebra SQUARE

SQL History n n 1970 - Codd invents relational model and relational algebra SQUARE language developed 1974 - D. Chamberlin (also at IBM) defined Structured English Query Language (SEQUEL) 1976/1977 - SEQUEL/2 defined and renamed SQL for legal reasons. q n n n n Origin of pronunciation 'See-Quel' but official pronunciation is 'S-Q-L'. 1978 – First commercial implementation by Oracle 1981 – IBM produces SQL/DS 1982 - standardization effort on SQL begins 1986 - became ANSI official standard 1987 - became ISO standard 1992 - SQL 2 (SQL 92) revision 1999 - SQL 3 (supports recursion, object-relational) 2003 - SQL: 2003

SQL Basic Rules Some basic rules for SQL statements: 1. There is a set

SQL Basic Rules Some basic rules for SQL statements: 1. There is a set of reserved words that cannot be used as names for database objects. q SELECT, FROM, WHERE, etc. 2. SQL is generally case-insensitive. q Only exception is string constants. 'FRED' not the same as 'fred'. 3. SQL is free-format and white-space is ignored. 4. The semi-colon is often used as a statement terminator, although that is not part of the standard. 5. Date and time constants have defined format: q DATE 'YYYY-MM-DD' e. g. DATE '1975 -05 -17' q TIME 'hh: mm: ss[. f]' e. g. TIME '15: 00', TIME '08: 30. 5' 6. Two single quotes '' are used to represent a single quote character in a character constant. e. g. 'Master''s'.

SELECT Statement Overview SELECT <list of column expressions> FROM <list of tables and join

SELECT Statement Overview SELECT <list of column expressions> FROM <list of tables and join operations> WHERE <list of logical expressions for rows> GROUP BY <list of grouping columns> HAVING <list of logical expressions for groups> ORDER BY <list of sorting specifications> n Expression: combination of columns, constants, operators, and functions

SQL Queries The query portion of SQL is performed using a SELECT statement. The

SQL Queries The query portion of SQL is performed using a SELECT statement. The general form of the statement is: SELECT A 1, A 2, … , An FROM R 1, R 2, … , Rm WHERE (condition) Notes: n n 1. 2. 3. The "*" is used to select all attributes. Combines the relational algebra operators of selection, projection, and join into a single statement. Comparison operators: =, <>, >, <, >=, <=.

SQL and Relational Algebra n The SELECT statement can be mapped directly to relational

SQL and Relational Algebra n The SELECT statement can be mapped directly to relational algebra. SELECT A 1, A 2, … , An FROM R 1, R 2, … , Rm WHERE P is equivalent to: Π A 1, A 2, …, An (σP (R 1 x R 2 x … x Rm))

Example Relations n Relations: emp (eno, ename, bdate, title, salary, supereno, dno) proj (pno,

Example Relations n Relations: emp (eno, ename, bdate, title, salary, supereno, dno) proj (pno, pname, budget, dno) dept (dno, dname, mgreno) workson (eno, pno, resp, hours) n Foreign keys: q q emp: emp. supereno to emp. eno, emp. dno to dept. dno proj: proj. dno to dept. dno dept: dept. mgreno to emp. eno workson: workson. eno to emp. eno, workson. pno to proj. pno

Example Relation Instances

Example Relation Instances

One Relation Query Example n Return the employee name and salary of all employees

One Relation Query Example n Return the employee name and salary of all employees whose title is 'EE': SELECT name, salary FROM emp WHERE title = 'EE'; Algorithm: Scan each tuple in table and check if matches condition in WHERE clause.

One Relation Query Examples n Return the birth date and salary of employee 'J.

One Relation Query Examples n Return the birth date and salary of employee 'J. Doe': SELECT bdate, salary FROM emp WHERE ename = 'J. Doe'; n Return all information on all employees: SELECT * FROM emp; n * returns all attributes Return the employee number, project number, and number of hours worked where the hours worked is > 50: SELECT eno, pno, hours FROM workson WHERE hours > 50;

Duplicates in SQL n n One major difference between SQL and relational algebra is

Duplicates in SQL n n One major difference between SQL and relational algebra is that relations in SQL are bags instead of sets. q It is possible to have two or more identical rows in a relation. Consider the query: Return all titles of employees. SELECT title FROM emp;

Duplicates in SQL - DISTINCT clause n To remove duplicates, use the DISTINCT clause

Duplicates in SQL - DISTINCT clause n To remove duplicates, use the DISTINCT clause in the SQL statement: SELECT DISTINCT title FROM emp;

Join Operator n n n Most databases have many tables Multiple tables can be

Join Operator n n n Most databases have many tables Multiple tables can be queried in a single SQL statement using the join operator. Specify matching condition q q q Can be any comparison but usually = PK = FK most common join condition Relationship diagram useful when combining tables

Join Example: Cross Product Style • List tables in the FROM clause • List

Join Example: Cross Product Style • List tables in the FROM clause • List join conditions in the WHERE clause • Example: Return the employees who are assigned to the 'Management' department. SELECT ename FROM emp, dept WHERE dname = 'Management' and emp. dno = dept. dno; Note that if you do not specify any join condition to relate them in the WHERE clause, you get a cross product of the tables.

More Join Query Examples n Return the department names and the projects in each

More Join Query Examples n Return the department names and the projects in each department: SELECT dname, pname FROM dept, proj WHERE dept. dno = proj. dno; n Return the employees and the names of their department: SELECT ename, dname FROM emp, dept WHERE emp. dno=dept. dno; n Return all projects who have an employee working on them whose title is 'EE': SELECT pname FROM emp, proj, workson WHERE emp. title = 'EE' and workson. eno=emp. eno and workson. pno = proj. pno;

Alternate Join Query n n Starting in SQL 2, you can specify a join

Alternate Join Query n n Starting in SQL 2, you can specify a join condition directly in the FROM clause instead of the WHERE. Example: Return the employees who are assigned to the 'Management' department: SELECT ename FROM (emp JOIN dept ON emp. dno = dept. dno) WHERE dname = 'Management';

More Alternate Join Query (1992 SQL standard ) SELECT ename FROM emp NATURAL JOIN

More Alternate Join Query (1992 SQL standard ) SELECT ename FROM emp NATURAL JOIN dept; WHERE dname = 'Management'; SELECT ename FROM emp INNER JOIN dept USING (dno) WHERE dname = 'Management'; SELECT ename FROM emp INNER JOIN dept ON emp. dno = dept. dno WHERE dname = 'Management';

Practice Questions n Relational database schema: emp (eno, ename, bdate, title, salary, supereno, dno)

Practice Questions n Relational database schema: emp (eno, ename, bdate, title, salary, supereno, dno) proj (pno, pname, budget, dno) dept (dno, dname, mgreno) workson (eno, pno, resp, hours) n n Return the project names that have a budget > 250000. Return the employees born after July 1, 1970 that have a salary > 35000 and have a title of 'SA' or 'PR'. q Write the equivalent relational algebra expression. Return a list of all department names, the names of the projects of that department, and the name of the manager of each department. Return a list of all distinct combinations of title and salary in the database

Using Dates • Dates are numbers • Date constants and functions are not standard

Using Dates • Dates are numbers • Date constants and functions are not standard Example (Access): SELECT ename FROM emp WHERE bdate BETWEEN #1/1/1965# AND #12/31/1975# Example (My. SQL): SELECT ename FROM emp WHERE bdate BETWEEN '1965 -01 -01' AND '1975 -01 -01'

Advanced Conditions - LIKE n n n For string valued attributes, the LIKE operator

Advanced Conditions - LIKE n n n For string valued attributes, the LIKE operator is used to search for partial matches. q Partial string matches are specified by using either "%" that replaces an arbitrary number of characters or underscore "_“ that replaces a single character. Example: Return all employee names that start with 'A'. SELECT ename FROM emp WHERE ename LIKE 'A%'; Example: Return all employee names who have a first name that starts with 'J' and whose last name is 3 characters long. SELECT ename FROM emp WHERE ename LIKE 'J. _ _ _';

Performance Concerns of LIKE n n Warning: Do not use the LIKE operator if

Performance Concerns of LIKE n n Warning: Do not use the LIKE operator if you do not have to. It is one of the most inefficient operations. The reason is that the DBMS is not able to optimize lookup using LIKE as it can for equal (=) comparisons. The result is the DBMS often has to examine ALL TUPLES in the relation. In almost all cases, adding indexes will not increase the performance of LIKE queries because the indexes cannot be used. q Most indexes are implemented using B-trees that allow for fast equality searching and efficient range searches.

Calculated Fields n Mathematical expressions are allowed in the SELECT clause to perform simple

Calculated Fields n Mathematical expressions are allowed in the SELECT clause to perform simple calculations. q n When an expression is used to define an attribute, the DBMS gives the attribute a unique name such as col 1, col 2, etc. Example: Return how much employee 'A. Lee' will get paid for his work on each project. SELECT ename, pname, salary/52/5/8*hours FROM emp, workson, proj WHERE emp. eno = workson. eno and ename=‘A. Lee’ and proj. pno = workson. pno;

Rename n Often it is useful to be able to rename an attribute in

Rename n Often it is useful to be able to rename an attribute in the final result (especially when using calculated fields). Renaming is accomplished using the keyword AS: SELECT ename, pname, salary/52/5/8*hours AS pay FROM emp, workson, proj WHERE emp. eno = workson. eno and ename=‘A. Lee’ and proj. pno = workson. pno; Note: AS keyword is optional.

Renaming and Aliasing n n Renaming is also used when two or more copies

Renaming and Aliasing n n Renaming is also used when two or more copies of the same table are in a query. Using aliases allows you to uniquely identify what table you are talking about. Example: Return the employees and their managers where the managers make less than the employee. SELECT E. ename, M. ename FROM emp as E, emp as M WHERE E. mgreno = M. eno and E. salary > M. salary;

Advanced Conditions - BETWEEN n n Sometimes the condition in the WHERE clause will

Advanced Conditions - BETWEEN n n Sometimes the condition in the WHERE clause will request tuples where one attribute value must be in a range of values. Example: Return the employees who make at least $20, 000 and less than or equal to $45, 000. We can use the keyword BETWEEN instead: SELECT ename FROM emp WHERE salary >= 20000 and salary <= 45000; SELECT ename FROM emp WHERE salary BETWEEN 20000 and 45000;

Advanced Conditions - IN n To specify that an attribute value should be in

Advanced Conditions - IN n To specify that an attribute value should be in a given set of values, the IN keyword is used. q Example: Return all employees who are in any one of the departments {'D 1', 'D 2', 'D 3'}. SELECT ename FROM emp WHERE dno IN ('D 1', 'D 2', 'D 3'); n Note that this is equivalent to using OR: SELECT ename FROM emp WHERE dno = 'D 1' OR dno = 'D 2' OR dno = 'D 3';

Advanced Conditions - NULL n n Remember NULL is used to indicate that a

Advanced Conditions - NULL n n Remember NULL is used to indicate that a given attribute does not have a value. To determine if an attribute is NULL, we use the clause IS NULL. q Note that you cannot test NULL values using = and <>. Example: Return all employees who are not in a department. SELECT ename FROM emp WHERE dno IS NULL; n Example: Return all departments that have a manager. SELECT dname FROM dept WHERE mgreno IS NOT NULL;