Dandii Boru College: Level-Iii
Dandii Boru College: Level-Iii
DATABASE ADMINISTRATION
LEVEL-III
INFORMATION SHEET
Learning outcomes:
Page 1
SQL Overview
SQL is a language of database, it includes database creation, deletion, fetching rows and
modifying rows etc. SQL is an ANSI (American National Standards Institute) standard, but there
are many different versions of the SQL language.
What is SQL?
SQL stands for Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in relational database.
Why SQL?
Allow users to access data in relational database management systems.
Allow users to describe the data.
Allows users to define the data in database and manipulate that data.
Allow embedding within other languages using SQL modules, libraries & pre-compilers.
Allows users to create and drop databases and table.
Allow users to create view, stored procedure, functions in a database.
Allow users to set permissions on tables, procedures and views
SQL Commands:
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP.
Command Description
CREATE Creates a new table, a view of a table, or other object in database
ALTER Modifies an existing database object, such as a table.
DROP Deletes an entire table, a view of a table or other object in the database.
Command Description
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records
select Retrieves certain records from one or more tables
Page 2
DCL - Data Control Language:
Command Description
GRANT Gives a privilege to user
REVOKE Takes back privileges granted from user
What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL and
for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.
A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model as introduced by E. F. Codd.
What is table?
The data in RDBMS is stored in database objects called tables. The table is a collection of
related data entries and it consists of columns and rows.
The following is the example of a CUSTOMERS table:
6 Komal 22 MP 4500
What is field?
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table
consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about every record
in the table.
What is record or row?
A record, also called a row of data, is each individual entry that exists in a table.
Page 3
For example, there are 7 records in the above CUSTOMERS table. Following is a single row of
data or record in the CUSTOMERS table:
ADDRESS
Ahmedabad
Delhi
Kota
Mumbai
Bhopal
MP
Indore
SQL Constraints:
Constraints are the rules enforced on data columns on table. These are used to limit the type of
data that can go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints could be column level or table level.
Column level constraints are applied only to one column, whereas table level constraints are
applied to the whole table.
Following are commonly used constraints available in SQL:
Page 4
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.
INDEX: Use to create and retrieve data from the database very quickly.
DEFAULT Constraint:
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO
statement does not provide a value for this column. Then by default this column would be set to
5000.00.
CREATE TABLE CUSTOMERS(ID INT NOT NULL, NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,ADDRESS CHAR (25) ,SALARY DECIMAL (18, 2) DEFAULT
5000.00,PRIMARY KEY (ID));
If CUSTOMERS table has already been created, then to add a DFAULT constraint to SALARY
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS alter column SALARY DECIMAL (18, 2) DEFAULT 5000.00;
Drop Default Constraint:
To drop a DEFAULT constraint, use the following SQL:
ALTER TABLE CUSTOMERS ALTER COLUMN SALARY DROP DEFAULT;
UNIQUE Constraint:
Page 5
The UNIQUE Constraint prevents two records from having identical values in a particular
column. In the CUSTOMERS table, for example, you might want to prevent two or more people
from having identical age.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns.
Here, AGE column is set to UNIQUE, so that you cannot have two records with same age:
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL,AGE INT NOT NULL UNIQUE, ADDRESS CHAR (25) ,SALARY DECIMAL (18,
2),PRIMARY KEY (ID);
If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS MODIFY AGE INT NOT NULL UNIQUE;
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS ADD UNIQUE(AGE, SALARY);
DROP a UNIQUE Constraint:
To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE CUSTOMERS DROP unique (age);
If you are using MySQL, then you can use the following syntax:
ALTER TABLE CUSTOMERS DROP INDEX myUniqueConstraint;
PRIMARY Key:
is a field in a table which uniquely identifies each row/record in a database table.
Page 6
column(s) must already have been declared to not contain NULL values (when the table was first
created).
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
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, NAME) );
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when
CUSTOMERS table already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERSADD PRIMARY KEY (ID, NAME);
The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign
Key in the second table.
If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
Page 7
condition evaluates to false, the record violates the constraint and isn’t entered into the table.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER
below 18 years:
CREATE TABLE CUSTOMERS(ID INT NOT NULL,NAME VARCHAR (20) NOT
NULL,AGE INT NOT NULL CHECK (AGE >= 18),ADDRESS CHAR (25) ,SALARY
DECIMAL (18, 2),PRIMARY KEY (ID));
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS MODIFY AGE INT NOT NULL CHECK (AGE >= 18 );
INDEX:
The INDEX is used to create and retrieve data from the database very quickly. Index can be
created by using single or group of columns in a table.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns:
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, you can create index on single or multiple columns using the following syntax:
CREATE INDEX index name ON table_name ( column1, column2.....);
To create an INDEX on AGE column, to optimize the search on customers for a particular age,
following is the SQL
syntax:
CREATE INDEX idx_age ON CUSTOMERS ( AGE );
DROP an INDEX Constraint:
To drop an INDEX constraint, use the following SQL:
ALTER TABLE CUSTOMERS DROP INDEX idx_age;
Data Integrity:
The following categories of the data integrity exist with each RDBMS:
Entity Integrity : There are no duplicate rows in a table. Primary key is considered as entity
integrity.
Domain Integrity: Enforces valid entries for a given column by restricting the type, the
format, or the range of values. Check constraint is considered as domain integrity.
Referential Integrity: Rows cannot be deleted which are used by other records. Foreign key
is considered as referential integrity
User-Defined Integrity: Enforces some specific business rules that do not fall into entity,
domain, or referential integrity.
SQL Syntax
SQL is followed by unique set of rules and guidelines called Syntax.
Page 8
All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE,
DELETE, ALTER, DROP, CREATE, USE and the entire statements end with a semi colon (;).
Note: Important point to be noted is that SQL is case insensitive, which means SELECT and
select have same meaning in SQL statements.
SQL Data Types
SQL data type is an attribute that specifies type of data of any object. Each column, variable
and expression has related data type in SQL.
You would use these data types while creating your tables. You would choose a particular data
type for a table column based on your requirement.
SQL Server offers different categories of data types for your use:
Exact Numeric Data Types:
Bigint Tinyint Numeric
Int Bit Money
Smallint Decimal Small money
Page 9
> Checks if the value of left operand is greater than the (a > b) is not true
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (a < b) is true.
value of right operand, if yes then condition becomes
true.
>= if the value of left operand is greater than or equal to Checks (a >= b) is not
the value of right operand, if yes then condition true.
becomes true.
<= Checks if the value of left operand is less than or equal (a <= b) is true.
to the value of right operand, if yes then condition
becomes true
!< Checks if the value of left operand is not less than the (a !< b) is false.
value of right operand, if yes then condition becomes
true.
!> Checks if the value of left operand is not greater than (a !> b) is true.
the value of right operand, if yes then condition
becomes true.
6 Komal 22 MP 4500.00
Page 10
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00
SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 2000;
Operator Description
BETWEEN The BETWEEN operator is used to search for values that are within a
set of values, given the minimum value and the maximum value.
Page 11
that have been specified.
LIKE The LIKE operator is used to compare a value to similar values using
wildcard operators. Percent sign and underscore(% and _)
NOT The NOT operator reverses the meaning of the logical operator with
which it is used.
Eg:
6 Komal 22 MP 4500.00
Page 12
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
SELECT * FROM CUSTOMERS WHERE AGE >= 25 OR SALARY >= 6500;
AGE
32
25
23
Page 13
25
27
22
24
Page 14
NOTE: Be careful before using this operation because by deleting an existing database would result
in loss of complete information stored in the database.
Make sure you have admin privilege before dropping any database. Once a database is dropped, you
can check it in the list of databases as follows:
use testDB;
Database
information_schema
AMROOD
TUTORIALSPOINT
mysql
Orig
Test
Now, if you want to work with AMROOD database, then you can execute the following SQL
command and start working with AMROOD database:
USE AMROOD;
Page 15
CREATE TABLE is the keyword telling the database system what you want to do. In this case, you
want to create a new table.
Then in brackets comes the list defining each column in the table and what sort of data type it is. The
syntax becomes clearer with an example below.
A copy of an existing table can be created using a combination of the CREATE TABLE statement
and the SELECT statement.
Following is an example, which creates a CUSTOMERS table with ID as primary key and NOT
NULL are the constraints showing that these fields cannot be NULL while creating records in this
table:
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));
You can verify if your table has been created successfully by looking at the message displayed by
the SQL server, otherwise you can use DESC command as follows:
DESC CUSTOMERS;
Now, you have CUSTOMERS table available in your database which you can use to store required
information related to customers.
Page 16
Following statements would create six records in CUSTOMERS table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS
table where salary is greater than 2000:
Page 18
SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000;
ID NAME SALARY
4 Chaitali 6500.00
5 Hardik 8500.00
6 Komal 4500.00
7 Muffy 10000.00
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS
table for a customer with name Hardik.
Here, it is important to note that all the strings should be given inside single quotes ('') where as
numeric values should be given without any quote as in above example:
SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE NAME = 'Hardik';
This would produce the following result:
ID NAME SALARY
5 Hardik 8500.00
Returns record both the first condition and the second condition is true.
Syntax:
The basic syntax of AND operator with WHERE clause is as follows:
SELECT column1, column2, column FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
Example:
Page 19
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 AND age is less than 25 years:
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.
Returns record either the first condition or the second condition is true
Syntax:
The basic syntax of OR operator with WHERE clause is as follows:
SELECT column1, column2, columnN FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
Example:
Consider the CUSTOMERS table having the following records:
Page 20
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
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS
table where salary is greater than 2000 OR age is less tan 25 years:
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
If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do
not need to use WHERE clause and UPDATE query would be as follows:
UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;
Now, CUSTOMERS table would have the following records:
Page 22
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE
clause and DELETE query would be as follows:
DELETE FROM CUSTOMERS;
Now, CUSTOMERS table would not have any record.
Page 23
SELECT FROM table_name WHERE column LIKE '% AAAA %'
or
SELECT FROM table_name WHERE column LIKE ‘AAAA _'
or
SELECT FROM table_name WHERE column LIKE '_ AAAA’
or
SELECT FROM table_name WHERE column LIKE '_ AAAA _'
You can combine N number of conditions using AND or OR operators. Here, AAAA 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 '200%' Finds any values that start with 200
WHERE SALARY LIKE
'%200%' Finds any values that have 200 in any position
WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions
WHERE SALARY LIKE
'2_%_%' Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY LIKE '%2' Finds any values that end with 2
WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end with
and 3 WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2 and
end with 3 Let us take a real example, consider the CUSTOMERS table having the following
records:
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
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%';
Page 24
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+
Page 25
SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition]
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
First, let us see how the following SELECT query returns duplicate salary records:
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.
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
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:
+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
Page 26
| 8500.00 |
| 10000.00 |
+----------+
SQL Joins
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a
means for combining fields from two tables by using values common to each.
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AGE, AMOUNT
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
Page 27
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be used
to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to
join tables. However, the most common operator is the equal symbol.
SQL Join Types:
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: returns rows when there is a match in one of the tables.
INNER JOIN
The most frequently used and important of the joins is the INNER JOIN. They are also referred to
as an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate. The query compares each row of table1 with each row of
table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied,
column values for each matched pair of rows of A and B are combined into a result row.
Syntax:
The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2... FROM table1
INNER JOIN table2ON table1.common_filed = table2.common_field;
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
| OID | DATE | ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
Page 28
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using INNER JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+
LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right
table. This means that if the ON clause matches 0 (zero) records in right table, the join will still
return a row in the result, but with NULL in each column from right table.
This means that a left join returns all the values from the left table, plus matched values from the
right table or NULL in case of no matching join predicate.
Syntax:
The basic syntax of LEFT JOIN is as follows:
SELECT table1.column1, table2.column2... FROM table1 LEFT JOIN table2
ON table1.common_filed = table2.common_field;
Here given condition could be any given expression based on your requirement.
Now, let us join these two tables using LEFT JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+----+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
Page 29
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+----------+--------+---------------------+
RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the left
table. This means that if the ON clause matches 0 (zero) records in left table, the join will still return
a row in the result, but with NULL in each column from left table.
This means that a right join returns all the values from the right table, plus matched values from the
left table or NULL in case of no matching join predicate.
Syntax:
The basic syntax of RIGHT JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_filed = table2.common_field;
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using RIGHT JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
Page 30
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches on
either side.
Syntax:
The basic syntax of FULL JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_filed = table2.common_field;
Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
Page 31
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using FULL JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
If your Database does not support FULL JOIN like MySQL does not support FULL JOIN, then you
can use UNION ALL clause to combine two JOINS as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
SQL Unions Clause
The SQL UNION clause/operator is used to combine the results of two or more SELECT statements
Page 32
without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same number of
column expressions, the same data type, and have them in the same order, but they do not have to be
the same length.
Syntax:
The basic syntax of UNION is as follows:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
Page 33
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+------+----------+--------+---------------------+
The UNION ALL Clause:
The UNION ALL operator is used to combine the results of two SELECT statements including
duplicate rows.
The same rules that apply to UNION apply to the UNION ALL operator.
Syntax:
The basic syntax of UNION ALL is as follows:
SELECT column1 [, column2 ] FROM table1 [, table2 ]
[WHERE condition] UNION ALL SELECT column1 [, column2 ]
FROM table1 [, table2 ] [WHERE condition]
Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| 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 |
Page 34
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
SQL Alias Syntax
You can rename a table or a column temporarily by giving another name known as alias.
Page 35
The use of table aliases means to rename a table in a particular SQL statement. The renaming is a
temporary change and the actual table name does not change in the database.
The column aliases are used to rename a table's columns for the purpose of a particular SQL query.
Syntax:
The basic syntax of table alias is as follows:
SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];
The basic syntax of column alias is as follows:
SELECT column_name AS alias_name FROM table_name WHERE [condition];
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
Page 36
3 kaushik 23 3000
3 kaushik 23 1500
2 Khilan 25 1560
4 Chaitali 25 20603
CUSTOMER_ID CUSTOMER_NAME
1 Ramesh
2 Khilan
3 kaushik
4 Chaitali
5 Hardik
6 Komal
7 Muffy
SQL Indexes
Indexes are special lookup tables that the database search engine can use to speed up data retrieval.
Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index
in the back of a book.
For example, if you want to reference all pages in a book that discuss a certain topic, you first refer
to the index, which lists all topics alphabetically and are then referred to one or more specific page
numbers.
An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with
UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to
specify the table and which column or columns to index, and to indicate whether the index is in
ascending or descending order.
Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate
entries in the column or combination of columns on which there's an index.
The CREATE INDEX Command:
The basic syntax of CREATE INDEX is as follows:
CREATE INDEX index_name ON table_name;
Single-Column Indexes:
A single-column index is one that is created based on only one table column. The basic syntax is as
follows:
CREATE INDEX index_name
ON table_name (column_name);
When should indexes be avoided?
Page 37
Although indexes are intended to enhance a database's performance, there are times when they
should be avoided.
The following guidelines indicate when the use of an index should be reconsidered:
Indexes should not be used on small tables.
Tables that have frequent, large batch update or insert operations.
Indexes should not be used on columns that contain a high number of NULL values.
Columns that are frequently manipulated should not be indexed.
The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as
follows:
ALTER TABLE table_name alter COLUMN column_name datatype;
Page 38
Following is the example to truncate:
SQL > TRUNCATE TABLE CUSTOMERS;
Now, CUSTOMERS table is truncated and following would be the output from SELECT statement:
SQL> SELECT * FROM CUSTOMERS;
Empty set
Page 39
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Now, following is the example to create a view from CUSTOMERS table. This view would be used
to have customer name and age from CUSTOMERS table:
CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table. Following is
the example:
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result:
name Age
Ramesh 32
Khilan 25
kaushik 23
Chaitali 25
Hardik 27
Komal 22
Muffy 24
A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are
frequently used in databases because many applications require each row in a table to contain a
unique value, and sequences provide an easy way to generate them.
Using AUTO_INCREMENT column:
SQL server uses identity keyword to use afield as auto increment.
Identity keyword use two parameter (initial value and increment seed)
Example:
Try out the following example. This will create table and after that it will insert few rows in this
table where it is not required to give record ID because its auto-incremented by MySQL.
CREATE TABLE INSECT ( ID INT identity(1,1)PRIMARY KEY , name VARCHAR(30) NOT
NULL, date DATE NOT NULL, origin VARCHAR(30) NOT NULL);
Query OK, 0 rows affected (0.02 sec)
INSERT INTO INSECT (name,date,origin) VALUES ('housefly','2001-09-0','kitchen'),
INSERT INTO INSECT (name,date,origin) VALUES ('millipede','2001-09-0','driveway'),
INSERT INTO INSECT (name,date,origin) VALUES ('grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
SELECT * FROM INSECT ORDER BY id;
+----+-------------+------------+------------+
Page 40
| id | name | date | origin |
+----+-------------+------------+------------+
| 1 | housefly | 2001-09-10 | kitchen |
| 2 | millipede | 2001-09-10 | driveway |
| 3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)
* Multiplication Multiplies values on either side of the operator a * b will give 200
/ Division Divides left hand operand by right hand operand b / a will give 2
% Modulus Divides left hand operand by right hand operand and returns remainder b
% a will give 0
Page 41
mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30');
+---------------------------------------------------------+
| DATEDIFF('1997-12-31 23:59:59','1997-12-30') |
+---------------------------------------------------------+
|1|
+---------------------------------------------------------+
Page 42
Count
7
1 row in set (0.01 sec)
Similarly, if you want to count the number of records for Zara, then it can be done as follows:
SQL>SELECT COUNT(*) FROM employee_tbl
-> WHERE name="Zara";
Count
2
1 row in set (0.04 sec)
NOTE: All the SQL queries are case insensitive, so it does not make any difference if you give
ZARA or Zara in WHERE CONDITION.
SQL MAX Function
SQL MAX function is used to find out the record with maximum value among a record set.
To understand MAX function, consider an employee_tbl table, which is having the following
records:
SQL> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now suppose based on the above table you want to fetch maximum value of daily_typing_pages,
then you can do so simply using the following command:
SQL> SELECT MAX(daily_typing_pages)
-> FROM employee_tbl;
+-------------------------+
| MAX(daily_typing_pages) |
+-------------------------+
| 350 |
+-------------------------+
1 row in set (0.00 sec)
You can find all the records with maxmimum value for each name using GROUP BY clause as
Page 43
follows:
SQL> SELECT id, name, MAX(daily_typing_pages)
-> FROM employee_tbl GROUP BY name;
+------+------+-------------------------+
| id | name | MAX(daily_typing_pages) |
+------+------+-------------------------+
| 3 | Jack | 170 |
| 4 | Jill | 220 |
| 1 | John | 250 |
| 2 | Ram | 220 |
| 5 | Zara | 350 |
+------+------+-------------------------+
5 rows in set (0.00 sec)
You can use MIN Function along with MAX function to find out minimum value as well. Try out
the following
example:
SQL> SELECT MIN(daily_typing_pages) least, MAX(daily_typing_pages) max
-> FROM employee_tbl;
+-------+------+
| least | max |
+-------+------+
| 100 | 350 |
+-------+------+
1 row in set (0.01 sec)
SQL MIN Function
SQL MIN function is used to find out the record with minimum value among a record set.
To understand MIN function, consider an employee_tbl table, which is having the following
records:
SQL> SELECT * FROM employee_tbl;
Page 44
5 Zara 2007-06-06 300
MIN(daily_typing_pages)
100
id name MIN(daily_typing_pages)
3 jack 100
4 Jill 220
1 John 250
2 Ram 220
5 Zara 300
Page 45
least Max
100 350
AVG(daily_typing_pages)
230.0000
Page 46
records related to a single person and you will have average typed pages by every person.
SQL> SELECT name, AVG(daily_typing_pages)
-> FROM employee_tbl GROUP BY name;
name AVG(daily_typing_pages)
Jack 135.0000
Jill 220.0000
John 250.0000
Ram 220.0000
Zara 325.0000
Page 47
so by using the following command:
SQL> SELECT SUM(daily_typing_pages)
-> FROM employee_tbl;
SUM(daily_typing_pages)
1610
FIRST SECOND
Page 48
work_date, then
you can do it using the following command:
SQL> SELECT CONCAT(id, name, work_date)
-> FROM employee_tbl;
+-----------------------------+
| CONCAT(id, name, work_date) |
+-----------------------------+
| 1John2007-01-24 |
| 2Ram2007-05-27 |
| 3Jack2007-05-06 |
| 3Jack2007-04-06 |
| 4Jill2007-04-06 |
| 5Zara2007-06-06 |
| 5Zara2007-02-06 |
+-----------------------------+
7 rows in set (0.00 sec)
Page 49
LO3 write an SQL statement that use aggregation and filtering
SQL Group By
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
Example:
Consider the CUSTOMERS table having the following records:
6 Komal 22 MP 4500.00
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:
NAME SUM(SALARY)
Chaitali 6500.00
Page 50
Hardik 8500.00
kaushik 2000.00
Khilan 1500.00
Komal 4500.00
Muffy 10000.00
Ramesh 2000.00
Now, let us have following table where CUSTOMERS table has the following records with
duplicate names:
6 Komal 22 MP 4500.00
Now again, if you want to know the total amount of salary on each customer, then GROUP BY
query would be as follows:
SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME;
This would produce the following result:
+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
Page 51
| Ramesh | 3500.00 |
+---------+-------------+
Page 52
LO4 write and execute sql sub query
SQL Sub Queries
A Sub query or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.
A sub query is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.
Sub queries 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 sub queries must follow:
Sub queries must be enclosed within parentheses.
A sub query can have only one column in the SELECT clause, unless multiple columns are in the
main query for the sub query to compare its selected columns.
An ORDER BY cannot be used in a sub query, although the main query can use an ORDER BY.
The GROUPBY can be used to perform the same function as the ORDER BY in a sub query.
A sub query cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a sub query; however, the BETWEEN operator can
be used within the sub query.
Page 53
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 |
+----+----------+-----+---------+----------+
Page 54