SQL Language - DML and DDL
SQL Language - DML and DDL
LANGUAGE
A database language should allow a user
to:
•
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
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.
Example;
To remove the PropertyForRent table we use the command:
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
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.
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[
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 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
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
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