Top Banner
Chapter -7 Chapter -7 SQL – 99 : Schema SQL – 99 : Schema Definition , Basic Definition , Basic Constraints, and Constraints, and Queries Queries
62
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Navathe SQL

Chapter -7Chapter -7

SQL – 99 : Schema SQL – 99 : Schema Definition , Basic Definition , Basic

Constraints, and QueriesConstraints, and Queries

Page 3: Navathe SQL

BackgroundBackground HistoryHistory

SEQUEL (Structured English QUEry Language) – designed and SEQUEL (Structured English QUEry Language) – designed and implemented at IBM Research as the interface for an experimental implemented at IBM Research as the interface for an experimental relational database system called SYSTEM R.relational database system called SYSTEM R.

Joint effort by ANSI(American National Standards Institute) and Joint effort by ANSI(American National Standards Institute) and ISO(International Standards Organization) has led to a standard ISO(International Standards Organization) has led to a standard version of SQL - SQL (ANSI 1986) called SQL1 or SQL86version of SQL - SQL (ANSI 1986) called SQL1 or SQL86

Revised and much expanded version SQL2 or SQL92Revised and much expanded version SQL2 or SQL92 Next version called SQL3 or SQL99Next version called SQL3 or SQL99

SQL is now the standard language for all commercial SQL is now the standard language for all commercial relational DBMSs. Sql -99 is divided into a core specification relational DBMSs. Sql -99 is divided into a core specification which is supposed to be implemented by all RDBMS vendors which is supposed to be implemented by all RDBMS vendors that are SQL-99 compliant plus optional specializedpackage that are SQL-99 compliant plus optional specializedpackage that can be implemented as optional modules to be purchased that can be implemented as optional modules to be purchased independently for specific database applications such as data independently for specific database applications such as data mining, spatial data, temporal data, data warehousing, on-line mining, spatial data, temporal data, data warehousing, on-line analytical procesing(OLAP), multimedia and so on.analytical procesing(OLAP), multimedia and so on.

Page 4: Navathe SQL

44

Features of SQLFeatures of SQL SQL is an English like language. It uses words such as select, insert, delete as part of its SQL is an English like language. It uses words such as select, insert, delete as part of its

command set.command set.

SQL is a non procedural language: we specify SQL is a non procedural language: we specify what information we require, not information we require, not how to get to get it.it.

SQL processes sets of records rather than a single record at a time. The most common SQL processes sets of records rather than a single record at a time. The most common form of a set of records is a table.form of a set of records is a table.

SQL can be used by a range of users including DBAs, application programmers, SQL can be used by a range of users including DBAs, application programmers, management personnel and many other types of end users.management personnel and many other types of end users.

SQL provides command for a variety of tasks including:SQL provides command for a variety of tasks including: - querying data- querying data - inserting, updating and deleting rows in a table- inserting, updating and deleting rows in a table - creating modifying and deleting database objects- creating modifying and deleting database objects - controlling access to the database and database objects- controlling access to the database and database objects - guaranteeing database consistency.- guaranteeing database consistency.

Page 5: Navathe SQL

SQL- a comprehensive database SQL- a comprehensive database language language

Data Definition Language (DDL)Data Definition Language (DDL) Define/re-define database structureDefine/re-define database structure

Data Manipulation Language (DML)Data Manipulation Language (DML) UpdatesUpdates QueriesQueries

Additional facilitiesAdditional facilities ViewsViews Security, authorizationSecurity, authorization Integrity constraintsIntegrity constraints Transaction constraintsTransaction constraints Rules for embedding SQL statements into other Rules for embedding SQL statements into other

languages like Java, C\C++, COBOLlanguages like Java, C\C++, COBOL

Page 6: Navathe SQL

7.1 SQL – DATA DEFINITION7.1 SQL – DATA DEFINITION

Theoretical foundation:Theoretical foundation:

The relational data modelThe relational data model

relationrelation ––tabletable

tupletuple –– rowrow attributeattribute ––

columncolumn

The above terms will be The above terms will be used interchangeably.used interchangeably.

columncolumn11 …… columncolumnnn

<row 2><row 2>

……

<row n><row n>

relation

Attribute1 Attribute2 Attribute2

Page 7: Navathe SQL

77

7.1.1 Schema and Catalog Concepts 7.1.1 Schema and Catalog Concepts in SQLin SQL

Concept of schema was incorporated from SQL2Concept of schema was incorporated from SQL2 To group together tables and other constructs that belong to the same To group together tables and other constructs that belong to the same

database applicationdatabase application An SQL schema is identified by a An SQL schema is identified by a schema nameschema name, and includes an , and includes an

authorization identifierauthorization identifier to indicate the user or account who owns the to indicate the user or account who owns the schema, as well as schema, as well as descriptors descriptors for each element in the schema.for each element in the schema.

Schema Schema elementselements include tables, constraints, views, domains, and other include tables, constraints, views, domains, and other constructs that describe the schema.constructs that describe the schema.

A schema can be assigned a name and authorization identifier, and the A schema can be assigned a name and authorization identifier, and the elements can be defined later. e.g. --elements can be defined later. e.g. --

CREATE SCHEMACREATE SCHEMA COMPANY COMPANY AUTHORIZATIONAUTHORIZATION RITU; RITU; The privilege to create schemas, tables and other constructs must be The privilege to create schemas, tables and other constructs must be

explicitly granted to the relevant user accounts by the system administrator explicitly granted to the relevant user accounts by the system administrator or DBAor DBA

Page 8: Navathe SQL

88

SQL2 uses the concept of a catalogSQL2 uses the concept of a catalog - a named collection of schemas in an SQL - a named collection of schemas in an SQL

environmentenvironment A catalog always contain a special schema called A catalog always contain a special schema called

INFORMATION_SCHEMA, which provides INFORMATION_SCHEMA, which provides information on all the schemas in the catalog and all the information on all the schemas in the catalog and all the element descriptors in these schemas.element descriptors in these schemas.

Integrity constraints such as referential integrity Integrity constraints such as referential integrity constraints can be defined between relations only if constraints can be defined between relations only if they exist in schemas within the same catalog.they exist in schemas within the same catalog.

Schemas within the same catalog can also share certain Schemas within the same catalog can also share certain elements, such as domain definitionselements, such as domain definitions

Page 9: Navathe SQL

Schema diagram for the COMPANY relational database schema

(Page no 106)

Page 10: Navathe SQL
Page 11: Navathe SQL

1111

7.1.2 CREATE TABLE 7.1.2 CREATE TABLE COMMANDCOMMAND

Used to specify a new relation by giving it a name and Used to specify a new relation by giving it a name and specifying its attributes and initial constraintsspecifying its attributes and initial constraints

Each attribute is given a name, a data type to specify its Each attribute is given a name, a data type to specify its domain of values and any attribute constraints such as domain of values and any attribute constraints such as NOT NULLNOT NULL

The key , entity integrity and referential integrity The key , entity integrity and referential integrity constraints can be specified within the CREATE constraints can be specified within the CREATE TABLE statement after the attributes are declared, or TABLE statement after the attributes are declared, or they can be added later using the ALTER TABLE they can be added later using the ALTER TABLE commandcommand

Page 12: Navathe SQL

1212

Syntax of create commandSyntax of create command

CREATE TABLE <table name>CREATE TABLE <table name>( ( <column name> <data type>[(size)]<column <column name> <data type>[(size)]<column

constraint>,constraint>,<column name> <data type>[(size)]<column <column name> <data type>[(size)]<column

constraint>,….constraint>,….…………<table constraint>(<column name>,[,<column <table constraint>(<column name>,[,<column

name>…])….name>…])….

););

Page 13: Navathe SQL

CREATE TABLE empCREATE TABLE emp (( empno integer NOT NULL,empno integer NOT NULL, empname varchar(10),empname varchar(10), job varchar(10) ,job varchar(10) , mgr integer,mgr integer, hiredate date,hiredate date, sal integer,sal integer, comm integer,comm integer, deptno integer not null, deptno integer not null, PRIMARY KEY (empno)PRIMARY KEY (empno) ););

Page 14: Navathe SQL

1414

What is a constraint ?What is a constraint ?

A constraint is a condition or a check applicable on a field or set of fields.A constraint is a condition or a check applicable on a field or set of fields.

Two basic types of constraints are column constraint and table constraint.Two basic types of constraints are column constraint and table constraint.

Constraints ensure database integrity, thus called database integrity Constraints ensure database integrity, thus called database integrity constraints.constraints.

Few of them are :Few of them are : - NOT NULL constraint- NOT NULL constraint - Unique constraint- Unique constraint - Primary key constraint- Primary key constraint - default constraint- default constraint - check constraint- check constraint

Page 15: Navathe SQL

1515

Unique ConstraintUnique ConstraintEnsures that no two rows have the same value in the Ensures that no two rows have the same value in the

specified columns. This constraint can be applied only specified columns. This constraint can be applied only to columns that have also been declared NOT NULL.to columns that have also been declared NOT NULL.

CREATE TABLE empCREATE TABLE emp (( empno integer NOT NULL UNIQUE,empno integer NOT NULL UNIQUE, empname varchar(10),empname varchar(10), job varchar(10) ,job varchar(10) , mgr integer,mgr integer, hiredate date,hiredate date, sal integer,sal integer, comm integer,comm integer, deptno integer not null, deptno integer not null, ););

Page 16: Navathe SQL

1616

Primary Key ConstraintPrimary Key Constraint

Does not allow NULL valueDoes not allow NULL value

Similar to unique constraint except that only one column (or one group Similar to unique constraint except that only one column (or one group of column) can be applied in this constraint.of column) can be applied in this constraint.

CREATE TABLE empCREATE TABLE emp (( empno integer NOT NULL primary key,empno integer NOT NULL primary key, empname varchar(10),empname varchar(10), job varchar(10) ,job varchar(10) , mgr integer,mgr integer, hiredate date,hiredate date, sal integer,sal integer, comm integer,comm integer, deptno integer not null, deptno integer not null, ););

Page 17: Navathe SQL

1717

Default ConstraintDefault Constraint

When a user does not enter a value for the column (having default When a user does not enter a value for the column (having default value), automatically the defined default value is inserted in the field.value), automatically the defined default value is inserted in the field.

CREATE TABLE empCREATE TABLE emp (( empno integer NOT NULL,empno integer NOT NULL, empname varchar(10),empname varchar(10), job varchar(10) ,job varchar(10) , mgr integer,mgr integer, hiredate date,hiredate date, sal integer,sal integer, comm integer default = 15,comm integer default = 15, deptno integer not null, deptno integer not null, PRIMARY KEY (empno)PRIMARY KEY (empno) ););

Page 18: Navathe SQL

1818

Check ConstraintCheck Constraint

Limits the value that can be inserted into a column of a table.Limits the value that can be inserted into a column of a table.CREATE TABLE empCREATE TABLE emp (( empno integer NOT NULL,empno integer NOT NULL, empname varchar(10),empname varchar(10), job varchar(10) ,job varchar(10) , mgr integer,mgr integer, hiredate date,hiredate date, sal integer check (sal >20000),sal integer check (sal >20000), comm integer,comm integer, deptno integer not null, deptno integer not null, PRIMARY KEY (empno)PRIMARY KEY (empno) ););

Page 19: Navathe SQL

1919

Table ConstraintsTable Constraints

When a constraint is to be applied to a group of When a constraint is to be applied to a group of columns of the table, it is called table constraint. columns of the table, it is called table constraint.

Table constraint appears at the end of the table Table constraint appears at the end of the table definitiondefinition

CREATE TABLE membersCREATE TABLE members (( firstname varchar(20) NOT NULL,firstname varchar(20) NOT NULL, lastname varchar(20) NOT NULL,lastname varchar(20) NOT NULL, city char(10),city char(10), PRIMARY KEY (firstname,lastname)PRIMARY KEY (firstname,lastname) ););

Page 20: Navathe SQL

2020

INSERT Command (DML)INSERT Command (DML) INSERT INTO INSERT INTO tablename [(column, tablename [(column,

column,…..)]column,…..)] VALUES VALUES (value, value,…..)(value, value,…..);;INSERT INTO employee ( empno, ename, job, mgr, hiredate, sal, INSERT INTO employee ( empno, ename, job, mgr, hiredate, sal,

comm, deptno )comm, deptno )VALUES (7369, 'SMITH', 'CLERK', 7902, '06/13/1983', 800, NULL, VALUES (7369, 'SMITH', 'CLERK', 7902, '06/13/1983', 800, NULL,

20);20);oror

INSERT INTO EMPlOYEE VALUES (7499, 'ALLEN', INSERT INTO EMPlOYEE VALUES (7499, 'ALLEN', 'SALESMAN', 7698, '08/15/1983', 1600, 300, 30); 'SALESMAN', 7698, '08/15/1983', 1600, 300, 30);

Here the order of values matches the order of columns in the Here the order of values matches the order of columns in the CREATE TABLE command.CREATE TABLE command.

OrOrINSERT INTO EMPLOYEE (empno, deptno) values(9999,10);INSERT INTO EMPLOYEE (empno, deptno) values(9999,10);Only those columns can be omitted that have either default value Only those columns can be omitted that have either default value

defined or they allow NULL values.defined or they allow NULL values.

Page 21: Navathe SQL

2121

TABLES TO BE CREATEDTABLES TO BE CREATED

EMPNO ENAME JOB MGR HIREDATE SAL DEPTNO7369 SMITH CLERK 7902 13-Jun-83 800 207499 ALLEN SALESMAN 7698 15-Aug-83 1600 307521 WARD SALESMAN 7698 26-Mar-84 1250 307566 JONES MANAGER 7839 31-Oct-83 2975 207654 MARTIN SALESMAN 7698 5-Dec-83 1250 307698 BLAKE MANAGER 7839 11-Jun-84 2850 307782 CLARK MANAGER 7839 14-May-84 2450 107788 SCOTT ANALYST 7566 5-Mar-84 3000 207839 KING PRESIDENT 9-Jul-84 5000 107844 TURNER SALESMAN 7698 4-Jun-84 1500 307876 ADAMS CLERK 7788 4-Jun-84 1100 207900 JAMES CLERK 7698 23-Jul-84 950 307902 FORD ANALYST 7566 5-Dec-83 3000 207934 MILLER CLERK 7782 21-Nov-83 1,300 10

DEPTNO DNAME LOCATION10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON

.

EMPLOYEE TABLE

DEPARTMENT TABLE

Page 22: Navathe SQL

SELECT CommandSELECT Command

SELECTSELECT AA11, A, A22, …, A, …, Ann

FROMFROM rr11, r, r22, …, r, …, rmm

WHEREWHERE P;P; AA11, A, A22, …, A, …, Ann – list of attribute names to be retrieved – list of attribute names to be retrieved rr11, r, r22, …, r, …, rmm – List of tables required to process the query – List of tables required to process the query PP – Conditional expression identifying the tuples to be – Conditional expression identifying the tuples to be

retrievedretrieved AND, OR, NOT, <, <=, =, >=, >AND, OR, NOT, <, <=, =, >=, >

Result of the query is a tableResult of the query is a table

Page 23: Navathe SQL

SQL and the relational data modelSQL and the relational data model

Projection Projection Cartesian productCartesian product SelectionSelection Set operationsSet operations

UnionUnion DifferenceDifference IntersectionIntersection

Assignment operatorAssignment operator Rename relationsRename relations

JoinJoin joinjoin EquijoinEquijoin Natural joinNatural join

Page 24: Navathe SQL

2424

PROJECTIONPROJECTION

Q1 To display all the columns of the table employeeQ1 To display all the columns of the table employee

SELECT * from employee;SELECT * from employee;

Q2 To display empno, jab, salaryQ2 To display empno, jab, salary

SELECT empno, job, sal from employee;SELECT empno, job, sal from employee;

Q3 The order of selection determine the order of displayQ3 The order of selection determine the order of display

SELECT job, empno, sal from employee;SELECT job, empno, sal from employee;

Q4 To display the department numbers to which the employees belong to :Q4 To display the department numbers to which the employees belong to :

SELECT deptno from employee;SELECT deptno from employee;

Q5 To display only the distinct department numbers Q5 To display only the distinct department numbers

SELECT distinct deptno from employee;SELECT distinct deptno from employee;

Page 25: Navathe SQL

2525

ARITHMETIC EXPRESSIONSARITHMETIC EXPRESSIONS

Q6 Display the annual salary of all the employeesQ6 Display the annual salary of all the employees SELECT ename, sal*12 from employee;SELECT ename, sal*12 from employee; Q7 SELECT ename, sal + 250 * 12;Q7 SELECT ename, sal + 250 * 12; Q8 SELECT ename, (sal + 250) *12;Q8 SELECT ename, (sal + 250) *12; In Q7 multiplication(250*12) is evaluated first; then salary value In Q7 multiplication(250*12) is evaluated first; then salary value

is added to the result of the multiplication.is added to the result of the multiplication.In Q8 first 250 is added to the salary value and then it is In Q8 first 250 is added to the salary value and then it is

multiplied by 12.multiplied by 12.

If arithmetic expression contains more than one operator, the If arithmetic expression contains more than one operator, the priority is * and / first, then + and – second (left to right if priority is * and / first, then + and – second (left to right if there are several operators with the same priority)there are several operators with the same priority)

Page 26: Navathe SQL

2626

COLUMN ALIASESCOLUMN ALIASES

When displaying the result of the query SQL * Plus normally When displaying the result of the query SQL * Plus normally uses the selected column’s name as the heading. In many cases uses the selected column’s name as the heading. In many cases it may be meaningless.it may be meaningless.

A column alias gives a column an alternative heading on A column alias gives a column an alternative heading on output.output.

Specify the alias after the column in the select list.Specify the alias after the column in the select list.

Q9 Q9 SELECT empname, sal *12 ANNSAL, comm from employee;SELECT empname, sal *12 ANNSAL, comm from employee;

oror SELECT empname, sal *12 as ANNSAL, comm from employee;SELECT empname, sal *12 as ANNSAL, comm from employee;

Page 27: Navathe SQL

2727

CONCATENATION OPERATORCONCATENATION OPERATOR

Q10.SELECT empname || job AS employee_job FROM emp;Q10.SELECT empname || job AS employee_job FROM emp;

oror

SELECT empname + " “ + job AS employee_job FROM emp;SELECT empname + " “ + job AS employee_job FROM emp;

Page 28: Navathe SQL

2828

SQL OperatorsSQL Operators There are four SQL operators which operate with all data types :There are four SQL operators which operate with all data types :

BETWEEN..ANDBETWEEN..AND between two values (inclusive) between two values (inclusive) NOT BETWEEN…AND not between two given valuesNOT BETWEEN…AND not between two given values IN(list)IN(list) match any of the list values match any of the list values NOT IN not in the given list of valuesNOT IN not in the given list of values LIKELIKE match a character pattern match a character pattern NOT LIKE does not match a character patternNOT LIKE does not match a character pattern IS NULLIS NULL is a null value is a null value IS NOT NULL is not a null valueIS NOT NULL is not a null value

Page 29: Navathe SQL

2929

BETWEEN…ANDBETWEEN…AND Q11(a). Those employees whose salary is between 1000 and Q11(a). Those employees whose salary is between 1000 and

2000.2000.

Select ename,sal from employee where sal between 1000 and Select ename,sal from employee where sal between 1000 and 2000;2000;

Q11(b). Those employees whose salary is not between 1000 Q11(b). Those employees whose salary is not between 1000 and 2000.and 2000.

Select ename,sal from employee where sal not between 1000 and Select ename,sal from employee where sal not between 1000 and 2000;2000;

Page 30: Navathe SQL

3030

IN opeartorIN opeartor Q12 To list the employees who belong to department no 10 or Q12 To list the employees who belong to department no 10 or

30.30.

Select eno,ename from employee where deptno in(10,30);Select eno,ename from employee where deptno in(10,30);

Q13 List the details of the employees with employee number Q13 List the details of the employees with employee number 7788,7369,7902,7876.7788,7369,7902,7876.

Select * from employee where eno in(7788,7369,7902,7876);Select * from employee where eno in(7788,7369,7902,7876);

Page 31: Navathe SQL

3131

LIKE OperatorLIKE Operator

% is used for any sequence of zero or more characters% is used for any sequence of zero or more characters - is used for any single character- is used for any single character

Q14(a). List all the employees whose name start with S.Q14(a). List all the employees whose name start with S.

Select ename from employee where ename like ’S%’;Select ename from employee where ename like ’S%’;

Q14(b). List all the employees whose job does not start with M.Q14(b). List all the employees whose job does not start with M.

Select ename from employee where ename not like ’M%’;Select ename from employee where ename not like ’M%’;

Q15. List all employees whose name has 4 characters.Q15. List all employees whose name has 4 characters.

Select ename from employee where ename like ‘----’;Select ename from employee where ename like ‘----’;

Page 32: Navathe SQL

3232

IS NULL operatorIS NULL operator

Q16(a). List the employees who have no manager.Q16(a). List the employees who have no manager.

Select ename,mgr from employee where mgr is null;Select ename,mgr from employee where mgr is null;

Q16(b). List the empoyees who have Manager.Q16(b). List the empoyees who have Manager.

Select ename,mgr from employee where mgr is not null;Select ename,mgr from employee where mgr is not null;

Page 33: Navathe SQL

3333

Querying with multiple conditionsQuerying with multiple conditions

Q17(a) To find all clerks who earn between 1000 and 2000.Q17(a) To find all clerks who earn between 1000 and 2000. Select eno,ename,job,sal from employee where job=‘CLERK’ and sal between Select eno,ename,job,sal from employee where job=‘CLERK’ and sal between

1000 and 2000;1000 and 2000;

Q17(b) To find all employees who are either clerks or who earn between 1000 and Q17(b) To find all employees who are either clerks or who earn between 1000 and 2000.2000.

Select eno, ename, job, sal from employee where job=‘CLERK’ or sal between Select eno, ename, job, sal from employee where job=‘CLERK’ or sal between 1000 and 2000;1000 and 2000;

Q18(a) Find all managers with salariws over 1500 and all salesman.Q18(a) Find all managers with salariws over 1500 and all salesman.Select eno,ename,job,sal from employee where sal>1500 and job=‘MANAGER’ or Select eno,ename,job,sal from employee where sal>1500 and job=‘MANAGER’ or

jab=‘SALESMAN’;jab=‘SALESMAN’;

Q18(b) Find all managers and salesmen with salaries over 1500.Q18(b) Find all managers and salesmen with salaries over 1500.Select eno,ename,job,sal from employee where sal>1500 and (job=‘MANAGER’ or Select eno,ename,job,sal from employee where sal>1500 and (job=‘MANAGER’ or

jab=‘SALESMAN’);jab=‘SALESMAN’);

Page 34: Navathe SQL

3434

ORDER BY clauseORDER BY clause Used to sort the rows. If used, it must be last Used to sort the rows. If used, it must be last

clause in the SELECT statement. The default clause in the SELECT statement. The default order is ascending.order is ascending.

Q19. To sort the table on name.Q19. To sort the table on name.

select * from employee order by ename;select * from employee order by ename;

Q20. To display employees with recently joined first.Q20. To display employees with recently joined first.

select ename,job,hiredate from employee order by date select ename,job,hiredate from employee order by date descdesc;;

Q21. Make a departmentwise list of employees with employee Q21. Make a departmentwise list of employees with employee having the highest salary on the top;having the highest salary on the top;

Select deptno,job,ename from employee order by deptno,sal Select deptno,job,ename from employee order by deptno,sal desc;desc;

Page 35: Navathe SQL

3535

Aggregate FunctionsAggregate Functions They operate on a group of tuples and return a single value.They operate on a group of tuples and return a single value.

avgavg minmin maxmax SumSum countcount count(*)count(*) stddevstddev variancevariance

Page 36: Navathe SQL

3636

Q22. To calculate the total salary of all managers.Q22. To calculate the total salary of all managers.select sum(sal) from employee where job=‘MANAGER’;select sum(sal) from employee where job=‘MANAGER’;Q23. Find the minimum salary earned by the clerk.Q23. Find the minimum salary earned by the clerk.select min(sal) from employee where job=‘CLERK’;select min(sal) from employee where job=‘CLERK’;Q24. To count the total number of employees in department 10.Q24. To count the total number of employees in department 10.select count(*) from employee where deptno=10;select count(*) from employee where deptno=10;Q25. List the minimum, maximum, average salary of all the Q25. List the minimum, maximum, average salary of all the

employees.employees.select max(sal), min(sal), avg(sal) from employee;select max(sal), min(sal), avg(sal) from employee;Q26. Find out how many managers are there.Q26. Find out how many managers are there.select count(*) from employee where job=‘MANAGER’;select count(*) from employee where job=‘MANAGER’;

Page 37: Navathe SQL

The SQL WHERE clauseThe SQL WHERE clause Ex 1, Look for employee infoEx 1, Look for employee info

>> select * from employeeselect * from employee

where fname=’John’;where fname=’John’;

• Ex 3, vector length!

> select x,y,z from vectors

where x > 10 and x*x+y*y+z*z < 200;

Ex 2, Look for employee infoEx 2, Look for employee info

>> select * from employee select * from employee

where bdate > ’1955-01-01’where bdate > ’1955-01-01’

and salary between 30000 and 50000;and salary between 30000 and 50000;

Page 38: Navathe SQL

Rel. algebra Rel. algebra Cartesian productCartesian product

Similar to Cartesian product of two vectorsSimilar to Cartesian product of two vectors

nnn

n

nn

wvwv

wvwv

wwwvvv

1

111

2121

The Cartesian product forms

all possible pairs

of the elements

of the operands

Page 39: Navathe SQL

The SQL FROM clauseThe SQL FROM clauseSimilarly, given two Similarly, given two database tablesdatabase tables

personspersons

AlexAlex

JohnJohn

MikeMike

carscars

AudiAudi

BMWBMW

MercedesMercedes

select *from persons, cars;

AlexAlex AudiAudi

JohnJohn AudiAudi

MikeMike AudiAudi

AlexAlex BMWBMW

JohnJohn BMWBMW

MikeMike BMWBMW

AlexAlex MercedesMercedes

JohnJohn MercedesMercedes

MikeMike MercedesMercedes

, this SQL query generates all possible persons-cars combinations.

x =

More… #

Page 40: Navathe SQL

Select … from … whereSelect … from … where

revisitedrevisited

Relational algebraRelational algebra Cartesian productCartesian product SelectionSelection ProjectionProjection

Basic SQL query: three Basic SQL query: three clausesclausesselectselect <projection-<projection-predicate>predicate>

fromfrom <table list><table list>

wherewhere <selection-predicate><selection-predicate>

Page 41: Navathe SQL

Select – from – whereSelect – from – where

Ex 1: Ex 1: Find all employees working at research deptFind all employees working at research dept

SELECTSELECT EMPLOYEE.LNAME, ADDRESSEMPLOYEE.LNAME, ADDRESSFROMFROM EMPLOYEE, DEPARTMENTEMPLOYEE, DEPARTMENTWHEREWHERE DEPARTMENT.NAME=‘Research’DEPARTMENT.NAME=‘Research’

AND DNUMBER=DNO;AND DNUMBER=DNO;

Ex 2:Ex 2:

SELECTSELECT E.FNAME, E.LNAME, S.FNAME, S.LNAMEE.FNAME, E.LNAME, S.FNAME, S.LNAMEFROMFROM EMPLOYEE E, EMPLOYEE SEMPLOYEE E, EMPLOYEE SWHEREWHERE E.SUPERSSN=S.SSN;E.SUPERSSN=S.SSN;

All employees and their managers

Page 42: Navathe SQL

SQL and the relational data modelSQL and the relational data model

SELECT … FROM … WHERE …SELECT … FROM … WHERE …

projection,projection,

cartesian product,cartesian product,

selectionselection Set operationsSet operations

UnionUnion DifferenceDifference IntersectionIntersection

Assignment operatorAssignment operator Rename relationsRename relations

JoinJoin joinjoin EquijoinEquijoin Natural joinNatural join

Operands must be union compatible

Page 43: Navathe SQL

Examples of set operations Examples of set operations

Retrieve all first names in the databaseRetrieve all first names in the database>> select fname from employeeselect fname from employee

unionunion

select dependent_name from dependent;select dependent_name from dependent;

Are there any projects in a town without Are there any projects in a town without departments?departments?>> select plocation FROM project pselect plocation FROM project p

exceptexcept

select dlocation FROM dept_locations;select dlocation FROM dept_locations;

#

Page 44: Navathe SQL

SQL and the relational data modelSQL and the relational data model

Assignment operatorAssignment operator Rename relationsRename relations

JoinJoin joinjoin EquijoinEquijoin Natural joinNatural join

SELECT … FROM … WHERE …SELECT … FROM … WHERE …

projection,projection,

cartesian product,cartesian product,

selectionselection

Set operationsSet operations Union – Union – unionunion Difference – Difference – exceptexcept Intersection – Intersection – intersectintersect

Page 45: Navathe SQL

Rename, assignmentRename, assignment

Rename: Rename: asas

>> select distinct superssnselect distinct superssnas ’manager social security number’as ’manager social security number’from employee;from employee;

Assignment:Assignment: create tablecreate table … … asas selectselect … …

>> create table names ascreate table names asselect fname from employeeselect fname from employee

unionunion

select dependent_name from select dependent_name from dependent;dependent;

Page 46: Navathe SQL

SQL and the relational data modelSQL and the relational data model

Assignment operatorAssignment operator Rename relationsRename relations

JoinJoin joinjoin EquijoinEquijoin Natural joinNatural join

SELECT … FROM … WHERE …SELECT … FROM … WHERE …

projection,projection,

cartesian product,cartesian product,

selectionselection

Set operationsSet operations Union – Union – unionunion Difference – Difference – exceptexcept Intersection – Intersection – intersectintersect

Page 47: Navathe SQL

JoinJoin

Relational algebra notation: R Relational algebra notation: R CC SS C C – join condition – join condition

C is on the form C is on the form AARR AASS

is one of {=, <, >, is one of {=, <, >, ≤, ≥, ≤, ≥, }} Several terms can be connected as Several terms can be connected as CC11 C C22…C…CKK..

Special casesSpecial cases Equijoin: Equijoin: is is == Natural join: Natural join: All identically named attributes in All identically named attributes in

relations R and S have matching values relations R and S have matching values

Page 48: Navathe SQL

SQL joinSQL join

Recall this queryRecall this querySELECTSELECT EMPLOYEE.LNAME, ADDRESSEMPLOYEE.LNAME, ADDRESSFROMFROM EMPLOYEE, DEPARTMENTEMPLOYEE, DEPARTMENTWHEREWHEREDEPARTMENT.NAME=‘Research’DEPARTMENT.NAME=‘Research’

AND DNUMBER=DNO;AND DNUMBER=DNO;

EquijoinEquijoin of of employeeemployee and and departmentdepartment tables tables w.r.t. employee.dnumber and department.dno.w.r.t. employee.dnumber and department.dno.

Joins are cartesian productsJoins are cartesian productswith some selection criteriawith some selection criteria

Page 49: Navathe SQL

SQL joinSQL join

Another way:Another way: alter table project change pnumber pno int(10);alter table project change pnumber pno int(10);

Page 50: Navathe SQL

One more exampleOne more example

Show the resulting salaries if every Show the resulting salaries if every employee working on the ‘ProductX’ employee working on the ‘ProductX’ project is given a 10 percent raiseproject is given a 10 percent raise

SELECTSELECT FNAME, LNAME, FNAME, LNAME,

1.1*SALARY AS INC_SAL1.1*SALARY AS INC_SAL

FROMFROM EMPLOYEE, WORKS_ON, PROJECTEMPLOYEE, WORKS_ON, PROJECT

WHEREWHERE SSN=ESSNSSN=ESSN

AND PNO=PNUMBERAND PNO=PNUMBER

AND PNAME=‘ProductX’;AND PNAME=‘ProductX’;

Page 51: Navathe SQL

Special comparisonSpecial comparison Matching string patternsMatching string patterns

Use LIKEUse LIKE %% for any number of arbitrary symbol for any number of arbitrary symbol __ for any symbol for any symbol

select * from employee select * from employee

where address like ’%Houston%’;where address like ’%Houston%’;

Approx math equalityApprox math equality Use Use abs(x-xabs(x-x11)) < <

select * from employeeselect * from employee

where abs(salary-30000) < 8000;where abs(salary-30000) < 8000; Use BETWEEN:Use BETWEEN:

select * from employeeselect * from employee

where salary between 22000 and where salary between 22000 and 38000;38000;

Page 52: Navathe SQL

NULL valuesNULL values

Sometimes an attribute isSometimes an attribute is UnknownUnknown (date of birth unknown)(date of birth unknown) Unavailable/withheldUnavailable/withheld (refuses to list home (refuses to list home

phone #)phone #) Not applicapleNot applicaple (last college degree)(last college degree)

Need to represent these cases in a DB!Need to represent these cases in a DB!

Solution: NULL.Solution: NULL. What about logical operations involving NULL?What about logical operations involving NULL?

Need to extend logic…Need to extend logic…

Page 53: Navathe SQL

3-valued logic3-valued logic

ANDAND TRUETRUE FALSEFALSE UNKNOWNUNKNOWN

TRUETRUE TRUETRUE FALSEFALSE UNKNOWNUNKNOWN

FALSEFALSE FALSEFALSE FALSEFALSE FALSEFALSE

UNKNOWNUNKNOWN UNKNOWNUNKNOWN FALSEFALSE UNKNOWNUNKNOWN

OROR TRUETRUE FALSEFALSE UNKNOWNUNKNOWN

TRUETRUE TRUETRUE TRUETRUE TRUETRUE

FALSEFALSE TRUETRUE FALSEFALSE UNKNOWNUNKNOWN

UNKNOWNUNKNOWN TRUETRUE UNKNOWNUNKNOWN UNKNOWNUNKNOWN

NOTNOT TRUETRUE FALSEFALSE UNKNOWNUNKNOWN

FALSEFALSE TRUETRUE UNKNOWNUNKNOWN

Page 54: Navathe SQL

Comparison of NULL valuesComparison of NULL values =, =, , >, <, LIKE, …, >, <, LIKE, …

won’t work. NULL is UNDEFINED!won’t work. NULL is UNDEFINED!

SQL check for NULLSQL check for NULL ISIS NULLNULL IS NOTIS NOT NULLNULL

JOIN operationsJOIN operations Tuples with NULL values in the join columnsTuples with NULL values in the join columns

Not included in resultNot included in result Exception: OUTER JOIN (E/N 8.5.6)Exception: OUTER JOIN (E/N 8.5.6)

Page 55: Navathe SQL

NULLNULL

Find out who is The Big BossFind out who is The Big Bossselect fname, lnameselect fname, lname

from employeefrom employee

where superssn is NULL;where superssn is NULL;

Page 56: Navathe SQL

Aggregate functionsAggregate functions

AvgAvg –– average valueaverage value MinMin –– minimum valueminimum value MaxMax –– maximum valuemaximum value SumSum –– sum of valuessum of values CountCount –– number of valuesnumber of values

Page 57: Navathe SQL

Aggregate functions – group byAggregate functions – group by

Average salaryAverage salaryselect avg(salary)select avg(salary)

from employee;from employee;

Average salary at each departmentAverage salary at each departmentselect dname, avg(salary)select dname, avg(salary)

from employee, department from employee, department

where dno=dnumber group by dno;where dno=dnumber group by dno;

Page 58: Navathe SQL

Aggregate functions – HAVINGAggregate functions – HAVING

Find the projects that more than two employees are Find the projects that more than two employees are assigned to:assigned to: retrieve the project number, retrieve the project number, its name, its name, and the number of its employeesand the number of its employees

SELECT project.pnumber, pname , count(*) SELECT project.pnumber, pname , count(*)

FROM project, works_on FROM project, works_on

WHERE project.pnumber = works_on.pno WHERE project.pnumber = works_on.pno

GROUP BY project.pnumber, pname GROUP BY project.pnumber, pname

HAVING count(*)>2;HAVING count(*)>2;

Page 59: Navathe SQL

SummarySummary

Clauses:Clauses:SELECTSELECT <attribute list><attribute list>

FROMFROM <table list><table list>

[[WHEREWHERE <condition>]<condition>]

[[GROUP BY GROUP BY <grouping attributes><grouping attributes>

[[HAVINGHAVING <group condition>]<group condition>]

[ORDER BY [ORDER BY <attribute list><attribute list>]]

More Than One Way To Do It™…More Than One Way To Do It™…

Page 60: Navathe SQL

ViewsViews

Frequently posed queries should be expressed Frequently posed queries should be expressed as views.as views.

>> create view tax_view as create view tax_view as

select ssn, salary, salary*.327 from select ssn, salary, salary*.327 from employee;employee;

>> select * from tax_view;select * from tax_view;

Page 61: Navathe SQL

ViewsViews

Creating a view will not result in a new table. Views Creating a view will not result in a new table. Views are not tables themselvesare not tables themselves

– – they are they are viewsviews of the underlying tables. of the underlying tables.

A view query will return the state of the underlying A view query will return the state of the underlying tables.tables.

Consequence:Consequence:

underlying tables are changedunderlying tables are changed

the view will changethe view will change

Page 62: Navathe SQL

ViewsViews Ex 1:Ex 1:>> update table employeeupdate table employee

set salary = 1000000set salary = 1000000where ssn = 123456;where ssn = 123456;

>> select * from tax_view;select * from tax_view;

Ex 2:Ex 2:We are removing one column!We are removing one column!>> alter table employee drop salary;alter table employee drop salary;

The view will not work any moreThe view will not work any more>> select * from tax_view;select * from tax_view;