You are on page 1of 61

Unit III Relational Algebra and Calculus: Preliminaries, Relational Algebra, Relational Calculus,

Expressive Power of Algebra and Calculus. SQL: Queries, Constraints, Triggers, The Form of Basic
SQL Query, Set Operators, Nested Queries, Aggregate Operators, Procedures and functions, Triggers.

Relational algebra

The Relational algebra is a (high-level) procedural language (Theoretical language). It can be used to tell the DBMS
how to build a new relation from one or more relations in the database.

The relational algebra is a relation-at-a-time (or set) language in which all tuples, possibly from several relations, are
manipulated in one statement without looping.

The following are the possible operations of relational algebra:

Consider the following EMP and EMP1, DEPT relations in order to perform various Relational Algebra
operations:

EMP
EMP_ID ENAME DOB JOB DEPTNO SAL

1001 Arun 10-Jun-1991 Clerk 10 9000


1002 Bharathi 01-Jan-1992 Manager 20 18000
1003 Charitha 03-Jan-1992 Asst.Manager 20 15000
1004 Dheeraj 15-Jun-1992 Off.Asst 10 9500
1005 Ravi 04-Feb-1992 Manager 10 25000

EMP1

EMP_ID ENAME DOB JOB DEPTNO SAL

2009 Eesha 10-Feb-1990 Clerk 20 11000


1002 Bharathi 01-Jan-1992 Manager 20 18000
2012 Firoz 03-Jan-1992 Manager 30 25000
1005 Ravi 04-Feb-1992 Manager 10 25000
DEPT

DEPTNO DNAME LOCATION

10 Accounts Delhi
20 Finance Mumbai
30 Marketing Chennai
40 Production Hyderabad
50 I.T Amaravathi

Unary Operations

The operations that can operate on one relation are known as Unary Operations. There are two Unary Operations:

 Selection

 Projection

Selection (or Restriction)

The Selection operation works on a single relation R and Produces a relation that contains only those tuples of
R that satisfy the specified predicate. The following figure shows the Selection operation:

Figure: Selection Operation

A Selection operation can be denoted by the following notation:

predicate(R)

For example:

List all the Employees with a salary greater than ₹10000

Here, the input relation is EMP and the predicate is salary >10000.
The Selection operation produces a relation containing only those EMP tuples with a salary greater than ₹10000. The
result of this operation is shown in the following table:

EMP_ID ENAME DOB JOB DEPTNO SAL


1002 Bharathi 01-Jan-1992 Manager 20 18000
1003 Charitha 03-Jan-1992 Asst.Manager 20 15000
1005 Ravi 04-Feb-1992 Manager 10 25000

Projection:

The Projection operation works on a single relation R and produces a relation that contains a vertical subset of R,
extracting the values of specified attributes and eliminating duplicates. The following figure shows the Projection
operation:

Figure: Projection Operation

A Projection operation can be denoted by the following notation:

For example:

List all the Salaries of all employees showing only the Emp_Id, Ename, Job, and Salary details.

Here, the Projection operation produces a relation that contains only the specified EMP attributes

Emp_ID, EName, Job, and Sal, in the given order. The following table shows the result:

EMP_ID ENAME JOB SAL


1001 Arun Clerk 9000
1002 Bharathi Manager 18000
1003 Charitha Asst.Manager 15000
1004 Dheeraj Off.Asst 9500
1005 Ravi Manager 25000
Set Operations

a) Union:

The union of two relations R and S Produces a relation that contains all the tuples of R, or S, or both R and S. It
eliminates the duplicate tuples. The relations R and S must be union-compatible in order to perform the union operation.
The following figure shows the Union operation:

R∪S

Figure: Union

A Union operation can be denoted by the following notation:

RUS

Example:

List all Employee Names where the job is either ‘Clerk’ or ‘Manager’

The above union operation produces the following relation:


b). Set Difference:

The Set difference operation produces a relation consisting of the tuples that are in relation R, but not in S. R and S
must be union-compatible. The following figure shows the Set Difference operation:

Figure: Set Difference

Set difference operation can be denoted by the following notation:

R-S

Example:

Find the difference between EMP and EMP1 relations

The above Difference operation produces the following relation:


c). Intersection:

The Intersection operation produces a relation consisting of the set of all tuples that are in both R and S. R and S
must be union-compatible. The following figure shows the Intersection operation:

Figure: Intersection

Intersection operation can be denoted by the following notation:

R∩S

Example:

List all the Employees who are enrolled in both EMP and EMP1 relations:

EName(EMP) ∩ EName(EMP1)

The above Intersection operation produces the following relation:

d). Cartesian product:

The Cartesian product operation produces a relation that is the concatenation of every tuple of relation R with every
tuple of relation S.

 The Cartesian product operation multiplies two relations to define another relation consisting of all possible
pairs of tuples from the two relations. Therefore, if one relation has I tuples and N attributes and the other has J
tuples and M attributes, the Cartesian product relation will contain (I * J) tuples with (N + M) attributes.

Product operation can be denoted by the following notation:

R×S

Example: Find the Cartesian Product of the relations P and Q


Product of P×Q

JOIN

Join operation allows information to be combined from two or more relations. It joins the relations by common
attributes.

The following are various forms of Join operation:

 Theta join
 Equijoin (a particular type of Theta join)
 Natural join
 Outer join
 Semijoin

a). Theta Join ( − )

The Theta join operation produces a relation that contains tuples satisfying the predicate F from the Cartesian product
of R and S.

The predicate F is of the form R.ai S.bi.

Here, may be one of the comparison operators <, ≤, >, ≥, =, ≠


The following expression produces all the students and their subjects using Theta join with the comparison operator ‘=’.

STUDENT ⋈ STUDENT.class = COURSE.course COURSE

STUID SNAME CLASS COURSE SUBJECT

1001 Arun 468 468 Comp.Sci


1001 Arun 468 468 Maths
1002 Bharathi 402 402 Commerce
1002 Bharathi 402 402 Computers

b). EquiJoin:

Equi join is a particular type of Theta Join. It joins the tables on the basis of an equality condition. The outcome of
the equijoin does not eliminate duplicate columns. The equijoin uses the equality comparison operator (=) in the
condition.

c). Natural Join:

A natural join links tables by selecting only rows with common values in their common attributes. A natural join is
the result of three-stage process

First a Product of the tables is created. For example:


EMP_ID ENAME JOB SAL DEPTNO

12345 Arun Manager 25000 10


12346 Bhavya Clerk 10000 20
12347 Charan Typist 8000 10
12349 Eeshwar Clerk 10000 30

DEPTNO DNAME LOCATION

10 Accounts Bangalore
20 Finance Mumbai
30 Production Hyderabad PRODUCT
40 Marketing Delhi
EMP_ ENAME JOB SAL DEPT DEPT DNAME LOCATION
ID NO NO
12345 Arun Manager 25000 10 10 Accounts Banglore
12345 Arun Manager 25000 10 20 Finance Mumbai
12345 Arun Manager 25000 10 30 Production Hyderabad
12345 Arun Manager 25000 10 40 Marketing Delhi
12346 Bhavya Clerk 10000 20 10 Accounts Banglore
12346 Bhavya Clerk 10000 20 20 Finance Mumbai
12346 Bhavya Clerk 10000 20 30 Production Hyderabad
12346 Bhavya Clerk 10000 20 40 Marketing Delhi
12347 Charan Typist 8000 10 10 Accounts Banglore
12347 Charan Typist 8000 10 20 Finance Mumbai
12347 Charan Typist 8000 10 30 Production Hyderabad
12347 Charan Typist 8000 10 40 Marketing Delhi
12349 Eeshwar Clerk 10000 30 10 Accounts Banglore
12349 Eeshwar Clerk 10000 30 20 Finance Mumbai
12349 Eeshwar Clerk 10000 30 30 Production Hyderabad
12349 Eeshwar Clerk 10000 30 40 Marketing Delhi

Second, a SELECT is performed on the result of the Product, as shown below:

EMP_ID ENAME JOB SAL DEPT DEPT DNAME LOCATION


NO NO
12345 Arun Manager 25000 10 10 Accounts Banglore
12346 Bhavya Clerk 10000 20 20 Finance Mumbai
12347 Charan Typist 8000 10 10 Accounts Banglore
12349 Eeshwar Clerk 10000 30 30 Production Hyderabad

Third, a PROJECT is performed on the result of select, as shown below:

EMP_ ENAME JOB SAL DEPT DNAME LOCATION


ID NO
12345 Arun Manager 25000 10 Accounts Banglore
12346 Bhavya Clerk 10000 20 Finance Mumbai
12347 Charan Typist 8000 10 Accounts Banglore
12349 Eeshwar Clerk 10000 30 Production Hyderabad
The final outcome of a natural join yields a table that has only the matched rows.

d). Outer Join:

In an outer join, the matched pairs would be retained and any unmatched values in the other table would be left null.

A left outer join produces all of the rows from R, including those that do not have a matching value in the common
attributes of S.

The following is the left outer join on the above two relations STUDENT and PROFESSOR

STUDENT PROFESSOR

It will produce the following relation:

SID SUBJECT P.SID TEACHER


1001 DBMS 1001 RAVII
1002 JAVA 1002 NAVEEN
1003 CPP
1004 PYTHON 1004 RAM

A Right outer join produces all of the rows from S, including those that do not have a matching value in the common
attributes of R.

The following is the right outer join on the above two relations STUDENT and PROFESSOR

STUDENT PROFESSOR

It will produce the following relation:

SID SUBJECT P.SID TEACHER


1001 DBMS 1001 RAVII
1002 JAVA 1002 NAVEEN
1004 PYTHON 1004 RAM
1005 GIRI
e). Semi Join:

Semi Join performs a join operation on two relations and Projects over the attributes of first relation. It limits the tuples
in the join operation. It increases the performance of the join operation. Semi Join is particularly useful in distributed
systems

STUDENT

SID SUBJECT
1001 DBMS
1002 JAVA
1003 CPP
1004 PYTHON

The following is the Semi join on the above two relations STUDENT and PROFESSOR

Sid, Subject ((STUDENT)⋈Student.Subject = Professor.Subject (PROFESSOR))

It will produce the following relation:

SID SUBJECT

1001 DBMS

1004 PYTHON
Division

The Division operation defines a relation over the attributes C that consists of the set of tuples from R that match the
combination of every tuple in S.

A division operation can be indicated by the following notation:

R÷S

Example:

Aggregation and Grouping Operations:

Aggregate Operations:

Aggregate Operations will perform summation or aggregation of data. It uses the following functions:

 COUNT – returns the number of values in the associated attribute.


 SUM – returns the sum of the values in the associated attribute.
 AVG – returns the average of the values in the associated attribute.
 MIN – returns the smallest value in the associated attribute.
 MAX – returns the largest value in the associated attribute.

Aggregate operations uses the following notation:

AL(R)

Example:

To find the number of rows in EMP relation:

EMP(myCount) COUNT EMP_ID (EMP)

It will produce the following output:

myCount

------------

Example: Find the Minimum, Maximum, Average Salary of the Employees:

EMP (minSal, maxSal, AvgSal) MIN SAL, MAX SAL, AVG SAL, (EMP)
It will produce the following output:

minSal maxSal AvgSal


9000 25000 15300

Group functions:

Group functions Groups the tuples of relation R by the grouping attributes, GA, and then applies the aggregate function
list AL to define a new relation.

Grouping operation will take the following format:

a1, a2, . . . , an <Apap>, <Aqaq>, . . . , <Azaz>(R)

Example:

Find the number of Employees working in each Department and the sum of their salaries.

EMP(Deptno, myCount, mySum) deptno, COUNT EMP_ID, SUM SAL, (EMP)

It will produce the following output:

Deptno myCount MySum


10 3 43500
20 2 33000
Relational Calculus

o Relational calculus is a non-procedural query language. In the non-procedural query language, the user is
concerned with the details of how to obtain the end results.

o The relational calculus tells what to do but never explains how to do.

Types of Relational calculus:

1. Tuple Relational Calculus (TRC)

o The tuple relational calculus is specified to select the tuples in a relation. In TRC, filtering variable uses the
tuples of a relation.

o The result of the relation can have one or more tuples.

Notation:

1. {T | P (T)} or {T | Condition (T)}

Where

T is the resulting tuples

P(T) is the condition used to fetch T.

For example:

1. { T.name | Author(T) AND T.article = 'database' }

OUTPUT: This query selects the tuples from the AUTHOR relation. It returns a tuple with 'name' from Author who has
written an article on 'database'.

TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and Universal Quantifiers (∀).

For example:

1. { R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}

Output: This query will yield the same result as the previous one.
2. Domain Relational Calculus (DRC)

o The second form of relation is known as Domain relational calculus. In domain relational calculus, filtering
variable uses the domain of attributes.

o Domain relational calculus uses the same operators as tuple calculus. It uses logical connectives ∧ (and), ∨ (or)
and ┓ (not).

o It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable.

Notation:

1. { a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}

Where a1, a2 are attributes

P stands for formula built by inner attributes

For example:

1. {< article, page, subject > | ∈ javatpoint ∧ subject = 'database'}

Output: This query will yield the article, page, and subject from the relational javatpoint, where the subject is a database.

EXPRESSIVE POWER OF ALGEBRA AND CALCULUS

We presented two formal query languages for the relational model. Are they equivalent in power? Can every
query that can be expressed in relational algebra also be expressed in relational calculus? The answer is yes, it can.

Regarding expressiveness, we can show that every query that can be expressed using a safe relational calculus
query can also be expressed as a relational algebra query. The expressive power of relational algebra is often used as a
metric of how powerful a relational database query language is. If a query language can express all the queries that we
can express in relational algebra, it is said to be relationally complete. A practical query language is expected to be
relationally complete; in addition, commercial query languages typically support features that allow us to express some
queries that cannot be expressed in relational algebra.
SQL

Introduction:

SQL is the standard relational database language. SQL was standardized by the American National Standards
Institute (ANSI) in 1986. The same was adopted as an international standard by the International Organization for
Standardization (ISO) in 1987. More than one hundred DBMSs now support SQL.

Objectives of SQL

As a database language, SQL provides the features 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 can perform these tasks with minimal user effort. Its command structure and syntax is relatively easy to
learn. SQL is portable, it can work on any platform.
 SQL is an example of a transform-oriented language. It transforms the user inputs into required outputs.

As a language, the ISO SQL standard has two major components:

a Data Definition Language (DDL) for defining the database structure and controlling access to the data;

a Data Manipulation Language (DML) for retrieving and updating data.

Features of SQL:

 SQL is a relatively easy language to learn:


 It is a nonprocedural language: SQL does not require you to specify the access methods to the data.
 Like most modern languages, SQL is essentially free-format, which means that parts of statements do not have
to be typed at particular locations on the screen.
 The command structure consists of standard English words such as CREATE TABLE, INSERT, SELECT.
 SQL can be used by a range of users including database administrators (DBA), management personnel,
application developers, and many other types of end-user.

History of SQL

 In 1974, D. Chamberlin, also from the IBM San José Laboratory, defined a language called the Structured
English Query Language, or SEQUEL.
 A revised version, SEQUEL/2, was defined in 1976, but the name was changed to SQL.
 Importance of SQL
 SQL is the first and, so far, only standard database language to gain wide acceptance.
 Nearly every major current vendor provides database products based on SQL
 SQL would support interoperability across disparate systems.
 SQL is used in other standards and even influences the development of other standards.
 Specialized implementations of SQL, such as OnLine Analytical Processing (OLAP).
SQL Commands

o SQL commands are instructions. It is used to communicate with the database. It is also used to perform specific
tasks, functions, and queries of data.

o SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set
permission for users.

Types of SQL Commands

There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL)

o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.

o All the command of DDL are auto-committed that means it permanently save all the changes in the database.

Here are some commands that come under DDL:

o CREATE

o ALTER

o DROP

o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);


b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

DROP TABLE table_name;

Example

DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be either to modify the characteristics of an
existing attribute or probably to add a new attribute.

Syntax:

To add a new column in the table

ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));


ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.

Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE EMPLOYEE;


2. Data Manipulation Language

o DML commands are used to modify the database. It is responsible for all form of changes in the database.

o The command of DML is not auto-committed that means it can't permanently save all the changes in the database.
They can be rollback.

Here are some commands that come under DML:

o INSERT

o UPDATE

o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.

Syntax:

INSERT INTO TABLE_NAME


(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);

Or

INSERT INTO TABLE_NAME


VALUES (value1, value2, value3, .... valueN);

For example:

INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]

For example:

UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.

Syntax:

DELETE FROM table_name [WHERE condition];

For example:

DELETE FROM javatpoint


WHERE Author="Sonoo";
3. Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant

o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;


b. Revoke: It is used to take back permissions from the user.

Example

REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;


4. Transaction Control Language

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be used while creating tables or
dropping them.

Here are some commands that come under TCL:

o COMMIT

o ROLLBACK

o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

COMMIT;

Example:

DELETE FROM CUSTOMERS


WHERE AGE = 25;
COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database.

Syntax:

ROLLBACK;

Example:

DELETE FROM CUSTOMERS


WHERE AGE = 25;
ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;
5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

o SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to select the attribute based on
the condition described by WHERE clause.

Syntax:

SELECT expressions
FROM TABLES
WHERE conditions;

For example:

SELECT emp_name
FROM employee
WHERE age > 20;

DATA MANIPULATION LANGUAGE

DML provides a set of operations to support the basic data manipulation operations on the data in the database. Data
manipulation operations usually include the following:

SELECT – to query data in the database

INSERT – to insert data into a table

UPDATE – to update data in a table

DELETE – to delete data from a table

Simple Queries

SELECT statement can be useful to retrieve and display data from one or more database tables. It can perform the
equivalent of the relational algebra’s Selection, Projection, and Join operations in a single statement.

SELECT command has the following general form:

SELECT [DISTINCT | ALL] {* | [columnExpression [AS newName]] [, . . .]}

FROM TableName [alias] [, . . .]

[WHERE condition]

[GROUP BY columnList] [HAVING condition]

[ORDER BY columnList]

Here, The ColumnExpression represents a column name or an expression, TableName is the name of an existing
database table or view that you have access to, and alias is an optional abbreviation for TableName.

Example:

Retrieve all columns, all rows

List full details of all Employees.

SELECT Emp_Id, Ename, DOB, Dept_No, Sal FROM EMP;

OR

SELECT * FROM EMP;


It returns the following result:

EMP_ID ENAME DOB JOB DEPTNO SAL

1001 Arun 10-Jun-1991 Clerk 10 9000

1002 Bharathi 01-Jan-1992 Manager 20 18000

1003 Charitha 03-Jan-1992 Asst.Manager 20 15000

1004 Dheeraj 15-Jun-1992 Off.Asst 10 9500

1005 Ravi 04-Feb-1992 Manager 10 25000

Retrieve specific columns, all rows

Produce a list of salaries for all Employees, showing only the Emp number, Emp names, and the salary details.

SELECT Emp_Id, Ename, Sal from EMP;

It returns the following result:

EMP_ID ENAME SAL

1001 Arun 9000

1002 Bharathi 18000

1003 Charitha 15000

1004 Dheeraj 9500

1005 Ravi 25000

Use of DISTINCT

We use the DISTINCT keyword to eliminate the duplicates columns.

Example:

SELECT DISTINCT Dept_No FROM EMP

It will return the following result:

DEPTNO

10

20
Calculated Fields:

A calculated field (a computed or derived field) can be used by specifying an SQL expression in the SELECT
list. This expression can involve addition, subtraction, multiplication, and division. We can use more than one column
in a calculated field. The columns referenced in an arithmetic expression must have a numeric type.

Example:

Produce a list of monthly salaries for all Employees, showing the EmpNumber, Ename, and the Annual salary details.

SELECT Emp_ID, Ename, Sal*12 “Annual Sal” FROM EMP;

It returns the following result:


EMP_ID ENAME Annual Sal

1001 Arun 108000

1002 Bharathi 216000

1003 Charitha 180000

1004 Dheeraj 114000

1005 Ravi 300000

Here, Sal * 12 “Annual Sal” is the calculated Field.

Row selection (WHERE clause)

WHERE clause can be useful to restrict the rows that are retrieved. A WHERE clause consists of the keyword
WHERE followed by a search condition that specifies the rows to be retrieved.

A search condition may be of the following types:

 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 condition

List all Employees with a Salary greater than ₹10000.

SELECT Emp_ID, Ename, Job, DeptNo, Sal

FROM EMP

WHERE Sal > 10000;

EMP_ID ENAME JOB SAL

1002 Bharathi Manager 18000

1003 Charitha Asst.Manager 15000

1005 Ravi Manager 25000

In SQL, the following simple comparison operators are available:

= 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


AND OR and NOT

More complex predicates can be generated using the logical operators AND, OR, and NOT.

The rules for evaluating a conditional expression are:

 An expression is evaluated left to right;


 Sub expressions in brackets are evaluated first;
 NOTs are evaluated before ANDs and ORs;
 ANDs are evaluated before ORs.

Compound comparison search condition

The logical operator OR is used in the WHERE clause to find the employees working in JOB either as
Clerks or Managers

For example:

List the Employees who are working as either Managers or Clerks.

SELECT * FROM EMP

WHERE JOB = ‘Clerk’ OR JOB = ‘Manager';

It returns the following result:

EMP_ID ENAME JOB DEPTNO SAL

1001 Arun Clerk 10 9000

1002 Bharathi Manager 20 18000

1005 Ravi Manager 10 25000

Range search condition (BETWEEN/NOT BETWEEN)

In SQL, the BETWEEN test includes the endpoints of the range.

For example:

List all staff with a salary between ₹20,000 and ₹30,000.

SELECT EMP_ID, EName, Job, Sal

FROM EMP

WHERE Sal BETWEEN 20000 AND 30000;

It returns the following result:

EMP_ID ENAME JOB DEPTNO SAL

1005 Ravi Manager 10 25000

Set membership search condition (IN/NOT IN)

The set membership test (IN) tests whether a data value matches one of a list of values,

For example:
List all managers and Clerks.

SELECT Emp_ID, EName, Job

FROM EMP

WHERE Job IN (‘Manager’, ‘Clerk’);

It returns the following result:

EMP_ID ENAME JOB

1001 Arun Clerk

1002 Bharathi Manager

1005 Ravi Manager

Pattern match search condition (LIKE/NOT LIKE)

SQL has two special pattern-matching symbols (wildcards):

The % percent character represents a sequence of characters

The _ underscore character represents a single character.

For example:

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.

For example,

To list the employees names that starts with 'A'

SELECT Ename FROM EMP

WHERE Ename like 'A%';

It returns the following result:

ENAME

=======

Arun

NULL search condition (IS NULL/IS NOT NULL)

In all modern DBMSs. A null comment is considered as an unknown value. So that we can test the presence of a
null value, explicitly by using the special keyword IS NULL.

For example:

SELECT ENAME FROM EMP

WHERE DEPTNO IS NULL;


SORTING RESULTS

We can sort the results of a query by using the ORDER BY clause in the SELECT statement. The ORDER BY
clause requires column identifiers to sort the result.

It also allows the retrieved rows to be ordered in ascending (ASC) or descending (DESC) order.

Single-column ordering

Single column ordering can be achieved by adding the ORDER BY clause to the end of the SELECT statement.

For example:

Produce a list of salaries for all Employees, arranged in descending order of salary.

SELECT Emp_ID, EName, Sal FROM EMP

ORDER BY Sal DESC;

It returns the following result:

EMP_ID ENAME SAL

---------- ---------- ----------

1005 Ravi 25000

1002 Bharathi 18000

1003 Charitha 15000

1004 Dheeraj 9500

1001 Arun 9000

Multiple-Column ordering

We can include more than one element in the ORDER BY clause to control the sort. The first element
specified in the ORDER BY clause is referred as the major sort key. It determines the overall order of the result.

If the values of the major sort key are unique, there is no need to specify the additional keys. If the
values of the major sort key are not unique, then it may require a second sort key. The second element that
appears in the ORDER BY clause is called a minor sort key.

For example:

To produce the a list of Employees order by DeptNo and Job

SELECT Emp_ID, Ename, Job FROM EMP1

ORDER BY DeptNo, Job;

It returns the following result:

EMP_ID ENAME JOB

1001 Arun Clerk

1005 Ravi Manager

1004 Dheeraj Off.Asst

1003 Charitha A.Manager

1002 Bharathi Manager


SQL Aggregate Functions

The ISO standard SQL provides five aggregate functions to perform some form of summation or aggregation of
data. Those are:

COUNT – It returns the number of values in a specified column

SUM –It returns the sum of the values in a specified column

AVG – It returns the average of the values in a specified column

MIN – It returns the smallest value in a specified column

MAX – It returns the largest value in a specified column

These functions operate on a single column of a table and return a single value.

COUNT, MIN, and MAX apply to both numeric and nonnumeric fields, but SUM and AVG may be used on
numeric fields only

COUNT:

The COUNT function is used to tally the number of non-null values of an attribute. COUNT can be used in
conjunction with the DISTINCT clause.

Syntax:

COUNT(columnname)

Examples:

SELECT COUNT(DEPTNO) FROM EMP;

SELECT COUNT(EMP_ID) FROM EMP;

1. COUNT(*): It is a special use of COUNT that counts all the rows of a table, regardless of whether nulls or
duplicate values occur.

2. DISTINCT: We have to use the keyword DISTINCT before the column name in the functio, if we want to
eliminate duplicates before the function is applied.

MAX:

The MAX function is used to find the maximum of the given attribute.

Syntax:

MAX(columnname)

Example:

SELECT MAX(SAL) FROM EMP;


MIN:

The MAX function is used to find the maximum of the given attribute.

Syntax:

MIN(columnname)

Example:

SELECT MIN(SAL) FROM EMP;

SUM:

The SUM function returns the total sum for any specified attribute.

Syntax:

SUM(columnname)

Example:

SELECT SUM(SAL) FROM EMP;

AVG:

The AVG function returns the average of the specified columns.

Syntax:

AVG(columnname)

Example:

SELECT AVG(SAL) FROM EMP;

Grouping results
The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped according
to one or more columns. The GROUP BY clause is generally used when we have attribute columns combined
with aggregate functions in the SELECT statement. The GROUP BY clause can be used in conjunction with the
SQL aggregate functions, such as COUNT, MIN, MAX, AVG, and SUM.

It takes the following form:

SELECT column_name, aggr_function(column_name) FROM table_name

WHERE condition GROUP BY column_name


Example:

Use of GROUP BY

Find the number of staff working in each Dept and the sum of their salaries.

SELECT DeptNo, COUNT(EmpID) AS myCount, SUM(sal) AS SumofSal FROM EMP

GROUP BY DeptNo ORDER BY DeptNo;

Sub Queries
A subquery is a query that is nested inside another query. The inner query is always executed first. A
Sub query is also known as a nested query or an inner query. Characteristics of Subqueries:

 A subquery is a query inside a query.


 It can be expressed inside brackets (parentheses).
 The first query in the SQL statement is known as the outer query.
 The query inside the SQL statement is known as the inner query.
 The inner query is executed first.
 The output of an inner query is used as the input for the outer query.

Using a subquery with equality

List the Employees who work in the Department at ‘Mumbai’.

SELECT EMP_ID, ENAME, JOB FROM EMP

WHERE DEPTNO = (SELECT DEPTNO FROM DEPT

WHERE Location = 'Mumbai');

It will produce the following results:

EMP_ID ENAME JOB

---------- ---------- ----------

1002 Bharathi Manager

1003 Charitha A.Manager

Using a subquery with an aggregate function

List all Employees whose salary is greater than the average salary, and show by how much their salary is greater
than the average.

SELECT Emp_ID, ENAME, JOB,SAL – (SELECT AVG(SAL) FROM EMP1) AS salDiff FROM EMP1

WHERE Sal > (SELECT AVG(Sal) FROM EMP1);


It will produce the following result:

EMP_ID ENAME JOB SALDIFF

1002 Bharathi Manager 2700

1005 Ravi Manager 9700

ANY and ALL

The keywords ANY and ALL may be used with subqueries that produce a single column of numbers.

If the subque ry is preceded by the keyword ALL, the condition will be true only if it is satisfied by all values
produced by the subquery.

If the subquery is preceded by the keyword ANY, the condition will be true if it is satisfied by any (one or more)
values produced by the subquery.

If the subquery is empty, the ALL condition returns true, the ANY condition returns false.

The ISO standard also allows the qualifier SOME to be used in place of ANY.

For example:

Use of ANY/SOME

Find all Employees whose salary is larger than the salary of at least one member of Employees at Dept 20;

SELECT EMP_ID, ENAME, JOB, SAL FROM EMP

WHERE SAL > SOME (SELECT SAL FROM EMP WHERE DEPTNO= 20);

Use of ALL

Find all Employees whose salary is larger than the salary of every member of Employees at Dept 10;

SELECT EMP_ID, ENAME, JOB, SAL FROM EMP

WHERE SAL > ALL (SELECT SAL FROM EMP WHERE DEPTNO= 10);

Multi-table Queries
The SQL join operation combines information from two tables by forming pairs of related rows from
the two tables.

The result table contains those rows, where the matching columns in each of the two tables have the
same value.

To perform a join, we simply include more than one table name in the FROM clause, using a comma as
a separator, and typically including a WHERE clause to specify the join column(s).

We can also use an alias for a table named in the FROM clause. An alias can be used to qualify a
column name whenever there is ambiguity regarding the source of the column name. It can also be used as a
shorthand notation for the table name. If an alias is provided, it can be used anywhere in place of the table name.
Example:

Simple join

List the names, JoB of all Employees whos details match with DEPT table;

SELECT E.DEPTNO, ENAME, JOB FROM EMP e, DEPT d WHERE e.DEPTNO = d.DEPTNO;

To obtain the required rows, we include those rows from both tables that have identical values in the DEPTNO
columns, using the search condition (e.DEPTNO = d.DEPTNO). We call these two columns the matching
columns for the two tables. This is equivalent to the relational algebra Equijoin operation.

EXISTS and NOT EXISTS

The keywords EXISTS and NOT EXISTS check for the existence or nonexistence of rows in the subquery result
table. They can produce a simple true/false result. These keywords can be used only with subqueries.

The keyword EXISTS is true if and only if there exists at least one row in the result table returned by the
subquery. NOT EXISTS is the opposite of EXISTS.

Example Query using EXISTS:

Find all Employees who work in the department located at Delhi.

SELECT EMP_ID, ENAME, JOB FROM EMP e

WHERE EXISTS (SELECT * FROM DEPT d

WHERE e.DEPTNo = d.DEPTNO AND LOCATION = ‘DELHI’);

Combining Result Tables

We can use the set operations of Union, Intersection, and Difference to combine the results of two or more
queries into a single result table:

The Union of two tables, A and B, is a table containing all rows of A or B or both A and B.

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 to be combined using the set operations must be union-compatible.

In the ISO standard, these three set operators are called UNION, INTERSECT, and EXCEPT.

The format of the set operator clause in each case is:

operator [ALL] [CORRESPONDING [BY {column1 [, . . .]}]]

Use of UNION

Construct a list of all employees whose job is 'Clerk' or the location is 'Chennai'

(SELECT ENAME FROM EMP WHERE JOB='CLERK')

UNION

(SELECT ENAME FROM EMP e

WHERE EXISTS (SELECT * FROM DEPT d

WHERE e.DEPTNo = d.DEPTNO AND LOCATION = ‘Chenni’));


Use of INTERSECT

Construct a list of all Employee who enrolled in both EMP and EMP1 tables.

(SELECT ENAME FROM EMP) INTERSECT

(SELECT ENAME FROM EMP);

Use of EXCEPT

Construct a list of all Employee who enrolled in EMP but not in EMP1 table.

(SELECT ENAME FROM EMP) EXCEPT

(SELECT ENAME FROM EMP1)

Database Updates

SQL provides three statements to modify the contents of the tables in the database:

INSERT – adds new rows of data to a table

UPDATE – modifies existing data in a table

DELETE – removes rows of data from a table

Inserting the values (INSERT)

INSERT statement has two forms:

The first allows a single row to be inserted into a named table and has the following format:

INSERT INTO TableName [(columnList)] VALUES (dataValueList)

Example:

INSERT INTO EMP VALUES (‘1020’, ‘ANITHA’, ‘04-FEB-1991', ‘Assistant’, 20, 12000);

As we are inserting data into each column in the order the table was created, there is no need to specify a
column list.

INSERT . . . SELECT

The INSERT INTO SELECT statement copies data from one table and inserts it into another table.

INSERT INTO SELECT requires that data types in source and target tables must be matched.

The existing records in the target table are unaffected.

Syntax:

INSERT INTO table2

SELECT * FROM table1

WHERE condition;
Example:

INSERT INTO EMP1 (EMP_ID, ENAME, DOB, JOB, DEPTNO, SAL)

SELECT EMP_ID, ENAME, DOB, JOB, DEPTNO, SAL FROM EMP;

Modifying data in the database (UPDATE)

The UPDATE statement allows to change the contents of existing rows in a table.

The format of the command is:

UPDATE TableName

SET columnName1 = dataValue1 [, columnName2 = dataValue2 . . .]

[WHERE searchCondition]

Example:

UPDATE all rows

Give all Employees a 3% pay increase.

UPDATE EMP SET sal = sal*1.03;

UPDATE specific rows

Give all Managers a 5% pay increase.

UPDATE EMP SET sal = sal*1.05 WHERE job = ‘Manager’;

Deleting data from the database (DELETE)

The DELETE statement deletes the rows from a table. The format of the command is:

DELETE FROM TableName

[WHERE searchCondition]

Delete all employees working in department 30;

DELETE FROM EMP WHERE DEPTNO = 30;

DELETE all rows

Delete all rows from the EMP table.

DELETE FROM EMP;


The ISO SQL Data Types

The following are the data types defined in the SQL standard.

DATA TYPE DECLARATIONS

Boolean BOOLEAN

Character CHAR VARCHAR

Bit BIT BIT

VARYING

Exact numeric NUMERIC DECIMAL INTEGER SMALLINT

BIGINT

Approximate FLOAT REAL DOUBLEPRECISION

numeric

Datetime DATE TIME TIMESTAMP

Interval INTERVAL

Large objects CHARACTER LARGE OBJECT BINARY LARGE OBJECT

Boolean data:

Boolean data consists of the distinct truth values TRUE and FALSE.

Character data:

Character data consists of a sequence of characters. When a character string column is defined, a length can be
specified to indicate the maximum number of characters that the column can hold (default length is 1).

For example, the Department Number column DEPTNO of the DEPT table, which has a fixed length of three
characters, is declared as:

DEPTNo CHAR(3)

Bit data

The bit data type is used to define bit strings, that is, a sequence of binary digits (bits), each having either the
value 0 or 1. The format for specifying the bit data type is similar to that of the character data type: BIT
[VARYING] [length]

For example, to hold the fixed length binary string "0011", we declare a column bitString, as:

bitString BIT(4)

Exact Numeric Data

The exact numeric data type is used to define numbers with an exact representation. The number consists of
digits, an optional decimal point, and an optional sign. An exact numeric data type consists of a precision and a
scale.
There are several ways of specifying an exact numeric data type:

NUMERIC [ precision [, scale] ]

DECIMAL [ precision [, scale] ]

INTEGER

SMALLINT

BIGIN

INTEGER can be abbreviated to INT and DECIMAL to DEC

INTEGER is used for large positive or negative whole numbers. SMALLINT is used for small positive or
negative whole numbers and BIGINT for very large whole numbers.

Approximate numeric data

The approximate numeric data type is used for defining numbers that do not have an exact representation, such
as real numbers. There are several ways of specifying an approximate numeric data type:

FLOAT [precision]

REAL

DOUBLE PRECISION

Datetime data

The datetime data type is used to define points in time to a certain degree of accuracy.

Examples are dates, times, and times of day. The ISO standard subdivides the datetime data type into YEAR,
MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_HOUR, and TIMEZONE_MINUTE.

Three types of datetime data type are supported:

DATE

TIME [timePrecision] [WITH TIME ZONE]

TIMESTAMP [timePrecision] [WITH TIME ZONE]

DATE is used to store calendar dates using the YEAR, MONTH, and DAY fields. TIME is used to store time
using the HOUR, MINUTE, and SECOND fields. TIMESTAMP is used to store date and times. The
timePrecision is the number of decimal places of accuracy to which the SECOND field is kept.

Interval data

The interval data type is used to represent periods of time. Every interval data type consists of a contiguous
subset of the fields: YEAR, MONTH, DAY, HOUR.

Large objects

A large object is a data type that holds a large amount of data, such as a long text file or a graphics file. Three
different types of large object data types are defined in SQL:

Binary Large Object (BLOB): A Binary Large Object Stores any kind of data in binary format. Typically used
for multimedia data such as images, audio, and video.

Character Large Object (CLOB): Stores string data in the database character set format. Used for large strings or
documents that use the database character set exclusively.

National Character Large Object (NCLOB): Stores string data in National Character Set format. Used for large
strings or documents in the National Character Set. Supports characters of varying width format.
Integrity Enhancement Feature
Integrity is usually expressed in terms of constraints. Constraints are consistency rules that the database is not
permitted to violate.

We consider five types of integrity constraint:

 Required data;
 Domain constraints;
 Entity integrity;
 Referential integrity;
 General constraints.

These constraints can be defined in the CREATE and ALTER TABLE statements.

Required Data

Some columns must contain a valid value; they are not allowed to contain nulls.

This constraint can be implemented by using the keyword NOT NULL in the CREATE and ALTER TABLE
statements.

For example, to specify that the column JOB of the EMP table cannot be null, we define the column as:

JOB VARCHAR(10) NOT NULL

Domain Constraints

Every column has a domain; A domain is the set of allowable values for one or more attributes.

For example, The domain of the column sex of the EMP table is a single character string consisting of either
‘M’ or ‘F’.

The ISO standard provides two mechanisms for specifying domains :

CHECK clause

CREATE DOMAIN statement

CHECK clause allows a constraint to be defined on a column or the entire table.

The format of the CHECK clause is: CHECK (searchCondition).

In a column constraint, the CHECK clause can reference only the column being defined. Thus, to ensure that the
column sex can be specified only as ‘M’ or ‘F’.

We could define the column as: sex CHAR NOT NULL CHECK (sex IN (‘M’, ‘F’))

CREATE DOMAIN statement:

CREATE DOMAIN DomainName [AS] dataType [DEFAULT defaultOption] [CHECK (searchCondition)]

The preferred method of defining domain constraints is using the CREATE DOMAIN statement. Domains can
be removed from the database using the DROP DOMAIN statement:

DROP DOMAIN DomainName [RESTRICT | CASCADE]


Entity Integrity

The primary key of a table must contain a unique, nonnull value for each row. An entity integrity can be
implemented with the PRIMARY KEY clause in the CREATE and ALTER TABLE statements. For example,
to define the primary key of the EMP table, as: PRIMARY KEY(EMP_ID)

We can define a composite primary key by specifying multiple column names. For example, to define the
primary key of the EMP table, which consists of the columns EMP_ID and DEPTNO, as:

PRIMARY KEY(EMP_ID, DEPTNO)

Referential Integrity

Referential integrity means that, if the foreign key contains a value, that value must refer to an existing, valid
row in the parent table.

For example, the Department Number column DEPTNo in the DEPT table links the department to that row in
the EMP table where the deptno is assigned.

We can define foreign keys with the FOREIGN KEY clause in the CREATE and ALTER TABLE statements.
For example, to define the foreign key DEPTNO of the DEPT table, we include the clause:

FOREIGN KEY(DeptNo) REFERENCES EMP;

General Constraints

The ISO standard allows general constraints to be specified using the CHECK and UNIQUE clauses of the
CREATE and ALTER TABLE statements and the CREATE ASSERTION statement. The UNIQUE keyword
ensures uniqueness for any alternate keys in the table.

The CREATE ASSERTION statement is an integrity constraint that is not directly linked with a table definition.

The format of the statement is:

CREATE ASSERTION AssertionName CHECK (searchCondition)

Creating a Database
A schema is a named collection of database objects including tables, views, domains, assertions,
collations, translations, and character sets.

The schema definition statement has the following form:

CREATE SCHEMA [Name | AUTHORIZATION Creatorldentifier]

Therefore, if the creator of a schema 'TestSchema' is 'Ravi', then the SQL statement is:

CREATE SCHEMA TestSchema AUTHORIZATION Ravi;

A schema can be destroyed using the DROP SCHEMA statement. It has the following form:

DROP SCHEMA Name [RESTRICT | CASCADE]


Creating a Table (CREATE TABLE)

We can create the table structures by using the CREATE TABLE statement, which has the following basic
syntax:

CREATE TABLE TableName

column1 datatype,

column2 datatype,

column3 datatype,

.....

columnN datatype,

PRIMARY KEY( one or more columns )

);

The CREATE TABLE statement creates a table called TableName consisting of one or more columns of the
specified dataType.

Example:

CREATE TABLE EMPLOYEE(

EMPID INT NOT NULL,

ENAME VARCHAR (20) NOT NULL,

AGE INT NOT NULL,

ADDRESS CHAR (25) ,

SALARY DECIMAL (18, 2),

PRIMARY KEY (EMPID));

Changing a Table Definition (ALTER TABLE)

The ALTER TABLE statement can be used for changing the structure of a table once it has been created. The
definition of the ALTER TABLE statement in the ISO standard consists of six options to:

 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.

The basic syntax of an ALTER TABLE command to add a New Column:

ALTER TABLE table_name ADD column_name datatype;

Example:

ALTER TABLE EMPLOYEE ADD SEX char(1);


The basic syntax of an ALTER TABLE command to DROP COLUMN:

ALTER TABLE table_name DROP COLUMN column_name;

Example:

ALTER TABLE CUSTOMERS DROP SEX;

The basic syntax of an ALTER TABLE command to change the DATA TYPE:

ALTER TABLE table_name MODIFY COLUMN column_name datatype;

Example:

ALTER TABLE EMPLOYEE MODIFY JOB char(15);

Removing a Table (DROP TABLE)

We can remove an unwanted table from the database using the DROP TABLE statement. It has the following
format:

DROP TABLE TableName [RESTRICT | CASCADE]

DROP TABLE command removes not only the table, but also all the rows within it. For example, to remove the
EMP1 table we use the command:

DROP TABLE EMP1;

Constraints in SQL

Constraints in SQL means we are applying certain conditions or restrictions on the database. This further means
that before inserting data into the database, we are checking for some conditions. If the condition we have applied
to the database holds true for the data which is to be inserted, then only the data will be inserted into the database
tables.

Constraints in SQL can be categorized into two types:

Column Level Constraint:

Column Level Constraint is used to apply a constraint on a single column.

Table Level Constraint:

Table Level Constraint is used to apply a constraint on multiple columns.


Some of the real-life examples of constraints are as follows:

Every person has a unique email id. This is because while creating an email account for any user, the email
providing services such as Gmail, Yahoo or any other email providing service will always check for the
availability of the email id that the user wants for himself. If some other user already takes the email id that the
user wants, then that id cannot be assigned to another user. This simply means that no two users can have the same
email ids on the same email providing service. So, here the email id is the constraint on the database of email
providing services.

Whenever we set a password for any system, there are certain constraints that are to be followed. These constraints
may include the following:

o There must be one uppercase character in the password.

o Password must be of at least eight characters in length.

o Password must contain at least one special symbol.

Constraints available in SQL are:

1. NOT NULL

2. UNIQUE

3. PRIMARY KEY

4. FOREIGN KEY

5. CHECK

6. DEFAULT

7. CREATE INDEX

Now let us try to understand the different constraints available in SQL in more detail with the help of examples.
We will use MySQL database for writing all the queries.

1. NOT NULL

o NULL means empty, i.e., the value is not available.

o Whenever a table's column is declared as NOT NULL, then the value for that column cannot be empty
for any of the table's records.

o There must exist a value in the column to which the NOT NULL constraint is applied.

NOTE: NULL does not mean zero. NULL means empty column, not even zero.
Syntax to apply the NOT NULL constraint during table creation:

CREATE TABLE TableName (ColumnName1 datatype NOT NULL, ColumnName2 datatype,…., ColumnNa
meN datatype);

Example:

Create a student table and apply a NOT NULL constraint on one of the table's column while creating a table.

CREATE TABLE student(StudentID INT NOT NULL, Student_FirstName VARCHAR(20), Student_LastNa


me VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));

To verify that the not null constraint is applied to the table's column and the student table is created successfully,
we will execute the following query:

mysql> DESC student;

Syntax to apply the NOT NULL constraint on an existing table's column:

ALTER TABLE TableName CHANGE Old_ColumnName New_ColumnName Datatype NOT NULL;

Example:

Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply a
NOT NULL constraint to one of the table's column. Then we will execute the following query:

1. mysql> ALTER TABLE student CHANGE StudentID StudentID INT NOT NULL;
To verify that the not null constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

2. UNIQUE

o Duplicate values are not allowed in the columns to which the UNIQUE constraint is applied.

o The column with the unique constraint will always contain a unique value.

o This constraint can be applied to one or more than one column of a table, which means more than one
unique constraint can exist on a single table.

o Using the UNIQUE constraint, you can also modify the already created tables.

Syntax to apply the UNIQUE constraint on a single column:

CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2 datatype,…., ColumnNam


eN datatype);

Example:

Create a student table and apply a UNIQUE constraint on one of the table's column while creating a table.

mysql> CREATE TABLE student(StudentID INT UNIQUE, Student_FirstName VARCHAR(20), Student_L


astName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));

To verify that the unique constraint is applied to the table's column and the student table is created successfully,
we will execute the following query:

mysql> DESC student;


Syntax to apply the UNIQUE constraint on more than one column:

CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype,…., ColumnNameN datatyp


e, UNIQUE (ColumnName1, ColumnName 2));

Example:

Create a student table and apply a UNIQUE constraint on more than one table's column while creating a table.

mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName V


ARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), UNIQUE(Stude
ntID, Student_PhoneNumber));

To verify that the unique constraint is applied to more than one table's column and the student table is created
successfully, we will execute the following query:

mysql> DESC student;


Syntax to apply the UNIQUE constraint on an existing table's column:

ALTER TABLE TableName ADD UNIQUE (ColumnName);

Example:

Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply a
UNIQUE constraint to one of the table's column. Then we will execute the following query:

mysql> ALTER TABLE student ADD UNIQUE (StudentID);

To verify that the unique constraint is applied to the table's column and the student table is created successfully,
we will execute the following query:

mysql> DESC student;

3. PRIMARY KEY

o PRIMARY KEY Constraint is a combination of NOT NULL and Unique constraints.

o NOT NULL constraint and a UNIQUE constraint together forms a PRIMARY constraint.

o The column to which we have applied the primary constraint will always contain a unique value and will
not allow null values.

Syntax of primary key constraint during table creation:

CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, ColumnName2 datatype,…., Colu
mnNameN datatype);
Example:

Create a student table and apply the PRIMARY KEY constraint while creating a table.

mysql> CREATE TABLE student(StudentID INT PRIMARY KEY, Student_FirstName VARCHAR(20), St


udent_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(4
0));

To verify that the primary key constraint is applied to the table's column and the student table is created
successfully, we will execute the following query:

mysql> DESC student;

Syntax to apply the primary key constraint on an existing table's column:

ALTER TABLE TableName ADD PRIMARY KEY (ColumnName);

Example:

Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply the
PRIMARY KEY constraint to the table's column. Then we will execute the following query:

mysql> ALTER TABLE student ADD PRIMARY KEY (StudentID);

To verify that the primary key constraint is applied to the student table's column, we will execute the following
query:

mysql> DESC student;


4. FOREIGN KEY

o A foreign key is used for referential integrity.

o When we have two tables, and one table takes reference from another table, i.e., the same column is
present in both the tables and that column acts as a primary key in one table. That particular column will
act as a foreign key in another table.

Syntax to apply a foreign key constraint during table creation:

CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY, ColumnNameN Datatype(SI


ZE), FOREIGN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAME(Primary_Key_ColumnNa
me));

Example:

Create an employee table and apply the FOREIGN KEY constraint while creating a table.

To create a foreign key on any table, first, we need to create a primary key on a table.

mysql> CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR
(40), Emp_Salary VARCHAR (40));

To verify that the primary key constraint is applied to the employee table's column, we will execute the following
query:

mysql> DESC employee;


Now, we will write a query to apply a foreign key on the department table referring to the primary key of the
employee table, i.e., Emp_ID.

mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR
(40), Emp_ID INT NOT NULL, FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID));

To verify that the foreign key constraint is applied to the department table's column, we will execute the following
query:

mysql> DESC department;

Syntax to apply the foreign key constraint with constraint name:

CREATE TABLE tablename(ColumnName1 Datatype PRIMARY KEY, ColumnNameN Datatype(SIZE), C


ONSTRAINT ConstraintName FOREIGN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAM
E(Primary_Key_ColumnName));

Example:

Create an employee table and apply the FOREIGN KEY constraint with a constraint name while creating a table.

To create a foreign key on any table, first, we need to create a primary key on a table.

mysql> CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR
(40), Emp_Salary VARCHAR (40));

To verify that the primary key constraint is applied to the student table's column, we will execute the following
query:

mysql> DESC employee;


Now, we will write a query to apply a foreign key with a constraint name on the department table referring to the
primary key of the employee table, i.e., Emp_ID.

mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR
(40), Emp_ID INT NOT NULL, CONSTRAINT emp_id_fk FOREIGN KEY(Emp_ID) REFERENCES emp
loyee(Emp_ID));

To verify that the foreign key constraint is applied to the department table's column, we will execute the following
query:

mysql> DESC department;

Syntax to apply the foreign key constraint on an existing table's column:

ALTER TABLE Parent_TableName ADD FOREIGN KEY (ColumnName) REFERENCES Child_TableNa


me (ColumnName);

Example:

Consider we have an existing table employee and department. Later, we decided to apply a FOREIGN KEY
constraint to the department table's column. Then we will execute the following query:

mysql> DESC employee;


mysql> ALTER TABLE department ADD FOREIGN KEY (Emp_ID) REFERENCES employee (Emp_ID);

To verify that the foreign key constraint is applied to the department table's column, we will execute the following
query:

mysql> DESC department;

5. CHECK

o Whenever a check constraint is applied to the table's column, and the user wants to insert the value in it,
then the value will first be checked for certain conditions before inserting the value into that column.

o For example: if we have an age column in a table, then the user will insert any value of his choice. The
user will also enter even a negative value or any other invalid value. But, if the user has applied check
constraint on the age column with the condition age greater than 18. Then in such cases, even if a user
tries to insert an invalid value such as zero or any other value less than 18, then the age column will not
accept that value and will not allow the user to insert it due to the application of check constraint on the
age column.
Syntax to apply check constraint on a single column:

CREATE TABLE TableName (ColumnName1 datatype CHECK (ColumnName1 Condition), ColumnName2


datatype,…., ColumnNameN datatype);

Example:

Create a student table and apply CHECK constraint to check for the age less than or equal to 15 while creating a
table.

mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName V


ARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), Age INT CHE
CK( Age <= 15));

To verify that the check constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

Syntax to apply check constraint on multiple columns:

CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype CHECK (ColumnName1 C


ondition AND ColumnName2 Condition),…., ColumnNameN datatype);

Example:

Create a student table and apply CHECK constraint to check for the age less than or equal to 15 and a percentage
greater than 85 while creating a table.

mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName V


ARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), Age INT, Perce
ntage INT, CHECK( Age <= 15 AND Percentage > 85));
To verify that the check constraint is applied to the age and percentage column, we will execute the following
query:

mysql> DESC student;

Syntax to apply check constraint on an existing table's column:

ALTER TABLE TableName ADD CHECK (ColumnName Condition);

Example:

Consider we have an existing table student. Later, we decided to apply the CHECK constraint on the student
table's column. Then we will execute the following query:

mysql> ALTER TABLE student ADD CHECK ( Age <=15 );

To verify that the check constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;


6. DEFAULT

Whenever a default constraint is applied to the table's column, and the user has not specified the value to be
inserted in it, then the default value which was specified while applying the default constraint will be inserted into
that particular column.

Syntax to apply default constraint during table creation:

CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, ColumnName2 datatype,…., Colu
mnNameN datatype);

Example:

Create a student table and apply the default constraint while creating a table.

mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName V


ARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40) DEFAULT "anu
ja.k8@gmail.com");

To verify that the default constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

Syntax to apply default constraint on an existing table's column:

ALTER TABLE TableName ALTER ColumnName SET DEFAULT Value;

Example:

Consider we have an existing table student. Later, we decided to apply the DEFAULT constraint on the student
table's column. Then we will execute the following query:

mysql> ALTER TABLE student ALTER Student_Email_ID SET DEFAULT "anuja.k8@gmail.com";


To verify that the default constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

7. CREATE INDEX

CREATE INDEX constraint is used to create an index on the table. Indexes are not visible to the user, but they
help the user to speed up the searching speed or retrieval of data from the database.

Syntax to create an index on single column:

CREATE INDEX IndexName ON TableName (ColumnName 1);

Example:

Create an index on the student table and apply the default constraint while creating a table.

mysql> CREATE INDEX idx_StudentID ON student (StudentID);

To verify that the create index constraint is applied to the student table's column, we will execute the following
query:

mysql> DESC student;


Syntax to create an index on multiple columns:

CREATE INDEX IndexName ON TableName (ColumnName 1, ColumnName 2, ColumnName N);

Example:

mysql> CREATE INDEX idx_Student ON student (StudentID, Student_PhoneNumber);

To verify that the create index constraint is applied to the student table's column, we will execute the following
query:

mysql> DESC student;

Syntax to create an index on an existing table:

ALTER TABLE TableName ADD INDEX (ColumnName);

Consider we have an existing table student. Later, we decided to apply the DEFAULT constraint on the student
table's column. Then we will execute the following query:

mysql> ALTER TABLE student ADD INDEX (StudentID);

To verify that the create index constraint is applied to the student table's column, we will execute the following
query:

mysql> DESC student;


PL/SQL - Triggers
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are,
in fact, written to be executed in response to any of the following events −
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Triggers can be written for the following purposes −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions
Creating Triggers
The syntax for creating a trigger is −

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with
the trigger_name.
 {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD
OF clause is used for creating trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
 [OF col_name] − This specifies the column name that will be updated.
 [ON table_name] − This specifies the name of the table associated with the trigger.
 [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various
DML statements, such as INSERT, UPDATE, and DELETE.
 [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row
being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which
is called a table level trigger.
 WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is
valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would fire for INSERT or
UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary
difference between the old values and new values −

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
The following points need to be considered here −
 OLD and NEW references are not available for table-level triggers, rather you can use them for record-
level triggers.
 If you want to query the table in the same trigger, then you should use the AFTER keyword, because
triggers can query the table or change it again only after the initial changes are applied and the table is
back in a consistent state.
 The above trigger has been written in such a way that it will fire before any DELETE or INSERT or
UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for
example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE
operation on the table.

Stored Procedure in SQL Server

A stored procedure is a group of one or more pre-compiled SQL statements into a logical unit. It is stored as
an object inside the database server. It is a subroutine or a subprogram in the common computing language that
has been created and stored in the database. Each procedure in SQL Server always contains a name, parameter
lists, and Transact-SQL statements. The SQL Database Server stores the stored procedures as named objects.
We can invoke the procedures by using triggers, other procedures, and applications such as Java, Python, PHP,
etc. It can support almost all relational database systems.

SQL Server builds an execution plan when the stored procedure is called the first time and stores them in the
cache memory. The plan is reused by SQL Server in subsequent executions of the stored procedure, allowing it
to run quickly and efficiently.

Features of Stored Procedures in SQL Server

The following are the features of stored procedure in SQL Server:

o Reduced Traffic: A stored procedure reduces network traffic between the application and the database
server, resulting in increased performance. It is because instead of sending several SQL statements, the
application only needs to send the name of the stored procedure and its parameters.

o Stronger Security: The procedure is always secure because it manages which processes and activities
we can perform. It removes the need for permissions to be granted at the database object level and
simplifies the security layers.

o Reusable: Stored procedures are reusable. It reduces code inconsistency, prevents unnecessary rewrites
of the same code, and makes the code transparent to all applications or users.

o Easy Maintenance: The procedures are easier to maintain without restarting or deploying the
application.

o Improved Performance: Stored Procedure increases the application performance. Once we create the
stored procedures and compile them the first time, it creates an execution plan reused for subsequent
executions. The procedure is usually processed quicker because the query processor does not have to
create a new plan.
Types of Stored Procedures

SQL Server categorizes the stored procedures mainly in two types:

1. User-defined Stored Procedures

2. System Stored Procedures

User-defined Stored Procedures

Database developers or database administrators build user-defined stored procedures. These procedures
provide one or more SQL statements for selecting, updating, or removing data from database tables. A stored
procedure specified by the user accepts input parameters and returns output parameters. DDL and DML
commands are used together in a user-defined procedure.

We can further divide this procedure into two types:

o T-SQL Stored Procedures: Transact-SQL procedures are one of the most popular types of SQL Server
procedures. It takes parameters and returns them. These procedures handle INSERT, UPDATE, and
DELETE statements with or without parameters and output row data.

o CLR Stored Procedures: The SQL Server procedures are a group of SQL commands, and the CLR
indicates the common language runtime. CLR stored procedures are made up of the CLR and a stored
procedure, which is written in a CLR-based language like VB.NET or C#. CLR procedures are .Net
objects that run in the SQL Server database's memory.

System Stored Procedures

The server's administrative tasks depend primarily on system stored procedures. When SQL Server is installed, it
creates system procedures. The system stored procedures prevent the administrator from querying or modifying
the system and database catalog tables directly. Developers often ignore system stored procedures.

SQL Server Stored Procedures Syntax

The following are the basic syntax to create stored procedures in SQL Server:

CREATE PROCEDURE [schema_name].procedure_name


@parameter_name data_type,
....
parameter_name data_type
AS
BEGIN
-- SQL statements
-- SELECT, INSERT, UPDATE, or DELETE statement
END
Parameter Explanations

The stored procedure syntax has the following parameters:

Schema_name: It is the name of your database or schema. By default, a procedure is associated with the current
database, but we can also create it into another database by specifying the DB name.

Procedure_Name: It represents the name of your stored procedure that should be meaningful names so that you
can identify them quickly. It cannot be the system reserved keywords.

Parameter_Name: It represents the number of parameters. It may be zero or more based upon the user
requirements. We must ensure that we used the appropriate data type. For example, @Name VARCHAR(50).

SET NOCOUNT ON in Stored Procedure

In some cases, we use the SET NOCOUNT ON statement in the stored procedure. This statement prevents the
message that displays the number of rows affected by SQL queries from being shown. NOCOUNT denotes that
the count is turned off. It means that if SET NOCOUNT ON is set, no message would appear indicating the
number of rows affected.

How to execute/call a stored procedure?

We can use the EXEC command to call/execute stored procedures in SQL Server. The following syntax
illustrates the execution of a stored procedure:

EXEC procedure_name;
Or,
EXECUTE procedure_name;

If we are using the SSMS, we need to use the below steps to execute stored procedures:

1. Navigate to the Programmability -> Stored Procedures.

2. Next, select the Stored Procedure menu and expand it. You will see the available stored procedures.

3. Right-click on the stored procedure you want to execute and choose the Execute Stored Procedure

4. The Execute Procedure window will appear. If the procedure has any parameters, we must assign/pass
them before clicking OK to execute it. If no parameters are defined, click OK to run the procedure.

Stored Procedure Simple Example

We can create a stored procedure in SQL Server in two ways:

o Using T-SQL Query

o Using SQL Server Management Studio


We will take a student table to demonstrate the stored procedure examples. This table has the following data:

The below example uses the CREATE PROCEDURE SQL statement for creating a stored procedure that
displays the student's list in the increasing order of a salary from the STUDENT table in the selected database:

CREATE PROCEDURE studentList


AS
BEGIN
SELECT name, age, salary
FROM STUDENT
ORDER BY salary;
END;

In this syntax, the studentList is the name of the stored procedure, and the AS keyword distinguishes the stored
procedure's heading and body. The BEGIN and END keywords that accompany a single statement in a stored
procedure are optional. However, it's a good idea to include them to make the code more understandable.

When we run this statement, and everything is correct, the following message will appear: "Commands
completed successfully." It indicates that the stored procedure was successfully compiled and saved to the
database system.

We can execute this procedure by using the below command:

1. EXEC studentList;

It will return the output as follows:

You might also like