0% found this document useful (0 votes)
66 views8 pages

It223 Advance Database System

This document discusses SQL functions and statements. It describes different categories of SQL functions including data definition language, data manipulation language, and aggregate functions. It provides examples of common SQL statements like SELECT, WHERE, GROUP BY, and JOIN. It also discusses SQL functions that can derive values from existing attributes, like ordering records by year of birth or the first three digits of a phone number. Tables provide examples of date/time functions in MS Access and SQL Server.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views8 pages

It223 Advance Database System

This document discusses SQL functions and statements. It describes different categories of SQL functions including data definition language, data manipulation language, and aggregate functions. It provides examples of common SQL statements like SELECT, WHERE, GROUP BY, and JOIN. It also discusses SQL functions that can derive values from existing attributes, like ordering records by year of birth or the first three digits of a phone number. Tables provide examples of date/time functions in MS Access and SQL Server.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

IT223 ADVANCE DATABASE SYSTEM SELECT Selects attributes from

rows in one or more


M1L1: SQL STATEMENT REVIEW tables or views
CATEGORIES FOR SQL FUNCTIONS: WHERE Restricts the selection of
rows based on a
• DATA DEFINITION LANGUAGE (DDL) conditional expression
• DATA MANIPULATION LANGUAGE (DML) GROUP BY Groups the selected rows
based on one or more
DDL commands that allows the creation of attributes
database objects such as tables, indexes and views HAVING Restricts the selection of
as well as commands to define access rights to grouped rows based on a
those database objects: condition
ORDER BY Orders the selected rows
COMMAND OR DESCRIPTION based on one or more
OPTION attributes
CREATE SCHEMA Creates a database schema UPDATE Modifies an attribute’s
AUTHORIZATION values in one or more
CREATE TABLE Creates a new table in the table’s rows
user’s database schema DELETE Deletes one or more rows
NOT NULL Ensures that a column will not from a table
have null values COMMIT Permanently saves data
UNIQUE Ensures that a column will not changes
have duplicate values ROLLBACK Restores data to its
PRIMARY KEY Defines a primary key for a original values
table Comparison
FOREIGN KEY Defines a foreign key for a operators
table =, <, >, <=, >=, <>, != Used in conditional
DEFAULT Defines a default value for a expressions
column (when no value is Logical operators
given) AND/OR/NOT Used in conditional
CHECK Validates data in an attribute expressions
CREATE VIEW Creates a dynamic subset of Special operators Used in conditional
rows and columns from one or expressions
more tables BETWEEN Checks whether an
ALTER TABLE Modifies a table’s definition attribute value is within a
(adds, modifies, or deletes range
attributes or constraints) IS NULL Checks whether an
CREATE TABLE Creates a new table based on attribute value is null
a query in the user’s database LIKE Checks whether an
schema attribute value matches a
DROP TABLE Permanently deletes a table given string pattern
(and its data) IN Checks whether an
attribute value matches
any value within a value
DML commands that allows you to insert, update, list
delete and retrieve data within the database tables: EXISTS Checks whether a
subquery returns any
COMMAND OR DESCRIPTION
rows
OPTION
DISTINCT Limits values to unique
INSERT Inserts row(s) into a table
values
Aggregate functions Used with SELECT to Subqueries – complete select-from-where
return mathematical blocks within the WHERE clause of another
summaries on columns
query. Used in comparison condition. It uses the
COUNT Returns the number of
rows with non-null values
comparison operators IN, ANY or SOME, and
for a given column ALL because the nested query will usually
MIN Returns the minimum return a table (relation),which is a set or
attribute value found in a multiset of tuples.
given column
MAX Returns the maximum operator IN – compares a value returned by the
attribute value found in a subquery and evaluates to TRUE if a value is one
given column of the elements in the main query.
SUM Returns the sum of all
values for a given column SELECT DISTINCT Pnumber
AVG Returns the average of all
values for a given column FROM PROJECT
WHERE Pnumber IN
basic structure of making a SELECT (SELECT Pno FROM WORKS_ON,
command: EMPLOYEE WHERE Essn=Ssn AND
Lname=‘Smith’
SELECT <attribute list>
The operator =ANY or =SOME operator returns
FROM <table list> to TRUE if some of the rows in the inner query is
WHERE <condition> equal to some value in the outer query and
hence equivalent to IN. However, it can be
Join Operation – allows the joining tables. combined with other operators: >, >=, <=, and
<>. >ALL operators on the other hand, return all
Inner join – default type of join in a joined the rows in the outer query that is greater than
table. all in the inner query.
Tuple – included in the result only if a matching SELECT Lname, Salary
tuple exists in the other relation.
FROM EMPLOYEE
SELECT Fname, Lname, Dname
WHERE Salary > ANY (SELECT Salary FROM
FROM (EMPLOYEE JOIN DEPARTMENT ON EMPLOYEE WHERE Dno=4 );
Dno=Dnumber)
GROUP BY – specifies the grouping attributes,
WHERE Dname=’Research’; which should also appear in the SELECT clause,
so that the value resulting from applying each
Outer Joins – used when all rows should be
aggregate function to a group of tuples appears
displayed even it does that have a match in the along with the value of the grouping
other table. attribute(s).
SELECT E.Lname AS Employee_name, S.Lname SELECT Dno, COUNT (*), AVG (Salary)
AS Supervisor_name
FROM EMPLOYEE GROUP BY Dno;
FROM (EMPLOYEE AS E LEFT OUTER JOIN
---------------------------------------------------------
EMPLOYEE AS S ON E.Super_ssn=S.Ssn);
SELECT Pnumber, Pname, COUNT (*) FROM
PROJECT, WORKS_ON WHERE Pnumber=Pno
GROUP BY Pnumber, Pname HAVING COUNT (*) Table 1.3. Selected MS Access and SQL Server
> 2; Date/Time Functions
M1L2: DEPENDING SQL FUNCTIONS
SQL functions – very useful tools. when you
want to list all employees ordered by year of
birth, or when your marketing department
wants you to generate a list of all customers
ordered by zip code and the first three digits of
their telephone numbers. In both of these
cases, you’ll need to use data elements that are
not present as such in the database. Instead,
you will need a SQL function that can be derived
from an existing attribute. Functions always use
a numerical, date, or string value. The value
may be part of the command itself (a constant
or literal) or it may be an attribute located in a
table. Therefore, a function may appear
anywhere in a SQL statement where a value or
an attribute can be used.
Types of SQL Functions: Table 1.4 shows the equivalent date/time
functions used in Oracle.
• Arithmetic
• Trigonometric
• String
• Date
• Time

Date and Time Functions - All SQL-standard


DBMSs support. All date functions take one
parameter of a date or character data type and
return a value (character, numeric, or date
type). Unfortunately, date/time data types are
implemented differently by different DBMS
vendors. The problem occurs because the ANSI
SQL standard defines date data types, but it
does not specify how those data types are to be
stored. Instead, it lets the vendor deal with that
issue.
String Functions – String manipulations are
among the most-used functions in
programming.
Table 1.7 shows a subset of useful string
manipulation functions.

Numeric Functions – can be grouped in many


different ways, such as algebraic, trigonometric,
and logarithmic. The first group operates over a
set of values (multiple rows— hence, the name
aggregate functions), while the numeric
functions covered here operate over a single
row. Numeric functions take one numeric
parameter and return one value.
Table 1.6 shows a selected group of available
numeric functions.

M2L1: EFFICIENCY OF SQL INDEXES


The Database Model – simple database
composed of the following tables is used to
illustrate the SQL commands.
Indexes in the relational database environment
work like the indexes described in the preceding
paragraph. From a conceptual point of view, an
index is composed of an index key and a set of candidate key whose values must not be
pointers. The index key is, in effect, the index’s duplicated:
reference point. More formally, an index is an
ordered arrangement of keys and pointers. Each CREATE UNIQUE INDEX P_CODEX ON
key points to the location of the data identified PRODUCT(P_CODE);
by the key. Unique composite indexes – often used to
Functions of Indexes prevent data duplication.
Such duplication could have been avoided
• An index is a data structure that
through the use of a unique composite index,
contains information on database
using the attributes EMP_NUM, TEST_CODE,
records to improve the speed of data
and TEST_DATE:
retrieval operations.
• Indexes are used to quickly locate data CREATE UNIQUE INDEX EMP_TESTDEX ON
without the need to search the whole TEST(EMP_NUM, TEST_CODE, TEST_DATE);
data and the search speed is not heavily
affected by the increased number of By default, all indexes produce results that are
records. listed in ascending order, but you can create an
• An index is organized with column index that yields output in descending order.
values that generates it, and a table For example, if you routinely print a report that
contains locations where actual data is lists all products ordered by price from highest
stored. to lowest, you could create an index named
• The most important role of indexes is to PROD_PRICEX by typing:
speed up data search by shortening the CREATE INDEX PROD_PRICEX ON
access path. PRODUCT(P_PRICE DESC);
Index Design Process To delete an index, use the DROP INDEX
1. Evaluate access paths command:
2. Select candidate columns after the DROP INDEX indexname
review of distribution of values
3. Decide access paths For example, if you want to eliminate the
4. Decide column combinations and order PROD_PRICEX index, type:

Using the CREATE INDEX command, SQL indexes DROP INDEX PROD_PRICEX;
can be created on the basis of any selected M2L2: VIRTUAL TABLES: CREATING A VIEW
attribute.
VIEW – a virtual table based on a SELECT query.
The syntax is:
QUERY – can contain columns, computed
CREATE [UNIQUE]INDEX indexname ON columns, aliases, and aggregate functions from
tablename(column1 [, column2]) one or more tables.
Example: BASE TABLES – tables on which the view is
CREATE INDEX P_INDATEX ON based.
PRODUCT(P_INDATE); Creating a View
Using the UNIQUE index qualifier, you can even using the CREATE VIEW command:
create an index that prevents you from using a
value that has been used before. Such a feature CREATE VIEW viewname AS SELECT query
is especially useful when the index attribute is a
CREATE VIEW statement – a data definition • Join the PRODMASTER and PRODSALES tables.
command that stores the subquery • Update the PROD_QOH attribute (using the
specification— the SELECT statement used to PS_QTY value in the PRODSALES table) for each
generate the virtual table—in the data row of the PRODMASTER table with matching
dictionary. PROD_ID values in the PRODSALES table.
Characteristics of Database Views UPDATABLE VIEW – can be used to update
attributes in any base table(s) used in the view.
A relational view has several special You must realize that not all views are
characteristics: updatable. Actually, several restrictions govern
• You can use the name of a view updatable views, and some of them are vendor-
anywhere a table name is expected in a specific.
SQL statement. The most common updatable view restrictions
• Views are dynamically updated. That is, are as follows:
the view is re-created on demand each
time it is invoked. ▪ GROUP BY expressions or aggregate
• Views provide a level of security in the functions cannot be used.
database because they can restrict ▪ You cannot use set operators such as
users to seeing only specified columns UNION, INTERSECT, and MINUS.
and rows in a table. ▪ Most restrictions are based on the use of
• Views may also be used as the basis for JOINs or group operators in views.
reports.
M2L3: SQL STORED PROCEDURES
Modifying Data through a View
STORED PROCEDURE – a set of queries to be
➢ One of the most common operations in used as if it is a single function. Also called
production database environments is to use persistent storage module, wherein it is a series
batch update routines to update a master of work on database compiled and stored in
table attribute (field) with transaction data. relational database. One of the major
advantages of stored procedures is that they
BATCH UPDATE ROUTINE – pools multiple can be used to encapsulate and represent
transactions into a single batch to update a business transactions.
master table field in a single operation.
There are two clear advantages to the use of
Example: stored procedures:
Using the tables in Figure 2.3, update the 1. Stored procedures substantially reduce
PRODMASTER table by subtracting the network traffic and increase
PRODSALES table’s product monthly sales performance.
quantity (PS_QTY) from the PRODMASTER 2. Stored procedures help reduce code
table’s PROD_QOH. To produce the required duplication by means of code isolation
update, the update query would be written like and code sharing
this:
To create a stored procedure, you use the
UPDATE SET WHERE PRODMASTER, PRODSALES following syntax:
PRODMASTER.PROD_QOH = PROD_QOH –
PS_QTY PRODMASTER.PROD_ID = CREATE OR REPLACE PROCEDURE
PRODSALES.PROD_ID; procedure_name [(argument [IN/OUT] data-
type, … )]
Note that the update statement reflects the
following sequence of events: [IS/AS]
[variable_namedata • Triggers can be used to enforce
type[:=initial_value] ] constraints that cannot be enforced at
the DBMS design and implementation
BEGIN
levels.
PL/SQL or SQL statements; • Triggers add functionality by
automating critical actions and
… providing appropriate warnings and
END; suggestions for remedial action. In fact,
one of the most common uses for
Note the following important points about triggers is to facilitate the enforcement
stored procedures and their syntax: of referential integrity.
• Triggers can be used to update table
• argument specifies the parameters that are
values, insert records in tables, and call
passed to the stored procedure. A stored
other stored procedures.
procedure could have zero or more arguments
or parameters. Creating Triggers
• IN/OUT indicates whether the parameter is The syntax to create a trigger in Oracle is as
for input, output, or both. follows:
• data-type is one of the procedural SQL data CREATE OR REPLACE TRIGGER trigger_name
types used in the RDBMS. The data types
normally match those used in the RDBMS table [BEFORE / AFTER] [DELETE / INSERT /
creation statement. UPDATE OF column_name] ON table_name

• Variables can be declared between the [FOR EACH ROW]


keywords IS and BEGIN. You must specify the [DECLARE]
variable name, its data type, and (optionally) an
initial value. [variable_namedata
type[:=initial_value] ]
M2L4: UTILIZING SQL TRIGGERS
BEGIN
TRIGGER – procedural SQL code that is
automatically invoked by the RDBMS upon the PL/SQL instructions;
occurrence of a given data manipulation event.

It is useful to remember that:
END;
• A trigger is invoked before or after a
As you can see, a trigger definition contains
data row is inserted, updated, or
the following parts:
deleted.
• A trigger is associated with a database • The triggering timing: BEFORE or AFTER.
table. This timing indicates when the trigger’s
• Each database table may have one or PL/ SQL code executes—in this case,
more triggers. before or after the triggering statement is
• A trigger is executed as part of the completed.
transaction that triggered it. • The triggering event: The statement that
causes the trigger to execute (IN SERT,
Triggers are critical to proper database
UPDATE, or DELETE).
operation and management. For example:
- The triggering level: The two types
of triggers are statement-level
triggers and rowlevel triggers.A
statement-level trigger is assumed
if you omit the FOR EACH ROW
keywords. This type of trigger is ex
ecuted once, before or after the
triggering statement is completed.
This is the default case.
- A row-level trigger requires use of
the FOR EACH ROW keywords. This
type of trigger is executed once for
each row affected by the triggering
statement. (In other words, if you
update 10 rows, the trig ger
executes 10 times.)
• The triggering action: The PL/SQL code
enclosed between the BEGIN and END
keywords.Each statement inside the
PL/SQL code must end with a semi colon (
; ).
Creating Triggers
The use of triggers facilitates the automation of
multiple data management tasks. Although
triggers are independent objects, they are
associated with database tables. When you
delete a table, all its trigger objects are deleted
with it. However, if you needed to delete a
trigger without deleting the table, you could use
the following command:
DROP TRIGGER trigger_name
Trigger Action Based on Conditional DML
Predicates
You could also create triggers whose actions
depend on the type of DML statement (INSERT,
UPDATE, or DELETE) that fires the trigger. For
example, you could create a trigger that
executes after an INSERT, an UPDATE, or a
DELETE on the PRODUCT table. But how do you
know which one of the three statements caused
the trigger to execute? In those cases, you
could use the following syntax:
IF INSERTING THEN … END IF;
IF UPDATING THEN … END IF;
IF DELETING THEN … END IF;

You might also like