Unit 4 SQL
Unit 4 SQL
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.
3
START AUDIT
STOP AUDIT
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;
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:
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:
Example:
Consider the CUSTOMERS table having the following records:
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:
Example:
Consider the CUSTOMERS table having the following records:
9
First, let us see how the following SELECT query returns duplicate salary records:
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.
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.
derived field). In general, to use a calculated field you specify an SQL expression in the
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 −
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.
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 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:
Statement Description
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:
17
Selecting computed values:
Example:
Following is an example which would fetch ID, Name and Salary fields from the
CUSTOMERS table where salary is greater than 2000:
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.
19
Now, following is the usage of IS NULL operator:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+
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.
20
Example:
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:
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:
This would produce the following result: This would produce the following result:
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.
COUNT ( ) Function:
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:
Example:
o SELECT MAX (Phy) FROM EXAMINATION;
o The above query returns 100
MIN ( ) Function:
24
GROUP BY :
HAVING
• 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
Example
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.
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.
Subqueries are most frequently used with the SELECT statement. The basic syntax is
as follows:
26
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Example:
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
+----+----------+-----+---------+----------+
| 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
FROM Staff
List the properties that are handled by staff who work in the branch at ‘163 Main St’.
FROM PropertyForRent
FROM Staff
FROM Branch
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.
Find all staff whose salary is larger than the salary of at least one member of staff at
branch B003.
FROM Staff
FROM Staff
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.
FROM Staff
FROM Staff
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
use a join operation. The SQL join operation combines information from 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;
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
ID Name
1 abhi
2 adam
ID Name
2 adam
3 Chester
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
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
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.
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
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
ID NAME
1 abhi
2 adam
ID NAME
2 adam
3 Chester
ID NAME
1 abhi
38
JOIN OPERATIONS:
1. EQUI JOIN - Compare two or more tables with '=' operator.
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
3. OUTER JOIN - The missing rows can be returned if an outer join operator is
used in the join condition.
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.
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.
SUBQUERIES:
Definition:
often situation arises, so that, to get a output for a question two / more
queries may be needed.
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);
SELECT ename, job, sal FROM emp WHERE sal = (SELECT MIN(sal) FROM emp);
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
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);
SELECT empno, ename, job, sal FROM emp WHERE sal< ANY (SELECT sal
FROM emp WHERE job = 'CLERK') AND job <> 'CLERK';
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:
43
44
45