Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Structures Query Language - SQL - Notes

Structured Query Language (SQL) is a standard language used to communicate with relational database management systems. SQL is used to define data structures, manipulate data, and control access to data. It includes statements for data definition, data manipulation, data control, and transaction control. SQL is supported by major database systems and is a standard for relational databases.

Uploaded by

julius padi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Structures Query Language - SQL - Notes

Structured Query Language (SQL) is a standard language used to communicate with relational database management systems. SQL is used to define data structures, manipulate data, and control access to data. It includes statements for data definition, data manipulation, data control, and transaction control. SQL is supported by major database systems and is a standard for relational databases.

Uploaded by

julius padi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

STRUCTURES QUERY LANGUAGE (SQL)

Structured Query Language (SQL), also called Structured English Query Language (SEQUEL), is
relational query language. It is the standard command set used to communicate with the
relational database management system (RDBMS). It is based on the tuple relational calculus,
though not as closely as QUEL. SQL resembles relational algebra in some places and tuple
relational calculus in others. It is a non-procedural language in which block structured format of
English key words is used. SEQUEL (widely known as SQL) was the first prototype query
language developed by IBM in the early-1970s. It was first implemented on a large scale in IBM
prototype called System R and subsequently extended to numerous commercial products from
IBM as well as other vendors. In 1986, SQL was declared a standard for relational data retrieval
languages by the American National Standards Institute (ANSI) and by the International
Standards Organisation (ISO) and called it SQL-86. In 1987, IBM published its own corporate SQL
standard, the System Application Architecture Database Interface (SAA-SQL). ANSI published an
extended standard for SQL, SQL-89 in 1989, SQL-92 in 1992 and the most recent version SQL-
1999.
SQL is both data definition language and data manipulation language of a number of relational
database systems such as System R, SQL/DS, and DB2 of IBM, ORACLE of Oracle Corporation,
INGRES of Relational Technologies and so on. ORACLE was the first commercial RDBMS
developed in 1979 that supported SQL. SQL is very simple to use and interactive in nature.
Users with very little or no expertise in computers, can find it easy to use. SQL facilitates in
executing all tasks related to RDBMS such as creating tables, querying the database for
information, modifying the data in the database, deleting them, granting access to users and so
on. Thus, it has various features such as query formulation, facilities for insertion, deletion and
update operations. It includes statements such as RETURN, LOOP, IF, CALL, SET, LEAVE, WHILE,
CASE, REPEAT and several other related features such as variables and exception handlers. It
also creates new relations and controls the sets of indexes maintained on the database. SQL
can be used interactively to support ad hoc requests, or be embedded into procedural code to
support operational transactions. Different database vendors use different dialects of SQL, but
the basic features of all of them are the same. They use the same base standard of the ANSI
SQL standard.
SQL is essentially a free-format language, which means that parts of the statement do not have
to be typed at particular locations on the screen. There are many software packages for
example, SQL generators, CASE tools and application development environment, where SQL
statements can automatically be generated. CASE tools such as Designer-2000, Information
Engineering Facility (IEF) and so on can be used to generate the entire application including
SQLs. In a Power Builder application, its Data Window package can be used to generate SQL
code. SQL codes can be generated using browser software packages like MS-Query for querying
and updating data in a database. SQL is the main interface for communicating between the
users and RDBMS.
SQL has the following main components:
1. Data structure.
2. Data type.
3. SQL operators.
4. Data definition language (DDL).
5. Data query language (DQL).
6. Data manipulation language (DML).
7. Data control language (DCL).
8. Data administration statements (DAS).
9. Transaction control statements (TCS).

Advantages of SQL
 SQL is the standard query language.
 It is very flexible.
 It is essentially a free-format syntax, which gives the users the ability to structure SQL
statements in a way best suited to him.
 SQL is a high level language and the command structure of SQL consists of Standard
English words.
 It is supported by every product in the market.
 It gives the users an ability to specify key database operation such as table view and
index creation on a dynamic basic.
 It can express arithmetic operations as well as operations to aggregate data and sort
data for output.
 Applications written in SQL can be easily ported across systems.

Disadvantages of SQL
 SQL is very far from being the perfect relational language and it suffers from signs of
both omission and commission.
 It is not a general-purpose programming language and thus the development of an
application requires the use of SQL with a programming language.
5.5.3. Basic SQL Data Structure
In SQL, the data appears to be stored as simple linear files or relations. These files or relations
are called ‘tables’ in SQL terminology. SQL is set-oriented in which the referenced data objects
are always tables. SQL always produces results in tabular format. The tables are accessed either
sequentially or through indexes. An index can reference one or a combination of columns of a
table. A table can have several indexes built over it. When the data in a table changes, SQL
automatically updates the corresponding data in any indexes that are affected by that change.
In SQL, the concept of logical and physical views is implemented. A physical view is called a
‘base table’, whereas a logical view is simply called ‘view’. The logical view is derived from one
or more base tables of physical view. A view may consist of a subset of the columns of a single
table or of two or more joined tables.
The creation of a view in SQL does not entail the creation of a new table by physically
duplicating data in a base table. Instead, information describing the nature of the view is kept in
one or several system catalogs. The catalogue is a set of schemes, which when put
together, constitutes a description of a database. The queries can be issued to either base
tables or views. When a query references a view, the information about the view in the
catalogue maps it onto the base table where the required data is physically stored. , the schema
is that structure which contains descriptions of objects created by a user, such as base tables,
views, constraints and so on as part of the database.
5.5.4. SQL Data Types
Data type of every data object is required to be declared by the programmer while using
programming languages. Also, most database systems require the user to specify the type of
each data field. The data type varies from one programming language to another and from one
database application to another.

Table 5.4 lists data types supported by SQL.


Table 5.4. SQL data types

S.N. Data Type Description

1. BIT(n) Fixed-length bit string of ‘n’ bits, numbered 1-n.

2. BIT VARYING(n) Variable-length bit string with maximum length of ‘n’ bits.

3. CHAR(n) or CHARACTER(n) Fixed-length string of length of exactly ‘n’ characters.

4. VARCHAR(n) or CHAR Variable-length character string of maximum character length of ‘n’


VARYING(n)

5. DECIMAL(p, s) or DEC(p, s) or Exact decimal numeric value. The number of decimal digits or precis
NUMERIC(p, s) and the number of digits after the decimal point (the scale) by ‘s’.

6. INTEGER or INT Integer number.

7. FLOAT(p) Floating point number with precision equal to or greater than ‘p’.

8. REAL Single precision floating point number.

9. DOUBLE PRECISION Double precision floating point number.

10. SMALLINT Integer number of lower precision than INTEGER.

11. DATE Date expressed as YYYY-MM-DD.

12. TIME Time expressed as HH:MM:SS.


Table 5.4. SQL data types

S.N. Data Type Description

13. TIME(p) or TIME WITH TIME The optional fractional seconds precision(p) extends the format to in
ZONE or TIME(p) with TIME seconds, for example TIME(2) HH:MM:SS WITH TIME ZONE adds six
ZONE relative displacement from 12:59 to +13.00 in hours:minutes.

14. INTERVAL Relative time interval (positive or negative). Intervals are either year
as ‘YYYY-MM’ YEAR TO MONTH, or day/time, for example, ‘DD HH:M
SECOND(p).

15. TIMESTAMP Absolute time expressed as YYYY-MM-DD HH:MM:SS.

16. TIMESTANP(p) The optional fractional seconds precision(p) extends the format as f
Timestamps are graduated to be unique and to increase monotonic

17. TIMESTANP WITH TIMEZONE Same as TIME WITH TIMEZONE (Serial No. 13.
or TIMESTAMP(p) WITH
TIMEZONE

5.5.5. SQL Operators


SQL operators and conditions are used to perform arithmetic and comparison statements.
Operators are represented by single character or reserved words, whereas conditions are the
expression of several operators or expressions that evaluate to TRUE, FALSE or UNKNOWN. Two
types of operators are used, namely binary and unary. The unary operator operates on only one
operand, while the binary operator operates on two operands. Table 5.5 shows various types of
SQL operators.
Table 5.5. SQL operators

SN Operators Description

Arithmetic Operators

1. +, – Unary operators for denoting a positive (+ve) or negative (–ve) expression.

2. * Binary operator for multiplication.

3. / Binary operator for division.


Table 5.5. SQL operators

SN Operators Description

4. + Binary operator for addition.

5. – Binary operator for subtraction.

Comparison Operators

6. = Equality.

7. ! =, < >, ⌉ Inequality.

8. < Less than.

9. > Greater than.

10. >= Greater than or equal to.

11. <= Less than or equal to.

12. IN Equal to any member of.

13. NOT IN Not equal to any member of.

14. IS NULL Test for nulls.

15. IS NOT NULL Test for anything other than nulls.

16. LIKE Returns true when the first expression matches the pattern of the second expre

17. ALL Compares a value to every value in a list.

18. ANY, SOME Compares a value to each value in a list.

19. EXISTS True if sub-query returns at least one row.

20. BETWEEN x and y > = x and < = y

Logical Operators
Table 5.5. SQL operators

SN Operators Description

21. AND Returns true if both component conditions are true, otherwise returns false.

22. OR Returns true if either component conditions are true, otherwise returns false.

23. NOT Returns true if the condition is false, otherwise returns false.

Set Operators

24. UNION Returns all distinct rows from both queries.

25. UNION ALL Returns all rows from both queries.

26. INTERSECT Returns all rows selected by both queries.

27. MINUS Returns all distinct rows that are in the first query but not in the second one.

Aggregate Operators

28. AVG Average.

29. MIN Minimum.

30. MAX Maximum.

31. SUM Total.

32. COUNT Count.

5.5.6. SQL Data Definition Language (DDL)


The SQL data definition language (DDL) provides commands for defining relation schemas,
deleting relations and modifying relation schemas. These commands are used to create, alter
and drop tables. The syntax of the commands are CREATE, ALTER and DROP. The main logical
SQL data definition statements are:
CREATE TABLE
CREATE VIEW
CREATE INDEX
ALTER TABLE
DROP TABLE
DROP VIEW
DROP INDEX
5.5.6.1. CREATE TABLE Operation
Tables are the basic building blocks of RDBMSs. Tables contain rows (called tuples) and columns
(called attributes) of data in a database. CREATE TABLE operation is one of the more frequently
used DDL statements. It defines the names of tables and columns, as well as specifies the type
of data allowed in each columns. Fig. 5.1 illustrates the syntax of statements for table creation
operations.
Fig. 5.1. Syntax for creating SQL table

The CREATE TABLE statement specifies a logical definition of a stored table (or base table). It
specifies the name of the table and lists the name and type of each column. The type of column
may be standard data type or a domain name. The keywords NULL and NOT NULL are optional.
A DEFAULT clause may be used to set column values automatically wherever a new row is
inserted. In the absence of a specified default value, nullable columns will contain nulls. A type-
dependent value, such as zero or an empty string, will be used for nun-nullable columns.
The PRIMARY KEY clause lists one or more columns that form the primary key. The FOREIGN
KEY clause is used to specify referential integrity constraints and, optionally, the actions to be
taken if the related tuple is deleted or the value of its primary key is updated. If the table
contains other unique keys, the column can be specified in a UNIQUE clause.
Data types with defined constraints and default values can be combined into domain
definitions. A domain definition is a specialised data type, which can be defined within a
schema and used as desired in columns definitions. Limited support for domains is provided by
the CREATE DOMAIN statements, which associates a domain with a data type and, optionally, a
default value. For example, suppose we wish to define a domain of person identifiers to be
used in the column definitions of various tables. Since we will be using it over and over again in
the database schema, we would like to simplify our work and thus, we create a domain as
follows:
CREATE DOMAIN PERSON-IDENTIFIER NUMBER (6) DEFAULT (0)
or
CREATE DOMAIN PERSON-IDENTIFIER NUMERIC (6) DEFAULT (0) CHECK (VALUE IS NOT NULL);
The above definition says that a domain named PERSON-IDENTIFIER has the properties such as
its data type is of six-digit numeric and default value is zero. Any column defined with this
domain as its data type will have all these properties. As shown in the second form above, the
domain definition may also be followed by a constraint definition that limits the range of
possible values by employing a CHECK clause. Here domain has the property such that it can
never be null. Now we can define columns in our schema with PERSON-IDENTIFIER as their data
type. Fig. 5.2 illustrates examples of creating tables for a employee health center database.
Fig. 5.2. Creating SQL table for employee health centre schema
As shown in Fig. 5.2 under PATIENT table, a constraint may be named by preceding it with
Constraint 〈constraint-table-name〉. ON UPDATE and ON DELETE clauses are used to trigger
referential integrity checks and specifying their corresponding actions. The possible actions of
these clauses are SET NULL, SET DEFAULT and CASCADE. Both SET NULL and SET DEFAULT
remove the relationship by resetting the foreign key value to null, or to its default if it has one.
The action is same for both updates and deletes. The effect of CASCADE depends on the event.
With ON UPDATE, a change to the primary key value in the related tuple is reflected in the
foreign key. Changing a primary key should normally be avoided but it may be necessary when
a value has been entered incorrectly. Cascaded update ensures that referential integrity is
maintained. With ON DELETE, if the related tuple is deleted then the tuple containing the
foreign key is also deleted. Cascaded deletes are therefore appropriate for mandatory
relationships such as those involving weak entity classes. As shown in Fig. 5.2, the PATIENT
table includes the following named referential integrity constraints:
CONSTRAINT PATIENT-REG
FOREIGN KEY (REGISTERED-WITH) REFERENCES DOCTOR (DOCTOR-ID)
ON DELETE SET NULL
ON UPDATE CASCADE
In the above statements, the registration of patient with a doctor is optional to enable patient
details to be entered before the patient is assigned to a doctor, and to simplify the task of
transferring a patient from one doctor to another. The foreign key REGISTERED-WITH will be
updated to reflect any change in the primary key of the doctor table, but if the related doctor
tuple is deleted, it will be set to null. By default, all constraints are immediate and not
deferrable. This means that they are checked immediately after any change is made and that
this behavior cannot be changed.
It is also possible to create local or global temporary tables within a transaction as shown in Fig.
5.3. They may be preserved or deleted when the transaction is committed.
Fig. 5.3. Creating local or global temporary table
5.5.6.2. DROP TABLE Operation
DROP operation is used for deleting tables from the schema. It can be used to delete all rows
currently in the named table and to remove the entire definition of the table from the schema.
Entire schema can be dropped. The syntax of DROP statement is given in Fig. 5.4 below:
Fig. 5.4. Syntax for DROP operation

An example of DROP operations is given below:


DROP SCHEMA HEALTH-CENTRE

or DROP TABLE PATIENT

or DROP COLUMN CONSTRAINT

Since, simple DROP statement can be a dangerous operation, either CASCADE or RESTRICT must
be specified with it as shown below:
DROP SCHEMA HEALTH-CENTRE CASCADE

or DROP TABLE PATIENT CASCADE

The above statement means to drop the schema named as well as all tables, data and other
schema objects that still exist (that means removing the entire schema irrespective of its
content).
DROP SCHEMA HEALTH-CENTRE RESTRICT
DROP TABLE PATIENT RESTRICT
The above statement means to drop the schema only if all other schema objects have already
been deleted (that is only if schema is empty). Otherwise, an exception will be raised.
5.5.6.3. ALTER TABLE operation
ALTER operation is used for changing the definitions of tables. It is a schema
evolution command. It can be used to add one or more columns to a table, change the
definition of an existing column, or drop a column from a table. The syntax of ALTER statement
is given in Fig. 5.5, as shown below.
Fig. 5.5. Syntax for ALTER operation

An example of ALTER operations is given below:


ALTER TABLE PATIENT ADD COLUMN ADDRESS CHAR (30)

or ALTER TABLE DOCTOR DROP COLUMN ROOM-NO

or ALTER TABLE DOCTOR DROP COLUMN ROOM-NO RESTRICT

or ALTER TABLE DOCTOR DROP COLUMN ROOM-NO CASCADE

Again, CASCADE and RESTRICT can be used in the above statements to determine the drop
behavior when constraints or views depend on the affected column. Column default values may
be altered or dropped, as shown below:
ALTER TABLE APPOINTMENT

ALTER COLUMN APPT-DURATION SET DEFAULT 20

or ALTER TABLE APPOINTMENT

ALTER COLUMN APPT-DURATION DROP DEFAULT

Here, the default value of 10 for the appointment duration has been changed to 20. The default
even can be removed, as shown in the second statement above.
5.5.6.4. CREATE INDEX Operation
An index is a structure that provides faster access to the rows of a table based on the values of
one or more columns. The index stores data values and pointers to the rows (tuples) where
those data values occur. An index sorts data values and stores them in ascending or descending
order. Indexes are created in most RDBMSs to provide rapid random and sequential access to
base table data. It can help in quickly executing a query to locate particular column and rows.
The CREATE INDEX operation allows the creation of an index for an already existing relation.
The columns to be used in the generation of the index are also specified. The index is named
and the ordering for each column used in the index can be specified as either ascending or
descending. Like tables, indexes can also be created dynamically. Fig. 5.6 illustrates the syntax
of statements for index creation operations.
Fig. 5.6. Syntax for creating index

The CLUSTER option could also be specified to indicate the records and are to be placed in
physical proximity to each other. The unique option specifies that only one record could exist at
any time with a given value for the column(s) specified in the statement of create the index. An
example of creating index for EMPLOYEE relation is given below.
CREATE INDEX EMP-INDEX

ON EMPLOYEE (LAST-NAME ASC, SEX DESC);


The above statement causes a creation of an index called EMP-INDEX with columns LAST-NAME
and SEX from the relation (table) EMPLOYEE. The entries in the index are ascending by LAST-
NAME value and descending by SEX. In the above example, there are no restrictions on the
number of records with the same LAST-NAME and SEX. An existing relation or index can be
deleted for the database by using the DROP statement in the similar way as explained for table
and schema operations.
5.5.6.5. Create View Operation
A view is a named table that is represented by its definition in terms of other named tables. It is
a virtual table, which is constructed automatically as needed by the DBMS and is not
maintained as real data. The real data are stored in base tables. The CREATE VIEW operation
defines a logical table from one or more tables or views. Views may not be indexed. Fig.
5.7 illustrates the general syntax of creating view definition.
Fig. 5.7. Syntax for creating view definition

The sub-query cannot include either UNION or ORDER BY. The clause ‘WITH CHECK OPTION’
indicates that modifications (update and insert) operations against the view are to be checked
to ensure that the modified row satisfies the view-defining condition. There are limitations on
updating data through views. Where views can be updated, those changes can be transferred
to the underlying base tables originally referenced to create the view. An example of creating
view for EMPLOYEE relation is given below:
CREATE VIEW PATIENT VIEW
AS SELECT DOCTOR.DOCTOR-ID, DOCTOR.PHONE-NO,
PATIENT.PATIENT-ID, PATIENT.DATE-REGISTERED,
FROM DOCTOR, PATIENT
The above view operation will result into creation of a PATIENT-VIEW table with listing of
columns such as DOCTOR-ID and PHONE-NO from DOCTOR table and PATIENT-ID and DATE-
REGISTERED from the PATIENT table.
The main purpose of a view is to simplify query commands. However, a view may also provide
data security and significantly enhance programming productivity for a database. A view always
contains the most recent derived values and is thus superior in terms of data currency to
constructing a temporary real table from several base tables. It consumes very little storage
space. However, it is costly as because its contents must be calculated each time that they are
requested.
5.5.7. SQL Data Query Language (DQL)
SQL data query language (DQL) is one of the most commonly used SQL statements that enable
the users to query one or more tables to get the information they want. DQL has only one data
query statement whose syntax is SELECT. The SELECT statement is used for retrieval of data
from the tables and produce reports. It is the basis for all database queries. The SELECT
statement of SQL has no relationship to the SELECT or RESTRICT operations of relational
algebra. SQL table departs from the strict definition of a relation in that unique rows are not
enforced. SQL allows a table (relation) to have two or more rows (tuples) that are identical in all
their attribute (column) values. Thus, a query result may contain duplicate rows. Hence, in
general, an SQL table is not a set of tuples as is the case with relation, because a set does not
allow two identical members. In face, an SQL table is a multiset (sometimes called bag) of tuples
(or rows). Some SQL relations are constraints to be set because a key constraint has been
declared or because the DISTINCT option has been used with the SELECT statement. A typical
SQL statement for SELECT operation can be made up of two or more of the clauses as shown
in Fig. 5.8 below:

Fig. 5.8. Syntax for SQL SELECT statement

In the above syntax, the clauses such as WHERE, GROUP BY, HAVING and ORDER BY, are
optional. They are included in the SELECT statement only when functions provided by them are
required in the query. In its basic form of the SQL the SELECT statement is formed of three
clauses namely, SELECT, FROM and WHERE. This basic form of SELECT statement is sometimes
called a mapping or a select-from-where block. These three clauses corresponds to the
relational algebra operations as follows:
 The SELECT clause corresponds to the projection operation of the relational algebra. It is
used to list the attributes (columns) desired in the result of a query. SELECT * is used to
get all the columns of a particular table.
 The FROM clause corresponds to the Cartesian-product operation of the relational
algebra. It is used to list the relations (tables) to be scanned from where data has to be
retrieved.
 The WHERE clause corresponds to the selection predicate of the relational algebra. It
consists of a predicate involving attributes of the relations that appear in the FROM
clause. It tells SQL to include only certain rows of data in the result set. The search
criteria is specified in WHERE clause.
Fig. 5.9 illustrates the variations of SELECT statements and their results
Fig. 5.9. Examples of query using SELECT statement
5.5.7.1. Abbreviation or Alias Name
Columns name may be qualified by the name of the table (or relation) in which they are found.
But this is only necessary where queries involve two or more tables containing columns with
the same name to prevent ambiguity. Due to this reason, an abbreviation (also called
correlation or alias name) S and I have been used in Query 5 to define two relations STORED
and ITEMS. Instead of abbreviations, the relation names can also be directly used to qualify the
attribute name, for example, STORED.ITEM-NO, ITEMS.ITEM-NO and so on. Where the column
name is unique the table qualification may be omitted. Queries can also be shortened by using
an abbreviation name for a table name. This abbreviation or alias is specified in the FROM
clause.
5.5.7.2. Aggregate Functions and the GROUP BY Clause
SQL provides several sets, or aggregate functions using the GROUP BY clause for summarising
the content of the columns. This function is usually used with aggregate functions such as AVG,
SUM, MIN, MAX and so on. It used to give out common information when querying the tables
of a database. Examples of GROUP BY clause, with reference are given in Fig. 5.10 below.

Fig. 5.10. Examples of aggregate functions and GROUP BY clauses


HAVING Clause
The HAVING clause is used to include only certain groups produced by the GROUP BY clause in
the query result set. It is equivalent to WHERE clause and is used to specify the search criteria
or search condition when GROUP BY clause is specified. Example of HAVING clause, with
reference to of is given in Fig. 5.11 below.
Fig. 5.11. Examples of HAVING clause

ORDERED BY Clause
The ORDER BY clause is used to sort the results based on the data in one or more columns in
the ascending or descending order. The default of ORDER BY clause is ascending (ASC) and if
nothing is specified the result set will be sorted in ascending order. An example of ORDER BY
clause, is given in Fig. 5.12 below:

Fig. 5.12. Examples of ORDER BY clause


SQL Data Manipulation Language (DML)
The SQL data manipulation language (DML) provides query language based on both the
relational algebra and the tuple relational calculus. It provides commands for updating,
inserting, deleting, modifying and querying the data or tuples in the database. These commands
may be issued interactively, so that a result is returned immediately following the execution of
the statement. The syntax of the SQL DML commands is INSET, DELETE and UPDATE.

SQL INSERT Command


The SQL INSERT command is used to add a new tuple (row) to a relation. The relation (or table)
name and list of values of the tuple must be specified. The value of each attribute (column or
field) of the tuple (row or record) to be inserted is either specified by an expression or could
come from selected records of existing relations. The values should be listed in the same order
in which the corresponding attributes were specified in the CREATE TABLE commands (already
discussed ) or in the order of existing relation. The syntax for INSERT command is given as:
INSERT INTO 〈table-name〉 [(attributes-name)]

VALUES (lists of values for row 1,

list of values for row 2,

list of values for row n);

In the above syntax, attribute name along with relation name is optional. An example of INSERT
command, is given in Fig. 5.13 below:

Fig. 5.13. Examples of INSERT command


In Query 2 of the above example, the INSERT command allows the user to specify explicit
attribute names that correspond to the values provided in the INSERT command. This is useful if
a relation has many attributes, but only a few of those attributes are assigned values in the new
tuple. The attributes not specified in the command format (as shown in Query 2), are set to
their DEFAULT or to NULL and the values are listed in the same order as the attributes are listed
in the INSERT command itself.

SQL DELETE Command


The SQL DELETE command is used to delete or remove tuples (rows) from a relation. It includes
WHERE clause, similar to that used in an SQL query, to select the tuples to be deleted. Tuples
are explicitly deleted from only one relation (table) at a time. The syntax of the DELETE
command is given as:
DELETE FROM 〈table-name〉
WHERE 〈predicate(s)〉

An example of DELETE command, is given in Fig. 5.14 below:

Fig. 5.14. Examples of DELETE command

If WHERE clause is not given, as the case in Query 2 of the above example, it specifies that all
tuples in the relation are to be deleted. However, the table remains in the database as an
empty table. To remove the table completely, a DROP statement can be used.

The WHERE clause of a DELETE command may contain a sub-query as illustrated in Query 3 in
the above example. In this case, the ITEM-NO column of each row in the STORED table is tested
for membership of the multi-set returned by the sub-query.
SQL UPDATE Command
The SQL UPDATE command is used to modify attribute (column) values of one or more selected
tuples (records) to be modified are specified by a predicate in a WHERE clause and the new
values of the columns to be updated is specified by a SET clause. The syntax of the UPDATE
command is given as:
UPDATE 〈table-name〉

SET 〈target-value-list〉

WHERE 〈predicate〉

An example of UPDATE command, with reference to of is given in Fig. 5.15 below:


Fig. 5.15. Examples of UPDATE command
As with other statements, an update may be performed according to the result of a search
condition involving other tables, as illustrated in Query 2 in the above example.

SQL Data Control Language (DCL)


SQL data control language (DCL) provides commands to help database administrator (DBA) to
control the database. It consists of the commands that control the user access to the database
objects. Thus, SQL DCL is mainly related to the security issues, that is, determining who has
access to the database objects and what operations they can perform on them. It includes
commands to grant or revoke privileges (or authorisation) to access the database or particular
objects within the database and to store or remove transactions that would affect the
database. The syntax of the commands is GRANT and REVOKE.

SQL GRANT Command


The SQL GRANT command is used by the DBA to grant privileges to users. The syntax of the
GRANT command is given as:
GRANT 〈privilege(s)〉

ON 〈table-name/view-name〉

TO 〈user(s)-id〉, 〈group(s)-id〉, 〈public〉

The key words for this command are GRANT, ON and TO. A privilege is typically a SQL command
such as CREATE, UPDATE or DROP and so on. The user-id is the identification code of the user to
whom the DBA wants to grant the specific privilege. The example of GRANT command is given
below:
Example 1: GRANT CREATE

ON ITEMS

TO Abhishek

Example 2: GRANT DROP

ON ITEMS

TO Abhishek

Example 3: GRANT UPDATE

ON ITEMS
TO Abhishek

Example 4: GRANT CREATE, UPDATE, DROP, SELECT

ON ITEMS

TO Abhishek

WITH GRANT OPTION

In the above examples, DBA has granted a user-id named Abhishek the capability to create,
update, drop and or select tables. As shown in example 4, the DBA has granted Abhishek the
right to create, update, drop and select data in ITEMS table. Furthermore, Abhishek can grant
these same rights to others at his discretion.

SQL REVOKE Command


The SQL REVOKE command is issued by the DBA to revoke privileges from users. It is opposite
to the GRANT command. The syntax of the REVOKE command is given as:
REVOKE 〈privilege(s)〉

ON 〈table-name/view-name〉

FROM 〈user(s)-id〉, 〈group(s)-id〉, 〈public〉

The key words for this command are REVOKE and FROM. The example of REVOKE command is
given below:
Example 1: INVOKE CREATE

ON ITEMS

FROM Abhishek

Example 2: REVOKE DROP

ON ITEMS

FROM Abhishek
Example 3: REVOKE UPDATE

ON ITEMS

FROM Abhishek

Example 4: REVOKE CREATE, UPDATE, DROP, INSERT, SELECT

ON ITEMS

FROM Abhishek

In the above examples, DBA has revoked the privileges that were previously granted to user-id
named Abhishek.

SQL Data Administration Statements (DAS)

The SQL data administration statement (DAS) allows the user to perform audits and analysis on
operations within the database. They are also used to analyse the performance of the system.
Data administration is different from database administration in the sense that database
administration is the overall administration of the database whereas data administration is only
a subset of that. DAS has only two statements whose syntax are START AUDIT and STOP AUDIT.

SQL Transaction Control Statements (TCS)

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. It may be defined as a process that contains
either read commands, write commands or both. An SQL transaction automatically begins with
a transaction-initiating SQL query executed by a user or program. SQL TCS manages all the
changes made by the DML statements. The main syntax of the TCS commands is COMMIT and
ROLLBACK.
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.

You might also like