Part II - SQL Ddl Dml Select
Part II - SQL Ddl Dml Select
Part II
Tables
Company Database
1
Database Applications Part
2
Database Applications Part
String types
Numeric types
3
Database Applications Part
Date/time type
CREATE TABLE
Specifies a new base relation by giving it a name, and specifying each of its
attributes with their data types.
Figure3: The basic CREATE TABLE statement, defining only columns names, data types and NOT
NULL constraints.
You can use the CREATE TABLE command for specifying the primary key
attributes, candidate keys, and referential integrity constraints (foreign keys).
Key attributes can be specified via the PRIMARY KEY and UNIQUE phrases
4
Database Applications Part
Figure4: CREATE TABLE statement, along with the definition of PRIMARY KEY, UNIQUE key and
FOREIGN KEY.
In the previous statement, the definition of a foreign key, will forbid the system
from deleting a record from another table that has related records in this table.
But, you can use ON DELETE and ON UPDATE, in the FOREIGN KEY
definition, to determine the way of handling the deleting and updating of a record
that has related records in this table.
ON DELETE SET NULL è when deleting a related record in another table, set
the foreign key column to NULL (this can be used if the column is defined as
NULL).
5
Database Applications Part
6
Database Applications Part
To check the creation of a table, you can view a description of it by using the
command DESC.
DESC PERSONS
ALTER TABLE
7
Database Applications Part
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
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.
You can change the default value of a certain column, or even set a new
default value.
You can also change the data type or length of an existing column
You can also add a primary key or a foreign key, if you haven’t added them
in the create statement.
8
Database Applications Part
DROP TABLE
Suppose you need to drop table EMPLOYEE, while it has related records in table
DEPENDENT, the system won’t allow dropping it, unless you give order to cancel
the constraints between the two tables using the CASCADE keyword.
Figure16: Dropping table EMPLOYEE and dropping all constraints relating this table to other tables.
There are three SQL commands to modify the database: INSERT, DELETE, and
UPDATE.
INSERT
9
Database Applications Part
Attribute values should be listed in the same order as the attributes were
specified in the CREATE TABLE command
Syntax:
- The columns are the names of columns you are putting data into, and the
values are that data
- String data must be enclosed in single quotes
- Numbers are not quoted
- You can omit the column names if you supply a value for every column
Example:
In the previous example, we didn’t specify the names of columns since we are
adding values to every column in the table.
The only condition in this case, is to add the values in the order of the columns in
the actual table.
10
Database Applications Part
In Figure18, an Insert statement written and some columns are specified. In this
case only these columns we have to specify their values. But, we should take into
considerations that the other columns in the table can accept NULL values in them,
otherwise they should be specified in the Insert Statement.
Important Note: Only the constraints specified in the DDL commands are
automatically enforced by the DBMS when updates are applied to the database. i.e.
you cannot insert an Employee in a Department that does not exist, because of the
Foreign Key constraint between the two tables.
DELETE
Tuples are deleted from only one table at a time (unless CASCADE is
specified on a referential integrity constraint)
The number of tuples deleted depends on the number of tuples in the relation
that satisfy the WHERE-clause
11
Database Applications Part
UPDATE
Figure20: Example of UPDATE Statement; updating the location and department number of project of
number 10.
Figure21: Updates the salaries of all Employees by giving them a 10% raise.
12
Database Applications Part
SQL has one basic statement for retrieving information from a database; the
SELECT statement
WHERE <condition>
– <table list> is a list of the relation names required to process the query
13
Database Applications Part
Retrieve the birthdate and address of the employee whose name is ‘John B. Smith’.
Note here that (birthdate, address and name are all attributes in one relation
Employee).
14
Database Applications Part
Figure23: Query0
Query1: Retrieve the name and address of all employees who work for the
‘Research’ department.
Note here, that the employee name and address can be accessed from table
EMPLOYEE, but the department name does not exist there, we have to use the
DEPARTMENT table to find it. So, we need to join both EMPLOYEE and
DEPARTMENT tables in the query. (i.e. using the FK).
Figure24: Query1
Query2: For every project located in 'Stafford', list the project number, the
controlling department number, and the department manager's last name, address,
and birthdate.
Figure25: Query2
ALIASES
In SQL, we can use the same name for two (or more) attributes as long as
the attributes are in different relations
A query that refers to two or more attributes with the same name must
qualify the attribute name with the relation name by prefixing the relation
name to the attribute name
Example:
DEPT_LOCATIONS.DNUMBER, DEPARTMENT.DNUMBER
You can change the name of a table in a query, by giving it an aliases that
may be easier to use in a query. Note: That you are not changing the actual name
of a table, only giving it another name in the query.
Query3: For every project located in 'Stafford', list the project number, the
controlling department number, and the department manager's last name, address,
and birth date.
Figure26: Query3
16
Database Applications Part
Query4: For each employee, retrieve the employee's name, and the name of his or
her immediate supervisor.
Note here, that in both cases you will need to retrieve the name of an employee,
either it was an ordinary employee or a supervisor. In both cases they reside in the
table EMPLOYEE. So, we give two aliases to the EMPLOYEE table, and treat it
as two copies of the same table.
Figure27: Query4
Unspecified WHERE-Clause
Figure28: Query5
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.
17
Database Applications Part
Query6:
Figure29: Query6
USE OF *
To retrieve all the attribute values of the selected tuples, a * is used, which stands
for all the attributes.
Query7: Retrieve all attributes of all employees who work in department number
5.
Figure30: Query7
Query8: Retrieve all attributes of all employees along with the attributes of their
departments they work for, as long as they work in the ‘Research’ department.
Figure31: Query8
Use of DISTINCT
18
Database Applications Part
Figure32: Query9
Set Operations
UNION
MINUS
INTERSECT
The two relations must have the same attributes and the attributes must
appear in the same order
Query10: Make a list of all project names 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.
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
19
Database Applications Part
Nesting of Queries
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
Query11: Retrieve the name and address of all employees who work for the
'Research' department.
Figure34: Query11
The outer query select an EMPLOYEE tuple if its DNO value is in the result of
either nested query
20
Database Applications Part
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 the previous example, the nested query is not correlated with the outer query.
The result of a correlated nested query is different for each tuple (or combination
of tuples) of the relation(s) the outer query
Query12: Retrieve the name of each employee who has a dependent with the same
first name as the employee.
Figure35: Query12
In Query12, 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.
21
Database Applications Part
EXISTS is used to check whether the result of a correlated nested query is empty
(contains no tuples) or not
Figure37: Query13.
Figure38: Query14
In Query14, the correlated nested query retrieves all DEPENDENT tuples related
to an EMPLOYEE tuple. If none exist , the EMPLOYEE tuple is selected.
Explicit SETS
Query15: Retrieve the social security numbers of all employees who work on
project number 1, 2, or 3.
22
Database Applications Part
Figure39: Query15.
SQL allows queries that check if a value is NULL (missing or undefined or not
applicable)
Query16: Retrieve the names of all employees who do not have supervisors.
Figure40: Query16
Note: If a join condition is specified, tuples with NULL values for the join
attributes are not included in the result.
Figure41: Query17
Aggregate Functions
Query18: Find the maximum salary, the minimum salary, and the average salary
among all employees.
23
Database Applications Part
Figure42: Query18.
Query19: Find the maximum salary, the minimum salary, and the average salary
among employees who work for the 'Research' department.
Figrue43: Query19.
Figure44: Query20
Figure45: Query21
Grouping
24
Database Applications Part
Each subgroup of tuples consists of the set of tuples that have the same value for
the grouping attribute(s)
SQL has a GROUP BY-clause for specifying the grouping attributes, which must
also appear in the SELECT-clause.
Query22: For each department, retrieve the department number, the number of
employees in the department, and their average salary.
Figure46: Query22
In Query22, 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
Query23: For each project, retrieve the project number, project name, and the
number of employees who work on that project.
Figure47: Query23
25
Database Applications Part
In this case, the grouping and functions are applied after the joining of the two
relations.
The HAVING-Clause
Sometimes we want to retrieve the values of these functions for only those groups
that satisfy certain conditions
Query24: 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.
Figure48: Query24
Substring Comparison
Two reserved characters are used: '%' (or '*' in some implementations) replaces an
arbitrary number of characters, and '_' replaces a single arbitrary character.
Query25: Retrieve all employees whose address is in Houston, Texas. Here, the
value of the ADDRESS attribute must contain the substring 'Houston,TX'.
26
Database Applications Part
Figure49: Query25
Query26: 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.
Figure50: Query26
Arithmetic Operations
The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction,
multiplication, and division, respectively) can be applied to numeric values in an
SQL query result
Query27: Show the effect of giving all employees who work on the 'ProductX'
project a 10% raise.
Figure51: Query27
27
Database Applications Part
ORDER BY
The ORDER BY clause is used to sort the tuples in a query result based on the
values of some attribute(s)
Query28: 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.
Firgure52: Query28.
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:
28
Database Applications Part
The FROM-clause specifies all relations (or aliases) needed in the query but not
those needed in nested queries
The WHERE-clause specifies the conditions for selection and join of tuples from
the relations specified in the FROM-clause
Example: Create a temporary table that has the name, number of employees, and
total salaries for each department.
29
Database Applications Part
Note: The DEPTS_INFO table may not be up-to-date if we change the tuples in
either the DEPARTMENT or the EMPLOYEE relations.
30