0% found this document useful (0 votes)
81 views53 pages

SQL Language - DML and DDL

SQL is a standard language used to define, manipulate, and control access to data in a relational database. It has 4 main components: DDL for defining database structure, DML for populating and querying data, DCL for controlling access, and DQL for querying. Key SQL statements allow users to create tables and other database objects, populate them with data, and perform queries.

Uploaded by

Pixie Music
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views53 pages

SQL Language - DML and DDL

SQL is a standard language used to define, manipulate, and control access to data in a relational database. It has 4 main components: DDL for defining database structure, DML for populating and querying data, DCL for controlling access, and DQL for querying. Key SQL statements allow users to create tables and other database objects, populate them with data, and perform queries.

Uploaded by

Pixie Music
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

SQL ; STANDARD QUERY

LANGUAGE
 A database language should allow a user
to:

• create the database and relation structures;

• perform basic data management tasks, such


as the insertion, modification, and deletion of
data from the relations;

• perform both simple and complex queries.


SQL ; STANDARD QUERY
LANGUAGE
 Major components of SQL
 Data definition language (DDL)
 Data Manipulation Language (DML)
 DCL; Control access to data using e.g. views, grant
privileges etc.

 Data definition language (DDL)


 Define database structure e.g. create tables

 Data Manipulation Language (DML)


 Used to populate and query tables e.g.
 Insert data
 Retrieve data
 Update data
 Delete data
SQL STATEMENTS
 Consists of reserved and user defined
words.
 Reserved; a fixed part of SQL and have fixed
meanings
 User defined; made up by the user according to
certain syntax rules and represent various
database objects e.g. table, column views etc.
 Components of an SQL statement NOT case
sensitive
 Literal characters must be typed exactly as
they are in the database e.g. ‘SMITH’
SQL STATEMENTS
 SELECT/FROM/WHERE
 INSERT/INTO/VALUES
 UPDATE/SET/WHERE
 DELETE FROM/WHERE
DATA DEFINITION
 Allows database objects to be created and destroyed.
 Main data definition statements;
 CREATE SCHEMA DROP SCHEMA
 CREATE DOMAIN ALTER DOMAIN DROP DOMAIN
 CREATE TABLE ALTER TABLE DROP TABLE
 CREATE VIEW DROP VIEW
 CREATE INDEX DROP INDEX
SCHEMAS
 A named collection of database objects and they are
related to one another
 Objects in a schema; tables, views, domains, assertions,
collations, translations and character sets
 All objects in a schema have the same owner and share the
same number of defaults
 Create Schema
CREATE SCHEMA [Name | AUTHORIZATION CreatorIdentifier]

Therefore, if the creator of a schema SqlTests is Smith, the SQL statement is:
CREATE SCHEMA SqlTests AUTHORIZATION Smith;

 Drop schema
DROP SCHEMA Name [RESTRICT | CASCADE]
SQL DATA TYPES
 SQL identifiers; used to identify objects in the database
 Characters used in SQL identifier must be a character set(A..Z, a…b, 0…9,
_ character)
 SQL scalar data types are as outlined;
 Boolean; either TRUE or FALSE
 Character data; defined as CHAR and the length is provided
 Big data; defines bit strings 000’s and 1111’s
 Exact numeric; represents numbers with an exact definition
 INTEGER FOR LARGE NUMBERS
 SMALL INT FOR SMALL NUMBERS
 Approximate numeric ;represents numbers that do not have exact
representations
 Datetime; Defines points in time
 Interval data; represents periods of time
 Large objects; represents image objects
CREATE TABLE
 Create base relations is achieved using the CREATE TABLE statement
 The CREATE TABLE statement incorporates facilities for defining referential
integrity and other constraints

CREATE TABLE TableName


(columName dataType [NOT NULL] [UNIQUE]
[DEFAULT defaultOption] [CHECK (searchCondition)] [, . . . ]}
[PRIMARY KEY (listOfColumns),]
{[UNIQUE (listOfColumns)] [, . . . ]}
{[FOREIGN KEY (listOfForeignKeyColumns)
REFERENCES ParentTableName [(listOfCandidateKeyColumns)]
[MATCH {PARTIAL | FULL}
[ON UPDATE referentialAction]
[ON DELETE referentialAction]] [, . . . ]}
{[CHECK (searchCondition)] [, . . . ]})
CREATE TABLE
CREATE DOMAIN OwnerNumber AS VARCHAR(5)
CHECK (VALUE IN (SELECT ownerNo FROM PrivateOwner));
CREATE DOMAIN StaffNumber AS VARCHAR(5)
CHECK (VALUE IN (SELECT staffNo FROM Staff));
CREATE DOMAIN BranchNumber AS CHAR(4)
CHECK (VALUE IN (SELECT branchNo FROM Branch));
CREATE DOMAIN PropertyNumber AS VARCHAR(5);
CREATE DOMAIN Street AS VARCHAR(25);
CREATE DOMAIN City AS VARCHAR(15);
CREATE DOMAIN PostCode AS VARCHAR(8);
CREATE DOMAIN PropertyType AS CHAR(1)
CHECK(VALUE IN (‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘M’, ‘S’));
CREATE TABLE
CREATE TABLE PropertyForRent(
propertyNo PropertyNumber NOT NULL,
street Street NOT NULL,
city City NOT NULL,
postcode PostCode,
type PropertyType NOT NULL DEFAULT ‘F’,
rooms PropertyRooms NOT NULL DEFAULT 4,
rent PropertyRent NOT NULL DEFAULT 600,
ownerNo OwnerNumber NOT NULL,
staffNo StaffNumber
CONSTRAINT StaffNotHandlingTooMuch
CHECK (NOT EXISTS (SELECT staffNo
FROM PropertyForRent
GROUP BY staffNo
HAVING COUNT(*) > 100)),
branchNo BranchNumber NOT NULL,
PRIMARY KEY (propertyNo),
FOREIGN KEY (staffNo) REFERENCES Staff ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (ownerNo) REFERENCES PrivateOwner ON DELETE NO
ACTION ON UPDATE CASCADE,
FOREIGN KEY (branchNo) REFERENCES Branch ON DELETE NO
ACTION ON UPDATE CASCADE);
ALTER TABLE
 ALTER TABLE statement for changing the structure of a table once it has
been created
 ALTER TABLE options;
 add a new column to a table;
 drop a column from a table;
 add a new table constraint;
 drop a table constraint;
 set a default for a column;
 drop a default for a column.

Statement;
ALTER TABLE TableName
[ADD [COLUMN] columnName dataType [NOT NULL] [UNIQUE]
[DEFAULT defaultOption] [CHECK (searchCondition)]]
[DROP [COLUMN] columnName [RESTRICT | CASCADE]]
[ADD [CONSTRAINT [ConstraintName]] tableConstraintDefinition]
[DROP CONSTRAINT ConstraintName [RESTRICT | CASCADE]]
[ALTER [COLUMN] SET DEFAULT defaultOption]
[ALTER [COLUMN] DROP DEFAULT]
ALTER TABLE
 RESTRICT The DROP operation is rejected if the column is referenced by
another database object (for example, by a view definition). This is the
default setting.
 CASCADE The DROP operation proceeds and automatically drops the column
from any database objects it is referenced by.
 This operation cascades, so that if a column is dropped from a referencing object,
SQL checks whether that column is referenced by any other object and drops it
from there if it is, and so on.

Change the Staff table by removing the default of ‘Assistant’


for the position column and setting the default for the gender
column to female (‘F’).
ALTER TABLE Staff
ALTER position DROP DEFAULT;

ALTER TABLE college.timetable


add default ('Mon') For Day ;
DROP TABLE
 Redundant tables are removed from the database using the
DROP TABLE statement
 Statement;
DROP TABLE TableName [RESTRICT | CASCADE]

Example;
 To remove the PropertyForRent table we use the command:

DROP TABLE PropertyForRent;

 Options for the DROP TABLE command;


 RESTRICT The DROP operation is rejected if there are any
other objects that depend for their existence upon the
continued existence of the table to be dropped.
 CASCADE The DROP operation proceeds and SQL
automatically drops all dependent objects (and objects
dependent on these objects)
 Cascade must be carried out with a lot of caution
CREATING AN INDEX
 An index is a structure that provides accelerated access to the rows of a
table based on the values of one or more columns
 Indexes are usually created to satisfy particular search criteria after the
table has been in use for some time and has grown in size.
 Indexes can be created only on base tables not on views.
 Statement
CREATE [UNIQUE] INDEX IndexName
ON TableName (columnName [ASC | DESC] [, . . . ])

CREATE UNIQUE INDEX StaffNoInd ON Staff (staffNo);


CREATE UNIQUE INDEX PropertyNoInd ON PropertyForRent (propertyNo);

 DROP INDEX
DROP INDEX IndexName
example
DROP INDEX StaffNoInd;
VIEWS
 The dynamic result of one or more relational operations operating on the base
relations to produce another relation.
 A view is a virtual relation that does not necessarily exist in the database but
can be produced upon request by a particular user, at the time of request.
 To create a view successfully, you must have SELECT privilege on all the tables
referenced in the subselect and USAGE privilege on any domains used in
referenced columns.
 Statement
CREATE VIEW ViewName [(newColumnName [, . . . ])]
AS subselect [WITH [CASCADED | LOCAL] CHECK OPTION]

Example
CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt)
AS SELECT s.branchNo, s.staffNo, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo
GROUP BY s.branchNo, s.staffNo;
 One of the most frequent reasons for using views is to simplify multi-table
queries.
 DROP VIEW statement is used to remove a view from the database, CASCADE
and RESTRICT may be used.
RESTRICTIONS ON VIEWS
 WHERE clause cannot be used on a column derived by an aggregate function
 Query below would fail;
SELECT *
FROM StaffPropCnt
WHERE count > 2;
 A grouped view may never be joined with a base table or a view
 i.e. a view grouping average salaries of members working for
different departments cannot be joined with other base
tables or views
VIEW UPDATABILITY
Views can be updated only if the following conditions are met;
 DISTINCT is not specified; that is, duplicate rows must not be
eliminated from the query results.
 Every element in the SELECT list of the defining query is a
column name (rather than a constant, expression, or aggregate
function) and no column name appears more than once.
 The FROM clause specifies only one table; that is, the view
must have a single source table for which the user has the
required privileges. If the source table is itself a view, then
that view must satisfy these conditions. This, therefore,
excludes any views based on a join, union (UNION), intersection
(INTERSECT), or difference (EXCEPT).
 The WHERE clause does not include any nested SELECTs that
reference the table in the FROM clause.
 There is no GROUP BY or HAVING clause in the defining query.
 In addition, every row that is added through the view must not
violate the integrity constraints of the base table.
VIEWS
 Advantages  Disadvantages
 Data  Update restriction
independence
 Currency  Structure restriction

 Improved security  Performance

 Reduced complexity
 Convenience
 Customization
 Data integrity
TRANSACTIONS
 A transaction is a logical unit of work consisting of one or more
SQL statements that is guaranteed to be atomic with respect to
recovery.
 An SQL transaction automatically begins with a transaction-
initiating SQL statement executed by a user or program (e.g.
SELECT, INSERT, UPDATE)
 Changes made by a transaction are not visible to other
concurrently executing transactions until the transaction
completes
 A transaction can complete in one of four ways:
 A COMMIT statement ends the transaction successfully, making the database
changes permanent. A new transaction starts after COMMIT with the next
transaction-initiating statement.
 A ROLLBACK statement aborts the transaction, backing out any changes made
by the transaction. A new transaction starts after ROLLBACK with the next
transaction initiating statement.
 For programmatic SQL, successful program termination ends the final
transaction successfully, even if a COMMIT statement has not been executed.
 For programmatic SQL, abnormal program termination aborts the transaction.
TRANSACTIONS
 Statement;
SET TRANSACTION
[READ ONLY | READ WRITE] |
[ISOLATION LEVEL READ UNCOMMITTED | READ COMMITTED |
REPEATABLE READ | SERIALIZABLE]

 The READ ONLY and READ WRITE qualifiers indicate whether the
transaction is read only or involves both read and write
operations.
 READ ONLY allows a transaction to issue INSERT, UPDATE, and
DELETE statements against temporary tables
 The isolation level indicates the degree of interaction that is
allowed from other transactions during the execution of the
transaction
TRANSACTIONS
 Isolation Levels prevent the following occurrences;
 Dirty read; A transaction reads data that has been written by another as yet
uncommitted transaction.
 Non repeatable read A transaction rereads data it has previously read but
another committed transaction has modified or deleted the data in the
intervening period.
 Phantom read A transaction executes a query that retrieves a set of rows
satisfying a certain search condition. When the transaction re-executes the
query at a later time additional rows are returned that have been inserted by
another committed transaction in the intervening period.

Isolation level Dirty read Nonrepeatable Phantom


read read
 

READ UNCOMMITTED Y Y Y
READ COMMITTED N Y Y
REPEATABLE READ N N Y
SERIALIZABLE N N N
TRANSACTIONS
 Read uncommitted
 thelowest level where transactions are isolated
only enough to ensure that physically corrupt
data is not read
 Read committed
 Database Engine default level
 Repeatable read
 Serializable
 the
highest level, where transactions are
completely isolated from one another
ACCESS CONTROL
Modern DBMSs typically provide one or both of the following
authorization mechanisms:
 Discretionary access control[

 Each user is given appropriate access rights (or privileges) on


specific database objects.
 Typically users obtain certain privileges when they create an
object and can pass some or all of these privileges to other
users at their discretion.
 Although flexible, this type of authorization mechanism can be
circumvented by a devious unauthorized user tricking an
authorized user into revealing sensitive data.
 Mandatory access control[
 Each database object is assigned a certain classification level

(for example, Top Secret, Secret, Confidential, Unclassified)


and each subject (for example, users, programs) is given a
designated clearance level
SQL supports only discretionary access control
through the GRANT and REVOKE statements.
PRIVILEGES
 Privileges are the actions that a user is permitted to
carry out on a given base table or view

 The privileges defined by the ISO standard are:


 SELECT – the privilege to retrieve data from a table;
 INSERT – the privilege to insert new rows into a table;
 UPDATE – the privilege to modify rows of data in a table;
 DELETE – the privilege to delete rows of data from a table;
 REFERENCES – the privilege to reference columns of a named
table in integrity constraints;
PRIVILEGES
 When a user creates a table using the CREATE TABLE
statement, he or she automatically becomes the
owner of the table and receives full privileges for the
table.
 When a user creates a view with the CREATE VIEW
statement, he or she automatically becomes the
owner of the view, but does not necessarily receive
full privileges on the view.
 To create the view, a user must have SELECT privilege
on all the tables that make up the view and
REFERENCES privilege on the named columns of the
view.,
 The view owner gets INSERT, UPDATE, and DELETE
privileges only if he or she holds these privileges for
every table in the view.
GRANTING PRIVILEGES
 The GRANT statement is used to grant privileges on database
objects to specific users.
 Privileges that can be granted; select, update, delete, insert and
references and they can all be granted using the keyword ALL
PRIVILEGES
 It also provides the keyword PUBLIC to allow access to be
granted to all present and future authorized users, not just to
the users currently known to the DBMS
 The WITH GRANT OPTION clause allows the user(s) in
AuthorizationIdList to pass the privileges they have been given
for the named object on to other users.
 Grant Statement;
GRANT {PrivilegeList | ALL PRIVILEGES}
ON ObjectName
TO {AuthorizationIdList | PUBLIC}
[WITH GRANT OPTION]
GRANTING PRIVILEGES
 GRANT all privileges
Give the user with authorization identifier Manager full privileges to
the Staff table.
GRANT ALL PRIVILEGES
ON Staff
TO Manager WITH GRANT OPTION;
 GRANT specific privileges
Give users Personnel and Director the privileges SELECT and UPDATE
on column salary of the Staff table.
GRANT SELECT, UPDATE (salary)
ON Staff
TO Personnel, Director;
 GRANT privileges to the PUBLIC
Give all users the privilege SELECT on the Branch table.
GRANT SELECT
ON Branch
TO PUBLIC;
REVOKING PRIVILEGES
 The REVOKE statement is used to take away privileges that were
granted with the GRANT statement.
 A REVOKE statement can take away all or some of the privileges
that were previously granted to a user.
 REVOKE Statement;
REVOKE [GRANT OPTION FOR] {PrivilegeList | ALL
PRIVILEGES}
ON ObjectName
FROM {AuthorizationIdList | PUBLIC} [RESTRICT | CASCADE]
REVOKING PRIVILEGES
 REVOKE specific privileges from PUBLIC
Revoke the privilege SELECT on the Branch table from all users.
REVOKE SELECT
ON Branch
FROM PUBLIC;

 REVOKE specific privileges from named user


Revoke all privileges you have given to Director on the Staff table.
REVOKE ALL PRIVILEGES
ON Staff
FROM Director;
SELECT STATEMENT
 Its purpose, to retrieve and display data
from one or more tables
SELECT [DISTINCT | ALL] {* | [columnExpression [AS newName]] [, . . ]}
FROM TableName [alias] [, . . . ]
[WHERE condition]
[GROUP BY columnList] [HAVING condition]
[ORDER BY columnList]

 FROM specifies the table or tables to be used


 WHERE filters the rows subject to some condition
 GROUP BY forms groups of rows with the same column value
 HAVING filters the groups subject to some condition
 SELECT specifies which columns are to appear in the output
 ORDER BY specifies the order of the output
USE OF SELECT STATEMENT
 Retrieve all columns and all rows
SELECT *
FROM Staff;
 Retrieve specific columns and all rows
SELECT staffNo, fName, lName, salary
FROM Staff;
 Use of distinct; removes duplicate values
SELECT DISTINCT propertyNo
FROM Viewing;
 Calculated or derived fields
SELECT staffNo, fName, lName, salary/12
FROM Staff;
USE OF SELECT STATEMENT
 Row selection (WHERE CLAUSE)
 Comparison Compare the value of one expression to the value of another expression.
 Range Test whether the value of an expression falls within a specified range of values.
 Set membership Test whether the value of an expression equals one of a set of values.
 Pattern match Test whether a string matches a specified pattern.
 Null Test whether a column has a null (unknown) value.

Comparison search;
= equals
< > is not equal to (ISO standard)
! = is not equal to (allowed in some dialects)
< is less than
< = is less than or equal to
> is greater than > = is greater than or equal to
More Complex predicates
 an expression is evaluated left to right;
 subexpressions in brackets are evaluated first;
 NOTs are evaluated before ANDs and ORs;
 ANDs are evaluated before ORs.
EXAMPLES OF SELECT STATEMENT
 List all staff with a salary greater than £10,000.
SELECT staffNo, fName, lName, position, salary
FROM Staff
WHERE salary > 10000;
 Compound Comparison (logical operator OR is used in the WHERE
clause)
List the addresses of all branch offices in London or Glasgow.
SELECT *
FROM Branch
WHERE city = ‘London’ OR city = ‘Glasgow’;
 Range search condition(BETWEEN/NOT BETWEEN)
List all staff with a salary between £20,000 and £30,000.
SELECT staffNo, fName, lName, position, salary
FROM Staff
WHERE salary BETWEEN 20000 AND 30000;
EXAMPLES OF SELECT STATEMENT
 Set membership search condition (IN/NOT IN)
List all managers and supervisors.
FROM Staff
WHERE position IN (‘Manager’, ‘Supervisor’);
 Pattern match search condition (LIKE/NOT LIKE)
 % percent character represents any sequence of zero or more characters
(wildcard).
 _ underscore character represents any single character.
 address LIKE ‘H%’ means the first character must be H, but the rest of the string
can be anything.
 address LIKE ‘H_ _ _’ means that there must be exactly four characters in the
string, the first of which must be an H.
 address LIKE ‘%e’ means any sequence of characters, of length at least 1, with
the last character an e.
 address LIKE ‘%Glasgow%’ means a sequence of characters of any length
containing Glasgow.
 address NOT LIKE ‘H%’ means the first character cannot be an H.
EXAMPLES OF SELECT STATEMENT
 NULL search condition (IS NULL/IS NOT NULL)
 Special keyword ISNULL is used
SELECT clientNo, viewDate
FROM Viewing
WHERE propertyNo = ‘PG4’ AND comment IS NULL;
SORTING RESULTS(ORDER BY
CLAUSE)
 Ensures results are in an ordered form
 Uses the ORDER BY CLAUSE
 ASC (ascending order), DESC (descending
order)
SELECT staffNo, fName, lName, salary
FROM Staff
ORDER BY salary DESC;
SQL AGGREGATE FUNCTIONS
 Functions operate on a single column of a
table
 Aggregate function only used in the select
list and in the Having clause
 COUNT – returns the number of values in a
specified column;
 SUM – returns the sum of the values in a specified
column;
 AVG – returns the average of the values in a
specified column;
 MIN – returns the smallest value in a specified
column;
 MAX – returns the largest value in a specified
column.
EXAMPLES OF AGGREGATE FUNCTIONS
 How many different properties were viewed in May 2004?
SELECT COUNT(DISTINCT propertyNo) AS myCount
FROM Viewing
WHERE viewDate BETWEEN ‘1-May-04’ AND ‘31-May-04’;;
 Find the total number of Managers and the sum of their salaries.
SELECT COUNT(staffNo) AS myCount, SUM(salary) AS mySum
FROM Staff
WHERE position = ‘Manager’;
 Find the minimum, maximum, and average staff salary.
SELECT MIN(salary) AS myMin, MAX(salary) AS myMax, AVG(salary)
AS myAvg
FROM Staff;
GROUPING RESULTS(GROUP BY CLAUSE)
 Groups data from SELECT tables and produces a single
summary row for each group
 The Select may only contain
 column names;
 aggregate functions;
 constants;
 an expression involving combinations of the above.
 Find the number of staff working in each branch and
the sum of their salaries.
SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS
mySum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;
SUBQUERIES OR NESTED QUERIES
 Select statements are used within other select
statements
 The results of the inner select statement are used on
the outer one and are used to determine contents of
the final result
 Types of subqueries;
 Scalar; returns single column and singe row
 Row; returns multiple columns, single row
 Table; returns one or more columns, multiple rows
 List the staff who work in the branch at ‘163 Main St’.

SELECT staffNo, fName, lName, position


FROM Staff
WHERE branchNo = (SELECT branchNo
FROM Branch
WHERE street = ‘163 Main St’);
RULES FOR SUBQUERIES OR
NESTED QUERIES
 The ORDER BY clause may not be used in a subquery (although it
may be used in the outermost SELECT statement).
 The subquery SELECT list must consist of a single column name
or expression, except for subqueries that use the keyword
EXISTS
 By default, column names in a subquery refer to the table name
in the FROM clause of the subquery. It is possible to refer to a
table in a FROM clause of an outer query by qualifying the
column name
 When a subquery is one of the two operands involved in a
comparison, the subquery must appear on the right-hand side of
the comparison.
SUBQUERIES OR NESTED
QUERIES USE OF IN
 List the properties that are handled by staff who work in the
branch at ‘163 Main St’.
SELECT propertyNo, street, city, postcode, type, rooms, rent
FROM PropertyForRent
WHERE staffNo IN (SELECT staffNo
FROM Staff
WHERE branchNo = (SELECT branchNo
FROM Branch
WHERE street = ‘163 Main St’));
 IN keyword is used as more than one row has been found in the
outermost query
MULTIPLE –TABLE QUERIES
 Uses the join operation
 Matching columns that have the same values are the ones used
to perform the operation.
 To perform a join, we include more than one table in the
FROM clause, separated by a comma and a WHERE clause to
specify the join columns.
 The most common multi-table queries involve two tables that
have a one-to-many (1:*) (or a parent/child) relationship
 To use the parent/child relationship in an SQL query, we
specify a search condition that compares the primary key and
the foreign key.
 For each branch office, list the numbers and names of staff
who manage properties and the properties that they manage.
SELECT s.branchNo, s.staffNo, fName, lName, propertyNo
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo
ORDER BY s.branchNo, s.staffNo, propertyNo;
JOIN QUERIES
 Types of Joins: Left, Right, Full
 Left outer join
 Produces rows of the first left table that are unmatched with rows from the
second right table
List all branch offices and any properties that are in the same city.

SELECT b.*, p.*


FROM Branch1 b LEFT JOIN PropertyForRent1 p ON b.bCity = p.pCity;

 Right outer join


 Produces rows of the second right table that are unmatched with rows from
the first left table
List all properties and any branch offices that are in the same city.

SELECT b.*, p.*


FROM Branch1 b RIGHT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
COMBINING RESULT TABLES
 To combine the results of two or more queries, we use union,
intersect or Except commands;
 The Union of two tables, A and B, is a table containing all
rows that are in either the first table A or the second table B
or both.
 The Intersection of two tables, A and B, is a table containing
all rows that are common to both tables A and B.
 The Difference of two tables, A and B, is a table containing all
rows that are in table A but are not in table B.

 The tables have to be union compatible i.e. have same


structure (same number of columns with same data types and
lengths)
EXAMPLE USING UNION OPERATOR
 Construct a list of all cities where there is either a branch
office or a property.

(SELECT city
FROM Branch
WHERE city IS NOT NULL)
UNION
(SELECT city
FROM PropertyForRent
WHERE city IS NOT NULL);
 This query is executed by producing a result table from the
first query and a result table from the second query, and then
merging both tables into a single result table consisting of all
the rows from both result tables.
 the duplicate rows removed
EXAMPLE USING INTERSECT
OPERATOR
 Construct a list of all cities where there is both a branch
office or a property.

(SELECT city
FROM Branch)
INTERSECT
(SELECT city
FROM PropertyForRent);
 This query is executed by producing a result table from the
first query and a result table from the second query, and then
creating a single result table consisting of those rows that are
common to both result tables.
EXAMPLE USING EXCEPT
OPERATOR
 Construct a list of all cities where there is both but no
properties.

(SELECT city
FROM Branch)
EXCEPT
(SELECT city
FROM PropertyForRent);
 This query is executed by producing a result table from the
first query and a result table from the second query, and then
creating a single result table consisting of those rows that
appear in the first result table but not in the second one.
DATABASE UPDATES
 INSERT – adds new rows of data to a table;
 UPDATE – modifies existing data in a table;
 DELETE – removes rows of data from a table.

 INSERT statement;
 You may insert a single row or multiple rows into the table
 You may insert into a table or an updatable view
 INSERT construct;
INSERT INTO TableName [(columnList)]
VALUES (dataValueList)
 The column and data value lists must match i.e. number of items, position
correspondence and data types

INSERT INTO Staff (staffNo, fName, lName, position, salary, branchNo)


VALUES (‘SG44’, ‘Anne’, ‘Jones’, ‘Assistant’, 8100, ‘B003’);
DATABASE UPDATES
 UPDATE statement;
 Allows contents of existing rows to be changed
 You may insert into a table or an updatable view
 UPDATE construct;
UPDATE TableName
SET columnName1 = dataValue1 [, columnName2 = dataValue2 . . . ]
[WHERE searchCondition]
 SET clause specifies the names of one or more columns that are to be updated.
 You may update specific rows or multiple columns

Give all staff a 3% pay increase.

UPDATE Staff
SET salary = salary*1.03;
DATABASE UPDATES
 DELETE statement;
 Allows contents to be deleted from table
 You may insert into a table or an updatable view
 DELETE construct;
DELETE FROM TableName
[WHERE searchCondition]
 Search condition is optional if all rows are to be deleted from the table

Delete all viewings that relate to property PG4.


DELETE FROM Viewing
WHERE propertyNo = ‘PG4’;
INTEGRITY CONSTRAINTS
 Integrity control consists of constraints that are imposed to
prevent the database from becoming inconsistent
 Types
 Required data; columns not allowed to contain nulls (nulls; missing or not
available)
 position VARCHAR(10) NOT NULL
 Doman constraints; columns have a set of allowable values. Enforced
using CHECK clause and allowed In the CREATE and ALTER statements
 CHECK (searchCondition)
 Gender CHAR NOT NULL CHECK (sex IN (‘M’, ‘F’))
 Create domain statement;

CREATE DOMAIN GenderType AS CHAR


DEFAULT ‘M’
CHECK (VALUE IN (‘M’, ‘F’));l
 Entity integrity; primary key must contain a unique non-null value
 Referential integrity; enforced with a foreign key that creates links
between tables, supports CASCADE, SET NULL, SET DEFAULT, NO ACTION
INTEGRITY CONSTRAINTS

CASCADE; Delete the row from the parent table and automatically delete the matching rows in
the child table.


SET NULL; Delete the row from the parent table and set the foreign key value(s) in
the child table to NULL

SET DEFAULT; Delete the row from the parent table and set each component of the
foreign key in the child table to the specified default value

 NO ACTION; Reject the delete operation from the parent table

 General constraints; updates on tables are constrained to enterprise rules


governing transactions, specified using CHECK and UNIQUE clauses and the
CREAT ASSERTION statement
CREATE ASSERTION AssertionName
CHECK (searchCondition)

CREATE ASSERTION StaffNotHandlingTooMuch


CHECK (NOT EXISTS (SELECT staffNo
FROM PropertyForRent
GROUP BY staffNo
HAVING COUNT(*) > 100))

You might also like