0% found this document useful (0 votes)
40 views

Unit 4 SQL

Uploaded by

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

Unit 4 SQL

Uploaded by

luvyharish
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT IV

SQL
What is SQL?
• SQL stands for Structured Query Language. It is used for storing and managing data in
Relational Database Management System (RDBMS).
• It is a standard language for Relational Database System. It enables a user to create,
read, update and delete relational databases and tables.
• All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as
their standard database language.
• SQL allows users to query the database in a number of ways, using English-like
statements.
What are the SQL rules?
SQL follows the following rules:
• Structure query language is not case sensitive. Generally, keywords of SQL are written
in uppercase.
• Statements of SQL are dependent on text lines. We can use a single SQL statement on
one or multiple text line.
• Using the SQL statements, you can perform most of the actions in a database.
• SQL depends on tuple relational calculus and relational algebra.
Importance of SQL
SQL is the first and, so far, only standard database language to gain wide acceptance.
The only other standard database language, the Network Database Language (NDL),
based on the CODASYL network model, has few followers.
It has become part of application architectures such as IBM’s Systems Application
Architecture (SAA) and is the strategic choice of many large and influential
organizations, for example, the X/OPEN consortium for UNIX standards.
SQL has also become a Federal Information Processing Standard (FIPS), to which
conformance is required for all sales of DBMSs to the US government. The SQL Access
Group, a consortium of vendors, defined a set of enhancements to SQL that would
support interoperability across disparate systems.
SQL is used in other standards and even influences the development of other standards
as a definitional tool. Examples include ISO’s Information Resource Dictionary System
(IRDS) standard and Remote Data Access (RDA) standard. The development of the
language is supported by considerable academic interest, providing both a theoretical
basis for the language and the techniques needed to implement it successfully. This is

1
especially true in query optimization, distribution of data, and security. There are now
specialized implementations of SQL that are directed at new markets, such as OnLine
Analytical Processing (OLAP).
What is Advantages of SQL?
• High speed
• No coding needed
• Well defined standards
• Portability
• Multiple data view
 Used with any DBMS system with any vendor
 Used for relational databases
 Easy to learn and understand
 Both as programming language and interactive language
 Client/Server language
 Dynamic database language
 Supports object based programming
 Integrates with Java
 Used in internet
 Used by IBM and Microsoft
SQL Commands
• 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.
• SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.
Creating a Database
 According to the ISO standard, relations and other database objects exist in an
environment.
 Among other things, each environment consists of one or more catalogs, and
each catalog consists of a set of schemas.
 A schema is a named collection of database objects that are in some way
related to one another (all the objects in the database are described in one
schema or another).
 The objects in a schema can be tables, views, domains, assertions, collations,
translations, and character sets.
 All the objects in a schema have the same owner and share a number of defaults.
Creating and destroying schemas
The schema creation statement has the following form:
CREATE SCHEMA [Name | AUTHORIZATION CreatorIdentifier]

2
Therefore, if the creator of a schema Jmc is Smith, the SQL statement is:
CREATE SCHEMA Jmc AUTHORIZATION Smith;
A schema can be destroyed using the DROP SCHEMA statement, which has the
following form:
DROP SCHEMA Name [RESTRICT | CASCADE]
 If RESTRICT is specified, which is the default if neither qualifier is specified, the
schema must be empty or the operation fails.
 If CASCADE is specified, the operation cascades to drop all objects associated
with the schema in the order defined above.
 If any of these drop operations fail, the DROP SCHEMA fails.
 The total effect of a DROP SCHEMA with CASCADE can be very extensive and
should be carried out only with extreme caution.
 The CREATE and DROP SCHEMA statements are not yet widely implemented.

Types of SQL Commands


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

1. Data Definition language (DDL)


2. Data Manipulation Language (DML)
3. Data Query Language (DQL)
4. Data Control Language (DCL)
5. Data Administration Statements (DAS)
6. Transaction Control Statements (TCS)

Data Administration Statements (DAS):

Data Administration commends allow the user to perform audits and


analysis on operations within the database.
Also analyze the performance of the system.
Data Administration commends are:

3
START AUDIT
STOP AUDIT

Data Definition Language (DDL)


• DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
• 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:
CREATE
ALTER
DROP
TRUNCATE

 The SQL Data Definition Language (DDL) allows database objects such as schemas,
domains, tables, views, and indexes to be created and destroyed.
(or)
 DDL statements are used to build and modify the structure of your tables
and other objects in the database. When you execute a DDL statement, it takes
effect immediately.
 The main SQL data definition language statements are:

 These statements are used to create, change, and destroy the structures that
make up the conceptual schema.
 Although not covered by the SQL standard, the following two statements are
provided by many DBMSs:
CREATE INDEX
DROP INDEX
Data Definition Language (DDL)- CREATE
CREATE It is used to create a new table in the database.
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

4
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR(20), empid VARCHAR(100),salary INT);
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
Example
The following example, which creates a CUSTOMERS table with an ID as a primary key
and NOT NULL are the constraints showing that these fields cannot be NULL while
creating records in this table −
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now we can verify if our table has been created successfully by looking at the message
displayed by the SQL server, otherwise you can use the DESC command as follows −
SQL> DESC CUSTOMERS;
+---------+---------------+------ +---- -+-------- -+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------ +----- +--------- +-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |

5
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+--------------- +------ +----- +-------- -+------ -+
5 rows in set (0.00 sec)
Now, we have CUSTOMERS table available in our database which you can use to store
the required information related to customers.
Data Definition Language (DDL)- Drop
Drop: It is used to delete both the structure and record stored in the table.
Syntax:
DROP TABLE ;
Example:
DROP TABLE EMPLOYEE;
Data Definition Language (DDL)- ALTER
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.
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.
Syntax:
ALTER TABLE table_name ADD column_name COLUMN-definition;
ALTER TABLE MODIFY(COLUMN DEFINITION....);
Example:
ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
Data Definition Language (DDL)- TRUNCATE
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:
6
TRUNCATE TABLE EMPLOYEE;

Data Manipulation Language(DML)


• DML commands are used to modify the database. It is responsible for all form of
CHANGES in the database.
• 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:
INSERT
UPDATE
DELETE
SELECT – to query data in the database;
Data Manipulation Language - INSERT
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);
Example:
INSERT INTO XYZ (Author, Subject) VALUES ("Sonoo", "DBMS");
Data Manipulation Language - UPDATE
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]
Example:
UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3';

7
SELECT Statement
The purpose of the SELECT statement is to retrieve and display data from one or more
database tables. It is an extremely powerful command in SQL.
By using this command, we can also access the particular record from the particular
column of the table. The table which stores the record returned by the SELECT
statement is called a result-set table.
Select-From-Where Statements:

 The SELECT clause lists the data items to be retrieved by the SELECT statement.
The
items may be columns from the database, or columns to be calculated by SQL as
it performs the query.
 The FROM clause lists the tables that contain the data to be retrieved by the
query.
 The WHERE clause tells SQL to include only certain rows of data in the query
results. A search condition is used to specify the desired rows.
Basic Structure:
Basic Structure of an SQL Expression consists of three clauses:
SELECT <attributes>
FROM <one or more relations>
WHERE <conditions>
For Example:
SELECT NAME, HIRE_DATE
FROM SALESREPS
WHERE SALES > 500000.00
SELECT statement:
SQL SELECT statement is used to fetch the data from a database table which returns data
in the form of result table. These result tables are called result-sets.

Syntax:
The basic syntax of SELECT statement is as follows:

SELECT column1, column2, columnN FROM table name;

8
Here, column1, column2...are the fields of a table whose values you want to fetch. If you
want to fetch all the fields available in the field, then you can use the following syntax:

SELECT * FROM table name;

Example:
Consider the CUSTOMERS table having the following records:

SELECT * FROM CUSTOMERS;

Following is an example, which would fetch ID, Name and Salary fields of the customers
available in CUSTOMERS table:

DISTINCT keyword:

The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate
all the duplicate records and fetching only unique records.

Syntax:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:

SELECT DISTINCT column1, column2,.....columnN


FROM table_name
WHERE [condition]

Example:
Consider the CUSTOMERS table having the following records:

9
First, let us see how the following SELECT query returns duplicate salary records:

SQL> SELECT SALARY


FROM CUSTOMERS
ORDER BY SALARY;

This would produce the following result where


salary 2000 is coming twice which is a duplicate
record from the original table.

Now, let us use DISTINCT keyword with the


above SELECT query and see the result:

SQL> SELECT DISTINCT SALARY


FROM CUSTOMERS
ORDER BY SALARY;

This would produce the following result where


we do not have any duplicate entry:

10
Calculated fields

Produce a list of monthly salaries for all staff, showing the staff number, the first and
last names, and the salary details.

SELECT staffNo, fName, lName, salary/12 FROM Staff;

This query is almost identical to Example 5.2, with the exception that monthly salaries
are required.In this case, the desired result can be obtained by simply dividing the
salary by 12, giving the result table shown in Table 5.4.

This is an example of the use of a calculated field (sometimes called a computed or

derived field). In general, to use a calculated field you specify an SQL expression in the

SELECT list. An SQL expression can involve addition, subtraction, multiplication,


and division, and parentheses can be used to build complex expressions.

Some other examples are


SQL> SELECT 2*35 FROM DUAL;
SQL> SELECT salary + 1500 FROM employees;
SQL> SELECT first_name, salary, salary + (commission_pct* salary) FROM employees;

11
SQL - WHERE Clause
The SQL WHERE clause is used to specify a condition while fetching the data from a single
table or by joining with multiple tables.
If the given condition is satisfied, then only it returns a specific value from the table. You
should use the WHERE clause to filter the records and fetching only the necessary
records.
The WHERE clause is not only used in the SELECT statement, but it is also used in the
UPDATE, DELETE statement, etc.,

Syntax

The basic syntax of the SELECT statement with the WHERE clause is as shown below.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
You can specify a condition using the comparison or logical operators like >, <, =, LIKE,
NOT, etc. The following examples would make this concept clear.
Example
The following code is an example which would fetch the ID, Name and Salary fields from
the CUSTOMERS table, where the salary is greater than 2000 −
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;
This would produce the following result −
This would produce the following result −
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

12
The following query is an example, which would fetch the ID, Name and Salary
fields from the CUSTOMERS table for a customer with the name Hardik.
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE NAME = 'Hardik';
This would produce the following result −
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 5 | Hardik | 8500.00 |
+----+----------+----------+
SQL - AND and OR Conjunctive Operators
The SQL AND & OR operators are used to combine multiple conditions to narrow
data in an SQL statement. These two operators are called as the conjunctive operators.
The AND Operator
The AND operator allows the existence of multiple conditions in an SQL
statement's WHERE clause.
The basic syntax of the AND operator with a WHERE clause is as follows
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
You can combine N number of conditions using the AND operator. For an action
to be taken by the SQL statement, whether it be a transaction or a query, all conditions
separated by the AND must be TRUE.

Example
Following is an example, which would fetch the ID, Name and Salary fields from
the CUSTOMERS table, where the salary is greater than 2000 and the age is less than 25
years −

SQL> SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY > 2000 AND age < 25;

13
This would produce the following result −
+----+-------+----------+
| ID | NAME | SALARY |
+----+-------+----------+
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+-------+----------+
The OR Operator
The OR operator is used to combine multiple conditions in an SQL statement's
WHERE clause.
Syntax
The basic syntax of the OR operator with a WHERE clause is as follows −
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
You can combine N number of conditions using the OR operator. For an action to
be taken by the SQL statement, whether it be a transaction or query, the only any ONE of
the conditions separated by the OR must be TRUE.
The following code block has a query, which would fetch the ID, Name and Salary
fields from the CUSTOMERS table, where the salary is greater than 2000 OR the age is
less than 25 years.
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 OR age < 25;
This would produce the following result −
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

14
Range search condition (BETWEEN/NOT BETWEEN)
List all staff with a salary between £20,000 and £30,000.
SELECT staffNo, fName, lName, position, salary
FROM Staff
WHERE salary BETWEEN 20000 AND 30000;
The BETWEEN test includes the endpoints of the range, so any members of staff with a
salary of £20,000 or £30,000 would be included in the result. The result table is shown
in
Table 5.7.

Example 5.8 Set membership search condition (IN/NOT IN)


List all managers and supervisors.
SELECT staffNo, fName, lName, position
FROM Staff
WHERE position IN (‘Manager’, ‘Supervisor’);
The set membership test (IN) tests whether a data value matches one of a list of values,
in this case either ‘Manager’ or ‘Supervisor’. The result table is shown in Table 5.8.
There is a negated version (NOT IN) that can be used to check for data values that do
not lie in a specific list of values. Like BETWEEN, the IN test does not add much to the
expressive power of SQL. We could have expressed the above query as:

15
LIKE clause:

The SQL LIKE clause is used to compare a value to similar values using wildcard
operators. There are two wildcards used in conjunction with the LIKE operator:

 The percent sign (%)

 The underscore (_)

The percent sign represents zero, one, or multiple characters. The underscore represents
a single number or character. The symbols can be used in combinations.

Syntax:
The basic syntax of % and _ is as follows:
You can combine N number of conditions
using AND or OR operators. Here, XXXX
could be any numeric or string value.

Example:

Here are number of examples showing


WHERE part having different LIKE clause
with '%' and '_' operators:

Statement Description

WHERE SALARY LIKE


Finds any values that start with 200
'200%'

16
WHERE SALARY LIKE
Finds any values that have 200 in any position
'%200%'

WHERE SALARY LIKE Finds any values that have 00 in the second and third
'_00%' positions

WHERE SALARY LIKE Finds any values that start with 2 and are at least 3
'2_%_%' characters in length

WHERE SALARY LIKE '%2' Finds any values that end with 2

WHERE SALARY LIKE Finds any values that have a 2 in the second position and
'_2%3' end with a 3

WHERE SALARY LIKE Finds any values in a five-digit number that start with 2
'2___3' and end with 3

Let us take a real example, consider the CUSTOMERS table having the following records:

Following is an example, which would display all the records from CUSTOMERS table
where SALARY starts with 200:

SQL> SELECT * FROM CUSTOMERS


WHERE SALARY LIKE '200%';

This would produce the following result:

17
Selecting computed values:

The basic syntax of SELECT statement with WHERE clause is as follows:

SELECT column1, column2, columnN


FROM table_name
WHERE [condition]
You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT,
etc. Below examples would make this concept clear.

Example:

Consider the CUSTOMERS table having the following records:

Following is an example which would fetch ID, Name and Salary fields from the
CUSTOMERS table where salary is greater than 2000:

SQL> SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY > 2000;

This would produce the following result:

Selection involving NULLs:

The SQL NULL is the term used to represent a missing value. A NULL value in a table is a
value in a field that appears to be blank.

18
A field with a NULL value is a field with no value. It is very important to understand that
a NULL value is different than a zero value or a field that contains spaces.

Syntax:
The basic syntax of NULL while creating a table:

Here, NOT NULL signifies that column should always accept an explicit value of the given
data type. There are two columns where we did not use NOT NULL, which means these
columns could be NULL.

A field with a NULL value is one that has been left blank during record creation.

Example:
You must use the IS NULL or IS NOT NULL operators in order to check for a NULL value.

Consider the following table, CUSTOMERS having the following records:

Now, following is the usage of IS NOT NULL operator:

SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY


FROM CUSTOMERS
WHERE SALARY IS NOT NULL;

This would produce the following result:

19
Now, following is the usage of IS NULL operator:

SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY


FROM CUSTOMERS
WHERE SALARY IS NULL;

This would produce the following result:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+

GROUP BY while selecting:

The SQL GROUP BY clause is used in collaboration with the SELECT statement to
arrange identical data into groups.

The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes
the ORDER BY clause.

Syntax:

The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow
the conditions in the WHERE clause and must precede the ORDER BY clause if one is
used.

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

20
Example:

Consider the CUSTOMERS table is having the following records:

Let us have following table where CUSTOMERS table has the following records with
duplicate names:

If you want to know the total amount of salary on each customer, then GROUP BY query
would be as follows:

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME;
This would produce the following result:

ORDER BY while selecting:

The SQL ORDER BY clause is used to sort the data in ascending or descending order,
based on one or more columns. Some database sorts query results in ascending order by
default.

Syntax:
The basic syntax of ORDER BY clause is as follows:

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

21
You can use more than one column in the ORDER BY clause. Make sure whatever column
you are using to sort, that column should be in column-list.

Example:
Consider the CUSTOMERS table having the following records:

Following is an example, which would


sort the resultin ascending order by
NAME and SALARY:

SQL> SELECT * FROM CUSTOMERS SQL> SELECT * FROM CUSTOMERS


ORDER BY NAME, SALARY; ORDER BY NAME DESC;

This would produce the following result: This would produce the following result:

Following is an example, which would


sort the result in descending order by
NAME:

22
Using the SQL Aggregate Functions

As well as retrieving rows and columns from the database, we often want to perform some

form of summation or aggregation of data, similar to the totals at the bottom of a report.

The ISO standard defines five aggregate functions:

n COUNT – returns the number of values in a specified column;

n SUM – returns the sum of the values in a specified column;

n AVG – returns the average of the values in a specified column;

n MIN – returns the smallest value in a specified column;

n MAX – returns the largest value in a specified column.

COUNT ( ) Function:

This function is used to count the number of values in a column.

COUNT (*) is used to count the number of rows in the table including duplicates
and those with NULL values.

23
Example 1:
o SELECT COUNT (*) FROM EXAMINATION;
o The above query returns 10.

Example 2:
o SELECT COUNT (RegNo) FROM EXAMINATION WHERE CC = „C3‟ ;
o The above query returns 4.

AVG ( ) Function:

This function is used to find the average of the values in a numeric column.

Example 1:
o SELECT AVG (Cs) FROM EXAMINATION;
o The above query returns 74.7

SUM ( ) Function:

This function is used to find the sum of the values in a numeric column.

Example:
o SELECT SUM (Phy) FROM EXAMINATION;
o The above query returns 729

MAX ( ) Function:

This function is used to find the maximum values in a column.

Example:
o SELECT MAX (Phy) FROM EXAMINATION;
o The above query returns 100

MIN ( ) Function:

This function is used to find the minimum values in a column.


Example:
o SELECT MIN (Phy) FROM EXAMINATION;
o The above query returns 33

24
GROUP BY :

Example 1: To find the number of students in each college.


SELECT CC, COUNT (CC) FROM EXAMINATION GROUP BY CC;
Example 2: To find the number of students, sum, average, maximum, minimum
marks in computer science from each city.
SELECT City, COUNT (City), SUM (Cs), AVG (Cs), MAX (Cs), MIN (Cs) FROM
EXAMINATION GROUP BY City;

HAVING

• HAVING clause is used to specify a search condition for a group or an aggregate.

• Having is used in a GROUP BY clause. If you are not using GROUP BY clause then
you can use HAVING function like a WHERE clause

Syntax

SELECT column1, column2 FROM table_name


WHERE conditions
GROUP BY column1, column2
HAVING conditions
ORDER BY column1, column2;

Example

SELECT COMPANY, COUNT(*)


FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING COUNT(*)>2;

25
Nested Queries (SubQueries)

A Subquery or Inner query or Nested query is a query within another SQL query and
embedded within the WHERE clause.

A subquery is used to return data that will be used in the main query as a condition
to further restrict the data to be retrieved.

Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.

There are a few rules that subqueries must follow:

 Subqueries must be enclosed within parentheses.

 A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected
columns.

 An ORDER BY cannot be used in a subquery, although the main query can use
an ORDER BY. The GROUP BY can be used to perform the same function as the
ORDER BY in a subquery.

 Subqueries that return more than one row can only be used with multiple value
operators, such as the IN operator.

 The SELECT list cannot include any references to values that evaluate to a
BLOB, ARRAY, CLOB, or NCLOB.

 A subquery cannot be immediately enclosed in a set function.

 The BETWEEN operator cannot be used with a subquery; however, the


BETWEEN operator can be used within the subquery.

Subqueries with the SELECT Statement:

Subqueries are most frequently used with the SELECT statement. The basic syntax is
as follows:

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR

26
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])

Example:

Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Now, let us check following subquery with SELECT statement:

SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;

This would produce the following result:

+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

27
Example 5.20 Using a subquery with an aggregate function

List all staff whose salary is greater than the average salary, and show by how much

their salary is greater than the average.

SELECT staffNo, fName, lName, position, salary

FROM Staff

WHERE (SELECT AVG(salary) FROM Staff) < salary;

Example 5.21 Nested subqueries: use of IN

List the properties that are handled by staff who work in the branch at ‘163 Main St’.

SELECT propertyNo, street, city, postcode, type, rooms, rent

FROM PropertyForRent

WHERE staffNo IN (SELECT staffNo

FROM Staff

WHERE branchNo = (SELECT branchNo

FROM Branch

WHERE street = ‘163 Main St’));

28
ANY and ALL

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

If the subquery is preceded by the keyword ALL, the condition will only be true 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.

Example 5.22 Use of ANY/SOME

Find all staff whose salary is larger than the salary of at least one member of staff at

branch B003.

SELECT staffNo, fName, lName, position, salary

FROM Staff

WHERE salary > SOME (SELECT salary

FROM Staff

WHERE branchNo = ‘B003’);

29
Example 5.23 Use of ALL

Find all staff whose salary is larger than the salary of every member of staff at

branch B003.

SELECT staffNo, fName, lName, position, salary

FROM Staff

WHERE salary > ALL (SELECT salary

FROM Staff

WHERE branchNo = ‘B003’);

This is very similar to the last example. Again, we could use a subquery to find the
maximum salary of staff at branch B003 and then use an outer query to find all staff
whose salary is greater than this number. However, in this example we use the ALL
keyword. The result table is shown in Table 5.23.

Multi-Table Queries

To combine columns from several tables into a result table we need to

use a join operation. The SQL join operation combines information from two tables

by forming pairs of related rows from the two tables.

SQL JOIN
SQL, JOIN means "to combine two or more tables". In SQL, JOIN clause is used to
combine the records from two or more tables in a database.

30
Types of SQL JOIN
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as
long as the condition is satisfied. It returns the combination of all rows from both
the tables where the condition satisfies.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Example
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

LEFT JOIN
The SQL left join returns all the values from left table and the matching values
from the right table. If there is no matching join value, it will return NULL.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1

31
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Example
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right
table and the matched values from the left table. If there is no matching in both
tables, it will return NULL.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Example
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join.
Join tables have all the records from both tables. It puts NULL on the place of
matches not found.

32
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Example
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

EXISTS and NOT EXISTS


The keywords EXISTS and NOT EXISTS are designed for use only with subqueries.
They produce a simple true/false result. EXISTS is true if and only if there exists at
least one row in the result table returned by the subquery; it is false if the subquery
returns an empty result table. NOT EXISTS is the opposite of EXISTS. Since EXISTS
and NOT EXISTS check only for the existence or non-existence of rows in the
subquery result table, the subquery can contain any number of columns. For
simplicity it is common for subqueries following one of these keywords to be of the
form:
(SELECT * FROM . . . )

33
34
SET OPERATIONS:
SQL supports few Set operations which can be performed on the table data.
These are used to get meaningful results from data stored in the table, under
different special conditions.In this tutorial, we will cover 4 different types of SET
operations, along with example:

1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

UNION Operation
UNION is used to combine the results of two or more SELECT statements. However
it will eliminate duplicate rows from its resultset. In case of union, number of
columns and datatype must be same in both the tables, on which UNION operation is
being applied.
Example of UNION

The First table,

ID Name

1 abhi

2 adam

The Second table,

ID Name

2 adam

3 Chester

Union SQL query will be,


SELECT * FROM First
UNION
SELECT * FROM Second;

35
The resultset table will look like,

ID NAME

1 abhi

2 adam

3 Chester

UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
Example of Union All

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Union All query will be like,

SELECT * FROM First


UNION ALL
SELECT * FROM Second;
The resultset table will look like,

ID NAME

1 abhi

36
2 adam

2 adam

3 Chester

INTERSECT
Intersect operation is used to combine two SELECT statements, but it only retuns
the records which are common from both SELECT statements. In case
of Intersect the number of columns and datatype must be same.

NOTE: MySQL does not support INTERSECT operator.


Example of Intersect

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Intersect query will be,

SELECT * FROM First


INTERSECT
SELECT * FROM Second;
The resultset table will look like

ID NAME

2 adam

37
MINUS
The Minus operation combines results of two SELECT statements and return only
those in the final result, which belongs to the first set of the result.
Example of Minus

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Minus query will be,

SELECT * FROM First


MINUS
SELECT * FROM Second;
The resultset table will look like,

ID NAME

1 abhi

38
JOIN OPERATIONS:
1. EQUI JOIN - Compare two or more tables with '=' operator.

Display the department details to all the employees

SELECT empno,dept.deptno,dname
FROM emp,dept
WHERE emp.deptno=dept.deptno;

List the details of the employees who are working in 'NEW YORK'
SELECT empno,ename,loc
FROM emp,dept

39
WHERE loc = 'NEW YORK' AND
emp.deptno=dept.deptno;

2. NON-EQUI JOIN - compares one or more tables with other than '=' operator.
SQL> select * from job_grades;
G LOWEST_SAL HIGHEST_SAL
- ---------- -----------
A 1000 2999
B 3000 5999
C 6000 9999
D 10000 14999
E 15000 24999
F 25000 40000

SELECT e.ename, e.sal, j.grade_level


FROM emp e, job_grades j
WHERE e.sal
BETWEEN j.lowest_sal AND j.highest_sal;

3. OUTER JOIN - The missing rows can be returned if an outer join operator is
used in the join condition.

SELECT e.ename, e.deptno, d.dname


FROM emp e, dept d
WHERE e.deptno(+) = d.deptno ;

a) LEFT OUTER JOIN - This query retrieves all rows in the EMP table,
which is the left table even if there is no match in the DEPT table.

SELECT e.ename, e.deptno, d.dname


FROM emp e
LEFT OUTER JOIN dept d
ON (e.deptno = d.deptno) ;

b) RIGHT OUTER JOIN - This query retrieves all rows in the DEPT
table, which is the right table even if there is no match in the EMP
table.

40
SELECT e.ename, e.deptno, d.dname
FROM emp e
RIGHT OUTER JOIN dept d
ON (e.deptno = d.deptno) ;

c) FULL OUTER JOIN - This query retrieves all rows in the EMP table, even
if there is no match in the DEPT table. It also retrieves all rows in the
DEPT table, even if there is no match in the EMP table.

SELECT e.ename, e.deptno, d.dname


FROM emp e
FULL OUTER JOIN dept d
ON (e.deptno = d.deptno) ;

4. SELF JOIN - to join a table to itself.


To find the name of each employee’s manager

SELECT w.ename||' works for '||m.ename


FROM emp w, emp m
WHERE w.mgr = m.empno ;

SUBQUERIES:
Definition:
often situation arises, so that, to get a output for a question two / more
queries may be needed.

- A subquery must be enclosed in paranthesis


- place the subquery on the right side of the comparison condition
- Two classes of comparison conditions are used in subqueries
1. Single row operator 2. Multiple-row operators

Which employees have salaries greater than ADAMS’s salary?


selectsal from emp where enamelike'ADAMS';
select * from emp where sal>1100
one to find what ADAM earns, and a second query to find
who earns more than that amount.
You can solve this problem by combining the two queries,
placing one query inside the other query.

41
SELECT ename FROM emp WHERE sal> (SELECT sal FROM emp
WHERE name = ’ADAM’);
1. Single row operator
-------------------------------
Use comparison operators

Display the employees whose job is the same as that of empno 7566.

SELECT ename, job FROM emp WHERE job = (SELECT job FROM emp
WHERE empno = 7566);

Display the employees whose job is the same as that of empno 7566 and whose sal
is
greater than that of empno 7698.

SELECT ename, job,sal FROM emp WHERE job = (SELECT job FROM emp
WHERE empno = 7566) AND sal> (SELECT sal FROM emp WHERE empno = 7698);

Using group functions in a subquery


===============================

SELECT ename, job, sal FROM emp WHERE sal = (SELECT MIN(sal) FROM emp);

Find the error in this statement ?

SELECT empno, ename FROM emp WHERE sal = (SELECT MIN(sal) FROM emp
GROUP BY deptno);

2. Multiple-row operators
----------------------------------
use multiple-row comparison operators

Operator Meaning

IN Equal to any member in the list

42
ANY Compare value to each value returned by the subquery
ALL Compare value to every value returned by the subquery

SELECT empno, ename FROM emp WHERE sal IN (SELECT MIN(sal) FROM emp
GROUP BY deptno);

SELECT ename, job FROM emp WHERE job IN (SELECT job FROM emp
WHERE mgr = 7566);

Using the ANY operator


====================
Displays employees who are not CLERK and whose salary is less
than that of any CLERK.

SELECT empno, ename, job, sal FROM emp WHERE sal< ANY (SELECT sal
FROM emp WHERE job = 'CLERK') AND job <> 'CLERK';

<ANY means less than the maximum.


>ANY means more than the minimum.
=ANY is equivalent toIN.
<ALL means less than the maximum.
>ALL means more than the minimum.

Database Updates

SQL is a complete data manipulation language that can be used for modifying the
data in the database as well as querying the database. The commands for modifying
the database are not as complex as the SELECT statement. In this section, we
describe the three SQL statements that are available to modify the contents of the
tables in the database:

n INSERT – adds new rows of data to a table;


n UPDATE – modifies existing data in a table;
n DELETE – removes rows of data from a table.

43
44
45

You might also like