0% found this document useful (0 votes)
107 views30 pages

SQL Unit 2

Uploaded by

Nikilesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
107 views30 pages

SQL Unit 2

Uploaded by

Nikilesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

SQL Commands

DCL Commands

What is DCL?
DCL (Data Control Language) includes commands like GRANT and REVOKE,
which are useful to give "rights & permissions." Other permission controls
parameters of the database system.

Examples of DCL commands:


Commands that come under DCL:

 Grant
 Revoke
 Grant:
This command is use to give user access privileges to a database.

Syntax:

GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

For example:

GRANT SELECT ON Users TO'Tom'@'localhost;

 Revoke:
It is useful to get back permissions from the user.

Syntax:

REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}

For example:

REVOKE SELECT, UPDATE ON student FROM BCA, MCA;

What is TCL?
Transaction control language or TCL commands deal with the transaction within
the database.

 Commit
This command is used to save all the transactions to the database.

Syntax:

commit;

For example:

DELETE FROM Students WHERE RollNo =25;


COMMIT;

 Rollback
Rollback command allows us to undo transactions that have not already been
saved to the database.

Syntax:

ROLLBACK;
ROLLBACT TO SAVEPOINT savepoint_name;

Example:

DELETE FROM Students WHERE RollNo =25;


ROLLBACK;

 SAVEPOINT
This command helps us to set a savepoint within a transaction. c. SAVEPOINT: It
is used to roll the transaction back to a certain point without rolling back the entire
transaction.

Syntax:

1. SAVEPOINT SAVEPOINT_NAME;

Syntax:

SAVEPOINT SAVEPOINT_NAME;

Example:

SAVEPOINT s1;

examples
UPDATE employees

SET salary = 7000

WHERE last_name = 'Banda';

SAVEPOINT banda_sal;

UPDATE employees
SET salary = 12000

WHERE last_name = 'Greene';

SAVEPOINT greene_sal;

SELECT SUM(salary) FROM employees;

ROLLBACK TO SAVEPOINT banda_sal;

UPDATE employees

SET salary = 11000

WHERE last_name = 'Greene';

COMMIT;

Data Manipulation Language (DML)

statements or commands are used for managing/manipulating data within


tables.

Some commands of DML are:

SELECT – retrieve data from the a database(also known as DQL)


INSERT – insert data into a table
UPDATE – updates existing data within a table
DELETE – deletes all records from a table, the space for the records remain

Insert:
The insert statement is used to add new row to a table.

INSERT INTO <table name> VALUES (<value 1>, ... <value n>);
Example:

INSERT INTO STUDENT VALUES (1001,‘Ram’);

The inserted values must match the table structure exactly in the number of
attributes and the data type of each attribute.

 Character type values are always enclosed in single quotes.


 number values are never in quotes.
 date values are often (but not always) in the format „yyyy-mm-dd‟ (for
example, „2006-11- 30‟).

UPDATE:
The update statement is used to change values that are already in a table.

UPDATE <table name> SET <attribute> = <expression> WHERE


<condition>;

Example:

UPDATE STUDENT SET Name = ‘Amar’ WHERE StudID=1001;

The update expression can be a constant, any computed value, or even the
result of a SELECT statement that returns a single row and a single column.

DELETE:
The delete statement deletes row(s) from a table.

DELETE FROM <table name> WHERE <condition>;


Example:

DELETE FROM STUDENT WHERE StudID=1001;

If the WHERE clause is omitted, then every row of the table is deleted that
matches with the specified condition.

SELECT:
The SELECT statement is used to form queries for extracting information out
of the database.

SELECT <attribute>, ….., <attribute n> FROM <table name>;

Example:

SELECT StudID, Name FROM STUDENT;

DML Commands Examples

 create table command to create the customer table structure


 insert command to insert records into the customer table.
 select command to view the records from the customer table.
 update command to modify the records from the customer table.
The cname ‘sasi’ is changed to ‘anusha’.
 delete command to delete the records from the customer table.
The record with cno ‘c1004’ is deleted.
 select command to view the modified and deleted records from the customer table.

Advanced SQL Queries

SQL Technique– Limiting Data


 Limit
we can use the LIMIT clause to limit the display of the record.
The above SQL command helps us show the first 5 rows of the table.

 OFFSET
To select only the fourth and fifth rows we can use the OFFSET clause. The OFFSET clause
will skip the specified number of rows.

SQL Technique – Sorting Data


Sorting data helps us put our data into perspective. We can perform the sorting process by
using the keyword – ORDER BY.

 ORDER BY
The keyword can be used to sort the data into ascending or descending order. The ORDER BY
keyword sorts the data in ascending order by default.

we sort the data according to the column Total_amt_spend in ascending order:


SQL Technique – Filtering Patterns
In the earlier sections, we learned how to filter the data based on one or multiple conditions.
Here, we will learn to filter the columns that match a specified pattern. To move forward with
this, we will first understand the LIKE operator and wildcard characters.

 LIKE operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

 Wildcard Characters
The Wildcard Character is used to substitute one or more characters in a string. These are used
along with the LIKE operator. The two most common wildcard characters are:

o % – It represents 0 or more number of characters


o _ – It represents a single character

In our dummy retail dataset, let‟s say we want all the localities that end with “Nagar”. Take a
moment to understand the problem statement and think about how we can solve this.
Let‟s try to break down the problem. We require all the localities that end with “Nagar” and can
have any number of characters before this particular string. Therefore, we can make use of the
“%” wildcard before “Nagar”:

Awesome, we have 6 localities ending with this name. Notice that we are using the LIKE
operator to perform pattern matching.

Next, we will try to solve another pattern-based problem. We want the names of the consumers
whose second character has “a” in their respective names. Again, I would suggest you to take a
moment to understand the problem and think of a logic to solve it.

Let‟s breakdown the problem. Here, the second character needs to be “a”. The first character
can be anything so we substitute this letter with the wildcard “_”. After the second character,
there can be any number of characters so we substitute those characters with the wildcard “%”.
The final pattern matching will look like this:
We have 6 people satisfying this bizarre condition!

SQL Technique – Groupings, Rolling up Data and Filtering


in Groups
We have finally arrived at one of the most powerful analysis tools in SQL – Grouping of data
which is performed using the GROUP BY statement. The most useful application of this
statement is to find the distribution of categorical variables. This is done by using the GROUP
BY statement along with aggregation functions like – COUNT, SUM, AVG, etc.

Let‟s try to understand this better by taking up a problem statement. The retail store wants to
find the Number of Customers corresponding to the industries they belong to:

We notice that the count of customers belonging to the various industries is more or less the
same. So, let us move forward and find the sum of spendings by customers grouped by the
industry they belong to:
We can observe that the maximum amount of money spent is by the customers belonging to
the Manufacturing industry. This seems a bit easy, right? Let us take a step ahead and make it
more complicated.

Now, the retailer wants to find the industries whose total_sum is greater than 2500. To solve
this problem, we will again group by the data according to the industry and then use the
HAVING clause.

 HAVING
The HAVING clause is just like the WHERE clause but only for filtering the grouped by data.
Remember, it will always come after the GROUP BY statement.

We have only 3 categories that satisfy the conditions – Aviation, Defense,


and Manufacturing. But to make it more clearer, I will also add the ORDER BY keyword to
make it more intuitive:
Aggregate functions
Aggregate functions perform a variety of actions such as counting all the rows in a table, averaging
a column's data, and summing numeric data.

Aggregates can also search a table to find the highest "MAX" or lowest "MIN" values in a column.

Some of the commonly used aggregate functions are as below -


SUM( [ALL | DISTINCT] expression )

AVG( [ALL | DISTINCT] expression )

COUNT( [ALL | DISTINCT] expression )

COUNT(*)

MAX(expression)

MIN(expression)

DISTINCT keyword with the input parameter, group by function considers only the unique value of
the column for aggregation.

By specifying ALL keyword with the input parameter, group by function considers all the values of
the column for aggregation, including nulls and duplicates.

The expression listed in the syntax can be a constant, a function, or any combination of column
names

There are two rules that you must understand and follow when using aggregates:
 Aggregate functions can be used in both the SELECT and HAVING clauses
 Aggregate functions cannot be used in a WHERE clause. Its violation will produce
the Oracle ORA-00934 group function is not allowed here error message.
The below SELECT query counts the number of employees in the organization.

SELECT COUNT(*) EMPCount FROM employees;

EMPCOUNT
-----
24
The below SELECT query returns the average of the salaries of employees in the
organization.
SELECT AVG(Salary) average_sal FROM employees;

AVERAGE_SAL
-----------
15694
The below SELECT query returns the sum of the salaries of employees in the
organization.
SELECT SUM(Salary) total_sal FROM employees;

TOTAL_SAL
---------
1250000
The below SELECT query returns the oldest and latest hired dates of employees in the
organization.
SELECT MIN (hire_date) oldest, MAX (hire_date) latest
FROM employees;

OLDEST LATEST
--------- -----------
16-JAN-83 01-JUL-2020

GROUP BY

The GROUP BY clause enables you to use aggregate functions to answer more complex
managerial questions such as:
What is the average salary of employees in each department?

How many employees work in each department?

How many employees are working on a particular project?

 Group by function establishes data groups based on columns and aggregates the
information within a group only.

 The grouping criterion is defined by the columns specified in GROUP BY clause.

 Data is first organized in the groups and then WHERE clause restricts the rows in each
group.

Examples:

Below query lists the count of employees working in each department.


SELECT DEPARTMENT_ID, COUNT (*)EMPCOUNT
FROM employees
GROUP BY DEPARTMENT_ID;

DEPARTMENT_ID EMPCOUNT
------------------------------------------------
D1 8
D2 7
D3 5
D4 4

query to find sum of salaries for each department

SELECT DEPARTMENT_ID, SUM (SALARY) DEPTSAL FROM employees


GROUP BY DEPARTMENT_ID;

DEPARTMENT_ID DEPTSAL
------------------------------------------------
D1 350000
D2 300000
D3 310000
D4 290000

query to find the maximum salary for each department

SELECT DEPARTMENT_ID, MAX(SALARY) MAXSAL FROM employees


GROUP BY DEPARTMENT_ID;

DEPARTMENT_ID MAXSAL
------------------------------------------------
D1 75000
D2 65000
D3 63500
D4 45000

Group By Clause
The GROUP BY Clause is utilized in SQL with the SELECT statement to
organize similar data into groups.
It combines the multiple records in single or more columns using aggregate
functions such as min(),max(),avg(), count(), and sum() to combine into single or
multiple columns.
It uses the split-apply-combine strategy for data analysis.

 In the split phase, It divides the groups with its values.

 In the apply phase, It applies the aggregate function and generates a


single value.

 In the combiner phase, It combines the groups with single values into a
single value.
e

Points to Remember:

 GROUP BY Clause is utilized with the SELECT statement.

 GROUP BY aggregates the results on the basis of selected column:


COUNT, MAX, MIN, SUM, AVG, etc.

 GROUP BY returns only one result per group of data.

 GROUP BY Clause always follows the WHERE Clause.

 GROUP BY Clause always precedes the ORDER BY Clause


In above example, Table is grouped based on the DeptID column and Salary is
aggregated department-wise.

Having Clause
HAVING Clause utilized in SQL as a conditional Clause with GROUP BY
Clause.

 HAVING Clause always utilized in combination with GROUP BY Clause.

 HAVING Clause restricts the data on the group records rather than
individual records.

 WHERE and HAVING can be used in a single query.


In above example, Table is grouped based on DeptID column and these grouped
rows filtered using HAVING Clause with condition AVG(Salary) > 3000.

GROUP BY and ORDER BY

ORDER BY returns sorted items in ascending and descending order while


GROUP BY returns unique items with the aggregate resultant column. In the
following example, you can see the ORDER BY or sorted salary table.

Example:
SELECT FROM emp ORDER BY salary ;
Example:

To display the avg salary of the department from high to low.

SELECT DeptID,AVG(SALARY) FROM Employee GROUP BY DeptID ORDER BY


AVG(Salary) DESC;

DeptID AVG(Salary)

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

3 4250.00

2 4000.00

1 3000.00

SQL JOINS
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set
of data. It is used for combining column from two or more tables by using values common to
both tables.
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Return all records from the left table, and the
matched records from the right table
 RIGHT (OUTER) JOIN: Return all records from the right table, and the
matched records from the left table
 FULL (OUTER) JOIN: Return all records when there is a match in either left
or right table
INNER Join or EQUI Join
This is a simple JOIN in which the result is based on matched data as per the equality
condition specified in the SQL query.
Inner Join Syntax is,
SELECT column-name-list FROM
table-name1 INNER JOIN table-name2
WHERE table-name1.column-name = table-name2.column-name;

Example of INNER JOIN

Consider a class table,

ID NAME

1 abhi
2 adam

3 alex

4 anu

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Inner JOIN query will be,

SELECT * from class INNER JOIN class_info where class.id =


class_info.id;
The resultset table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI
OUTER JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

1. Left Outer Join


2. Right Outer Join
3. Full Outer Join

LEFT Outer Join


The left outer join returns a resultset table with the matched data from the two tables and then
the remaining rows of the left table and null from the right table's columns.
Syntax for Left Outer Join is,

SELECT column-name-list FROM


table-name1 LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
To specify a condition, we use the ON keyword with Outer Join.
Left outer Join Syntax for Oracle is,

SELECT column-name-list FROM


table-name1, table-name2 on table-name1.column-name = table-
name2.column-name(+);

Example of Left Outer Join

Here is the class table,

ID NAME
1 abhi

2 adam

3 alex

4 anu

5 ashish

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Left Outer Join query will be,

SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id =


class_info.id);
The resultset table will look like,

ID NAME ID Address
1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null

RIGHT Outer Join


The right outer join returns a resultset table with the matched data from the two tables being
joined, then the remaining rows of the right table and null for the remaining left table's columns.
Syntax for Right Outer Join is,
SELECT column-name-list FROM
table-name1 RIGHT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
Right outer Join Syntax for Oracle is,

SELECT column-name-list FROM


table-name1, table-name2
ON table-name1.column-name(+) = table-name2.column-name;

Example

class table class_info table

ID NAME

1 abhi
ID Address

1 DELHI

2 adam
2 MUMBAI

3 alex
3 CHENNAI

4 anu
7 NOIDA

5 ashish
8 PANIPAT
Right Outer Join query will be,

SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id =


class_info.id);
The resultant table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

null null 7 NOIDA

null null 8 PANIPAT

Full Outer Join


The full outer join returns a resultset table with the matched data of two table then remaining
rows of both left table and then the right table.
Syntax of Full Outer Join is,
SELECT column-name-list FROM
table-name1 FULL OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;

Example

The class table, The class_info table,

ID Address

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu 7 NOIDA

5 ashish 8 PANIPAT

Full Outer Join query will be like,

SELECT * FROM class FULL OUTER JOIN class_info ON


(class.id = class_info.id);
The resultset table will look like,

ID NAME ID Address

1 abhi 1 DELHI
2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null

null null 7 NOIDA

null null 8 PANIPAT

You might also like