SQL Unit 2
SQL Unit 2
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.
Grant
Revoke
Grant:
This command is use to give user access privileges to a database.
Syntax:
For example:
Revoke:
It is useful to get back permissions from the user.
Syntax:
For example:
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:
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:
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
SAVEPOINT banda_sal;
UPDATE employees
SET salary = 12000
SAVEPOINT greene_sal;
UPDATE employees
COMMIT;
Insert:
The insert statement is used to add new row to a table.
INSERT INTO <table name> VALUES (<value 1>, ... <value n>);
Example:
The inserted values must match the table structure exactly in the number of
attributes and the data type of each attribute.
UPDATE:
The update statement is used to change values that are already in a table.
Example:
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.
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.
Example:
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.
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.
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:
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!
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.
Aggregates can also search a table to find the highest "MAX" or lowest "MIN" values in a column.
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.
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?
Group by function establishes data groups based on columns and aggregates the
information within a group only.
Data is first organized in the groups and then WHERE clause restricts the rows in each
group.
Examples:
DEPARTMENT_ID EMPCOUNT
------------------------------------------------
D1 8
D2 7
D3 5
D4 4
DEPARTMENT_ID DEPTSAL
------------------------------------------------
D1 350000
D2 300000
D3 310000
D4 290000
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 combiner phase, It combines the groups with single values into a
single value.
e
Points to Remember:
Having Clause
HAVING Clause utilized in SQL as a conditional Clause with GROUP BY
Clause.
HAVING Clause restricts the data on the group records rather than
individual records.
Example:
SELECT FROM emp ORDER BY salary ;
Example:
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;
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
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,
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
Example
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,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
Example
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
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI