1 chapter 5 the sql language. 2 5.1. data definition language the data definition language (ddl) is...

62
1 Chapter 5 The SQL Language

Upload: francis-carson

Post on 19-Jan-2016

245 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

1

Chapter 5The SQL Language

Page 2: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

2

5.1. Data Definition Language

• The Data Definition Language (DDL) is used to create and destroy databases and database objects

• These commands will primarily be used by database administrators during the setup and removal phases of a database project

• Let's take a look at the structure and usage of four basic DDL commands:

1. CREATE– Installing a database management system (DBMS)

such as SQL Server 2005 on a computer allows you to create and manage many independent databases

Page 3: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

3

– For example, you may want to maintain a database of customer contacts for your sales department and a personnel database for your Human Resource department

– The CREATE command can be used to establish each of these databases on your platform

–  For example, the command:

CREATE DATABASE Employees 

creates an empty database named "Employees" on your DBMS

 

Page 4: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

4

– After creating the database, your next step is to create tables that will contain data  

– Another variant of the CREATE command can be used for this purpose

– The command: 

CREATE TABLE personal_info(first_name varchar(20) NOT NULL, last_name varchar(20) NOT NULL, employee_id int NOT NULL)

Creates a table titled "personal_info" in the current database

Page 5: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

5

– The CREATE TABLE command specifies a new base relation by giving it a name, and specifying each of its attributes and their data types (INTEGER, FLOAT, DECIMAL(i,j), CHAR(n), VARCHAR(n), etc.)

– A constraint NOT NULL may be specified on an attribute

CREATE TABLE dept_info(DNAME VARCHAR(10)

NOT NULL,DNUMBER INTEGER NOT

NULL,EMPLOYEE_ID int );

Page 6: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

6

– The SQL language has many versions– In SQL2, we can use the CREATE TABLE command for

specifying the primary key attributes, and referential integrity constraints (foreign keys)

– Key attributes can be specified via the PRIMARY KEY, FOREIGN KEY, REFERENCES and UNIQUE phrases

CREATE TABLE dept_info(DNAME VARCHAR(10) NOT

NULL,DNUMBER INTEGER NOT NULL,EMPLOYEE_ID int ,PRIMARY KEY (DNUMBER),UNIQUE (DNAME),FOREIGN KEY (EMPLOYEE_ID)

REFERENCES personal_info);

Page 7: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

7

– We can specify CASCADE, SET NULL or SET DEFAULT on referential integrity constraints (foreign keys)

CREATE TABLE dept_info (DNAME VARCHAR(10) NOT NULL,

DNUMBER INTEGER NOT NULL,

EMPLOYEE_ID int,PRIMARY KEY (DNUMBER),UNIQUE (DNAME),FOREIGN KEY (EMPLOYEE_ID)

REFERENCES personal_info ON DELETE SET DEFAULT ON UPDATE CASCADE );

Page 8: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

8

2. USE 

– The USE command allows you to specify the database you wish to work with within your DBMS

– For example, if we are currently working in the sales database and if we want to issue some commands that will affect the employees database, we would preface them with the following SQL command: 

USE Employees 

Page 9: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

9

– For example: USE Employees

CREATE TABLE personal_info(first_name varchar(20) NOT NULL, last_name varchar(20) NOT NULL, employee_id int NOT NULL) CREATE TABLE dept_info(dept_name varchar(20) NOT NULL, dept_id int NOT NULL)Create two tables named "personal_info" and "dept_info“ under the Employee database while you are working on the Sales database

Page 10: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

10

– It's important to always be conscious of the database you are working in before issuing SQL commands that manipulate data

3. ALTER 

– Once you have created a table within a database, you may wish to modify its definition

– The ALTER command allows you to make changes to the structure of a table without deleting and recreating it

Page 11: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

11

– Take a look at the following command: 

ALTER TABLE personal_infoADD salary money null 

– This example adds a new attribute to the personal_info table -- an employee's salary

– The "money" argument specifies that an employee's salary will be stored using a dollars and cents format

– Finally, the "null" keyword tells the database that it's OK for this field to contain no value for any given employee

Page 12: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

12

– Used to add an attribute to one of the base relations

– The new attribute will have NULLs in all the tuples of the relation right after the command is executed; hence, the NOT NULL constraint is not allowed for such an attribute

– Example:

ALTER TABLE personal_info ADD JOB VARCHAR(12);

– The database users must still enter a value for the new attribute JOB for each EMPLOYEE tuple

– This can be done using the UPDATE command

Page 13: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

13

4. DROP 

– The final command of the Data Definition Language, DROP, allows us to remove entire database objects from our DBMS

– For example, if we want to permanently remove the personal_info table that we created, we'd use the following command: 

DROP TABLE personal_info 

– Similarly, the command below would be used to remove the entire employees database: 

DROP DATABASE employees

Page 14: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

14

– Use this command with care! – Remember that the DROP command removes entire data

structures from your database

– If you want to remove individual records, use the DELETE command of the Data Manipulation Language

Page 15: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

15

5.2. Data Manipulation Language

• The Data Manipulation Language (DML) is used to retrieve, insert and modify database information

• These commands will be used by all database users during the routine operation of the database

• Let's take a brief look at the basic DML commands: 1. INSERT 

– The INSERT command in SQL is used to add records to an existing table

– Returning to the personal_info example from the previous section, let's imagine that our HR department needs to add a new employee to their database

Page 16: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

16

– They could use a command similar to the one shown below: 

INSERT INTO personal_infovalues('Abebe',

'Kebede',1,$2000.00)

– Note that there are four values specified for the record

– These correspond to the table attributes in the order they were defined: first_name, last_name, employee_id, and salary

Page 17: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

17

2. SELECT 

– The SELECT command is the most commonly used command in SQL

– It allows database users to retrieve the specific information they desire from an operational database

– Let's take a look at a few examples, again using the personal_info table from our employees database

– The command shown below retrieves all of the information contained within the personal_info table

SELECT *FROM personal_info 

Page 18: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

18

– Note that the asterisk (*) is used as a wildcard in SQL

– This literally means "Select everything from the personal_info table."

– Alternatively, users may want to limit the attributes that are retrieved from the database

– For example, the Human Resources department may require a list of the last names of all employees in the company

– The following SQL command would retrieve only that information: 

Page 19: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

19

SELECT last_nameFROM personal_info 

– Finally, the WHERE clause can be used to limit the records that are retrieved to those that meet specified criteria

– The CEO might be interested in reviewing the personnel records of all highly paid employees

– The following command retrieves all of the data contained within personal_info for records that have a salary value greater than $50,000:

SELECT *FROM personal_infoWHERE salary > $50,000 

Page 20: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

20

3. UPDATE  – The UPDATE command can be used to modify

information contained within a table, either in bulk or individually

– Each year, our company gives all employees a 3% cost-of-living increase in their salary

– The following SQL command could be used to quickly apply this to all of the employees stored in the database: 

UPDATE personal_infoSET salary = salary *

1.03 

Page 21: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

21

– On the other hand, our new employee Almaz Tiku has demonstrated performance above and beyond the call of duty

– Management wishes to recognize her stellar accomplishments with a $5,000 raise

– The WHERE clause could be used to single out Bart for this raise: 

UPDATE personal_infoSET salary = salary +

$5000WHERE employee_id = 2

Page 22: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

22

4. DELETE 

– Finally, let's take a look at the DELETE command

– You'll find that the syntax of this command is similar to that of the other DML commands

– Unfortunately, our latest corporate earnings report didn't quite meet expectations and poor Almaz has been laid off

– The DELETE command with a WHERE clause can be used to remove his record from the personal_info table: 

DELETE FROM personal_infoWHERE employee_id = 2

Page 23: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

23

5.3. Basic Queries in SQL

• SQL has one basic statement for retrieving information from a database; the SELECT statement

• SQL relations can be constrained to be sets by specifying PRIMARY KEY or UNIQUE attributes, or by using the DISTINCT option in a query

• Basic form of the SQL SELECT statement is called a mapping or a SELECT-FROM-WHERE block

SELECT <attribute list>

FROM <table list>

WHERE <condition>

Page 24: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

24

• <attribute list> is a list of attribute names whose values are to be retrieved by the query

• <table list> is a list of the relation names required to process the query

• <condition> is a conditional (Boolean) expression that identifies the tuples to be retrieved by the query

Page 25: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

25

• Consider the following relational database schema corresponding to a COMPANY database

Page 26: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

26

Populated databasefor the relational schema

Page 27: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

27

• Basic SQL queries correspond to using the SELECT, PROJECT, and JOIN operations of the relational algebra

• All subsequent examples use the COMPANY database

• Example of a simple query on one relation

• Query 0: Retrieve the birthdate and address of the employee whose name is 'John B. Smith'.

Q0: SELECT BDATE, ADDRESSFROM EMPLOYEEWHERE FNAME='John' AND

MINIT='B’ AND LNAME='Smith'

Page 28: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

28

• Query 1: Retrieve the name and address of all employees who work for the 'Research' department

Q1: SELECT FNAME, LNAME, ADDRESSFROM EMPLOYEE, DEPARTMENTWHERE DNAME='Research' AND

DNUMBER=DNO

Page 29: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

29

• Query 2: For every project located in 'Stafford', list the project number, the controlling department number, and the department manager's last name, address, and birthdate

Q2: SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS

FROM PROJECT, DEPARTMENT, EMPLOYEE

WHERE DNUM=DNUMBER AND MGRSSN=SSN

ANDPLOCATION='Stafford'

In Q2, there are two join conditions

Page 30: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

30

• The join condition DNUM=DNUMBER relates a project to its controlling department

• The join condition MGRSSN=SSN relates the controlling department to the employee who manages that department

• A missing WHERE-clause indicates no condition; hence, all tuples of the relations in the FROM-clause are selected

• This is equivalent to the condition WHERE TRUE

• Query 3: Retrieve the SSN values for all employees

Q3: SELECT SSNFROM EMPLOYEE

Page 31: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

31

• If more than one relation is specified in the FROM-clause and there is no join condition, then the CARTESIAN PRODUCT of tuples is selected

• Example:

Q4: SELECT SSN,DNAMEFROM EMPLOYEE,DEPARTMENT

• It is extremely important not to overlook specifying any selection and join conditions in the WHERE-clause; otherwise, incorrect and very large relations may result

Page 32: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

32

• To retrieve all the attribute values of the selected tuples, a * is used, which stands for all the attributes

• Examples:

Q5: SELECT *FROM EMPLOYEEWHERE DNO=5

Q6: SELECT *FROM EMPLOYEE, DEPARTMENTWHERE DNAME='Research' AND

DNO=DNUMBER

Page 33: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

33

• SQL does not treat a relation as a set; duplicate tuples can appear

• To eliminate duplicate tuples in a query result, the keyword DISTINCT is used

• For example, the result of Q7 may have duplicate SALARY values whereas Q8 does not have any duplicate values

Q7: SELECT SALARYFROM EMPLOYEE

Q8: SELECT DISTINCT SALARYFROM EMPLOYEE

Page 34: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

34

• SQL has directly incorporated some set operations

• There is a union operation (UNION), and in some versions of SQL there are set difference (MINUS) and intersection (INTERSECT) operations

• The resulting relations of these set operations are sets of tuples; duplicate tuples are eliminated from the result

• The set operations apply only to union compatible relations ; the two relations must have the same attributes and the attributes must appear in the same order

Page 35: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

35

• Query 9: Make a list of all project numbers for projects that involve an employee whose last name is 'Smith' as a worker or as a manager of the department that controls the project

Q9: (SELECT PNAMEFROM PROJECT, DEPARTMENT, EMPLOYEEWHERE DNUM=DNUMBER AND MGRSSN=SSN ANDLNAME='Smith')UNION (SELECT PNAMEFROM PROJECT,

WORKS_ON, EMPLOYEEWHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith')

Page 36: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

36

• A complete SELECT query, called a nested query , can be specified within the WHERE-clause of another query, called the outer query

• Many of the previous queries can be specified in an alternative form using nesting

• Query 10: Retrieve the name and address of all employees who work for the 'Research' department

Q10: SELECT FNAME, LNAME, ADDRESSFROM EMPLOYEEWHERE DNO IN (SELECT

DNUMBERFROM DEPARTMENTWHERE DNAME='Research')

Page 37: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

37

• The nested query selects the number of the 'Research' department

• The outer query select an EMPLOYEE tuple if its DNO value is in the result of either nested query

• The comparison operator IN compares a value v with a set (or multi-set) of values V, and evaluates to TRUE if v is one of the elements in V

• In general, we can have several levels of nested queries• A reference to an unqualified attribute refers to the relation

declared in the innermost nested query• In this example, the nested query is not correlated with the

outer query

Page 38: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

38

• If a condition in the WHERE-clause of a nested query references an attribute of a relation declared in the outer query , the two queries are said to be correlated

• The result of a correlated nested query is different for each tuple (or combination of tuples) of the relation(s) the outer query

• Query 11: Retrieve the name of each employee who has a dependent with the same first name as the employee.

Q11: SELECT E.FNAME,E.LNAME FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN

FROM DEPENDENT WHERE ESSN=E.SSN AND

E.FNAME=DEPENDENT_NAME)

Page 39: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

39

• In Q11, the nested query has a different result for each tuple in the outer query

• A query written with nested SELECT... FROM... WHERE... blocks and using the = or IN comparison operators can always be expressed as a single block query

• For example, Q11 may be written as in Q12

Q12: SELECT E.FNAME, E.LNAMEFROM EMPLOYEE E, DEPENDENT

DWHERE E.SSN=D.ESSN AND

E.FNAME=D.DEPENDENT_NAME

Page 40: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

40

• EXISTS function is used to check whether the result of a correlated nested query is empty (contains no tuples) or not

• Query 13: Retrieve the name of each employee who has a dependent with the same first name as the employee.

Q13: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE EXISTS (SELECT *

FROM DEPENDENTWHERE SSN=ESSN AND

FNAME=DEPENDENT_NAME)

Page 41: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

41

• Query 14: Retrieve the names of employees who have no dependents.

Q14: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE NOT EXISTS (SELECT *

FROM DEPENDENTWHERE SSN=ESSN)

Page 42: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

42

• SQL allows queries that check if a value is NULL (missing or undefined or not applicable)

• SQL uses IS or IS NOT to compare NULLs because it considers each NULL value distinct from other NULL values, so equality comparison is not appropriate

• Query 15: Retrieve the names of all employees who do not have supervisors

Q15: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE SUPERSSN IS NULL

Page 43: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

43

• Note: If a join condition is specified, tuples with NULL values for the join attributes are not included in the result

• In SQL2 we can specify a "joined relation" in the FROM-clause

• Looks like any other relation but is the result of a join

• Allows the user to specify different types of joins (regular "theta" JOIN, NATURAL JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, CROSS JOIN, etc)

Page 44: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

44

• Examples:

Q16: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME

FROM EMPLOYEE E SWHERE E.SUPERSSN=S.SSN

can be written as:

SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME

FROM (EMPLOYEE E LEFT OUTER JOIN EMPLOYEES

ON E.SUPERSSN=S.SSN)

Q17: SELECT FNAME, LNAME, ADDRESSFROM EMPLOYEE, DEPARTMENTWHERE DNAME='Research' AND DNUMBER=DNO

Page 45: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

45

• could be written as:

– SELECT FNAME, LNAME, ADDRESSFROM (EMPLOYEE JOIN

DEPARTMENT ON DNUMBER=DNO)

WHERE DNAME='Research’

or as:

SELECT FNAME, LNAME, ADDRESSFROM (EMPLOYEE NATURAL JOIN

DEPARTMENT AS DEPT(DNAME, DNO, MSSN, MSDATE)

WHERE DNAME='Research’

Page 46: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

46

• Aggregate functions include COUNT, SUM, MAX, MIN, and AVG

• They are used to summarize data in tables• Query 18: Find the maximum salary, the minimum salary, and

the average salary among all employeesQ18: SELECT MAX(SALARY),

MIN(SALARY), AVG(SALARY)

FROM EMPLOYEE

• Some SQL implementations may not allow more than one function in the SELECT-clause

Page 47: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

47

• Query 19: Find the maximum salary, the minimum salary, and the average salary among employees who work for the 'Research' department

Q19: SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)

FROM EMPLOYEE, DEPARTMENTWHERE DNO=DNUMBER AND

DNAME='Research'

Page 48: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

48

• Queries 20: Retrieve the total number of employees in the company

Q20: SELECT COUNT (*)FROM EMPLOYEE

• Queries 21: Retrieve the total number of employees in the 'Research' department

Q21: SELECT COUNT (*)FROM EMPLOYEE,

DEPARTMENTWHERE DNO=DNUMBER AND

DNAME='Research'

Page 49: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

49

• In many cases, we want to apply the aggregate functions to subgroups of tuples in a relation

• Each subgroup of tuples consists of the set of tuples that have the same value for the grouping attribute(s)

• The function is applied to each subgroup independently

• SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause

• Query 22: For each department, retrieve the department number, the number of employees in the department, and their average salary

Page 50: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

50

Q22: SELECT DNO, COUNT (*), AVG (SALARY)FROM EMPLOYEEGROUP BY DNO

• In Q22, the EMPLOYEE tuples are divided into groups--each group having the same value for the grouping attribute DNO

• The COUNT and AVG functions are applied to each such group of tuples separately

• The SELECT-clause includes only the grouping attribute and the functions to be applied on each group of tuples

• A join condition can be used in conjunction with grouping

Page 51: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

51

• Query 23: For each project, retrieve the project number, project name, and the number of employees who work on that project.

Q23: SELECT PNUMBER, PNAME, COUNT (*)

FROM PROJECT, WORKS_ONWHERE PNUMBER=PNOGROUP BY PNUMBER, PNAME

• In this case, the grouping and functions are applied after the joining of the two relations

Page 52: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

52

• Sometimes we want to retrieve the values of these functions for only those groups that satisfy certain conditions

• The HAVING-clause is used for specifying a selection condition on groups (rather than on individual tuples)

•Query 24: For each project on which more than two employees work , retrieve the project number, project name, and the number of employees who work on that project.

Q24: SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME HAVING COUNT (*) > 2

Page 53: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

53

• The LIKE comparison operator is used to compare partial strings

• Two reserved characters are used: '%' (or '*' in some implementations) replaces an arbitrary number of characters, and '_' replaces a single arbitrary character

Query 25: Retrieve all employees whose address is in Houston, Texas. Here, the value of the ADDRESS attribute must contain the substring 'Houston,TX'.

Q25: SELECT FNAME, LNAME FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX%'

Page 54: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

54

Query 26: Retrieve all employees who were born during the 1950s. Here, '5' must be the 8th character of the string (according to our format for date), so the BDATE value is '_______5_', with each underscore as a place holder for a single arbitrary character

Q26: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE BDATE LIKE '_______5_’

• The LIKE operator allows us to get around the fact that each value is considered atomic and indivisible; hence, in SQL, character string attribute values are not atomic

Page 55: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

55

• The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction, multiplication, and division, respectively) can be applied to numeric values in an SQL query result

Query 27: Show the effect of giving all employees who work on the 'ProductX' project a 10% raise.

Q27: SELECT FNAME, LNAME, 1.1*SALARYFROM EMPLOYEE,

WORKS_ON, PROJECTWHERE SSN=ESSN AND

PNO=PNUMBER ANDPNAME='ProductX’

Page 56: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

56

• The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s)Query 28: Retrieve a list of employees and the projects each works in, ordered by the employee's department, and within each department ordered alphabetically by employee last name.

Q28: SELECT DNAME, LNAME, FNAME, PNAME

FROM DEPARTMENT, EMPLOYEE, WORKS_ON,

PROJECTWHERE DNUMBER=DNO AND

SSN=ESSN ANDPNO=PNUMBER

ORDER BY DNAME, LNAME

Page 57: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

57

• The default order is in ascending order of values• We can specify the keyword DESC if we want a descending

order; the keyword ASC can be used to explicitly specify ascending order, even though it is the default

• A query in SQL can consist of up to six clauses, but only the first two, SELECT and FROM, are mandatory. The clauses are specified in the following order:

SELECT <attribute list>FROM <table list>[WHERE <condition>][GROUP BY <grouping attribute(s)>][HAVING <group condition>][ORDER BY <attribute list>]

Page 58: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

58

5.4. Views

• A view is a "virtual" table that is derived from other tables

• Allows for limited update operations (since the table may not physically be stored)

• Allows full query operations• A convenience for expressing certain operations• Views can only select data • Views have several advantages • They enable you to:

– Join data so that users can work with it easily– Aggregate data so that users can work with it easily– Customize data to users' needs

Page 59: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

59

– Hide underlying column names from users

– Limit the columns and rows with which a user works

– Easily secure data

• View specification consists of:

– SQL command CREATE VIEW

• a table (view) name

• a possible list of attribute names (for example, when arithmetic operations are specified or when we want the names to be different from the attributes in the base relations)

Page 60: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

60

• a query to specify the table contents

• Example:– Specify a different WORKS_ON table

CREATE TABLE WORKS_ON_NEW AS

SELECT FNAME, LNAME, PNAME, HOURS

FROM EMPLOYEE, PROJECT, WORKS_ON

WHERE SSN=ESSN AND PNO=PNUMBER

GROUP BY PNAME;

Page 61: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

61

• We can specify SQL queries on a newly create table (view):

SELECT FNAME, LNAME

FROM WORKS_ON_NEW

WHERE PNAME=‘Seena’;

• When no longer needed, a view can be dropped:

DROP WORKS_ON_NEW;

• Update on a single view without aggregate operations: update may map to an update on the underlying base table

Page 62: 1 Chapter 5 The SQL Language. 2 5.1. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database

62

• Views involving joins: an update may map to an update on the underlying base relations

– not always possible

• Views defined using groups and aggregate functions are not updateable

• Views defined on multiple tables using joins are generally not updateable

• WITH CHECK OPTION: must be added to the definition of a view if the view is to be updated

– to allow check for updatability and to plan for an execution strategy