Unit 3 SQL
Unit 3 SQL
Data Control Language - Transaction Control Language - Queries using Order by – Where -
Group by - Nested Queries. Joins – Views – Sequences - Indexes and Synonyms - Table
Handling.
1
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.
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.
2
SQL Language Statements
SQL commands are divided into 4 types. They are listed below.
3
ii. ALTER: SQL command can be used to add, modify, or drop a column from the existing table or to
rename a table. ALTER statement is used to
1. Add new columns to the existing table
2. Modify existing column size or data type
3. Remove columns from the table
4. Drop constraints
5. Rename a table.
1. To add new columns
Syntax:
ALTER TABLE table_name ADD new_column_name DATATYPE;
Example:
ALTER TABLE Employee ADD (Salary NUMBER);
EMP_ID(PK) EMP_NAME AGE PHONE_NUM Salary
2. Modify columns
Syntax:
ALTER TABLE table_name MODIFY existing_column new_datatype[new_size];
Example:
ALTER TABLE employee MODIFY emp_name char(25);
3. Remove columns from the table
ALTER TABLE existing_table_name DROP COLUMN name_of_the_column;
Example of removing column “Salary”
ALTER TABLE Employee DROP COLUMN Salary
EMP_ID(PK) EMP_NAME AGE PHONE_NUM
4. Drop constraints
ALTER TABLE existing_table_name
DROP constraint constraint _name;
Example of deleting primary key constraint
ALTER TABLE employees DROP PRIMARY KEY;
EMP_ID EMP_NAME AGE PHONE_NUM
This would remove primary key constraint on employee table.
5. Rename a table.
ALTER TABLE existing_table_name RENAME TO new_table_name;
Example of Renaming table:
ALTER TABLE employees RENAME TO emp;
This would rename the table EMPLOYEES to EMP.
4
iii. DROP: The SQL command that removes the entire table. DROP Table statement is used to remove
the table from the database. It means all the table definitions, constraints, permissions and data
stored in tables will be deleted.
Syntax:
DROP TABLE table_name;
Ex: DROP TABLE emp;
Note: Before table drop must remove the dependent constraints
iv. TRUNCATE: TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example: TRUNCATE TABLE stu;
i. INSERT INTO:
It creates new record(s) in a table. Basic syntax of Insert Into:
INSERT INTO table_name
VALUES (value1, value2, value3,…………………………….valueN);
Example:
INSERT INTO emp (emp_id, emp_name,age,phno)
values(1, „Ramu‟,25,123456789 );
We can insert records into specific columns as well. It is important to note that we can skip only those
columns which have been defined to support NULL values.
EMP_ID EMP_NAME AGE PHONE_NUM
1 Ramu 25 123456789
We can insert another row we are using insert into query again.
INSERT INTO emp (emp_id, emp_name,age,phno)
values(2, „Rani‟,18,456321789 );
EMP_ID EMP_NAME AGE PHONE_NUM
1 Ramu 25 123456789
2 Rani 18 456321789
5
ii. SELECT statement: SELECT statement is used to retrieve data from the tables based on
various conditions.
1. Select all columns and data.
2. Retrieve selective columns using column names
3. Retrieve selective data from the table based on conditions
Syntax:
SELECT column_name1, column_name2,………
FROM table_name
WHERE condition;
iv. DELETE statement: DELETE statement is used to delete all or selected rows from a table.
1) To delete all rows
Syntax:
DELETE FROM table_name ;
Example :
DELETE FROM stu5 ;
2) We can delete selected records using WHERE clause.
Syntax:
DELETE FROM table_name WHERE conditions;
Example:
DELETE FROM employee WHERE AGE= 25;
This will delete the records from EMPLOYEE table, which have DEPT_ID as 3.
7
✓ Pattern Match : tests whether a string matches a specified pattern.
✓ Null: tests a column for null (unknown) value.
Each type of these search conditions will be presented in this section.
Syntax:
SELECT * FROM table_name WHERE condition
Example1:
Select * from Employee2 where DeptName=‟Accounts‟;
Example2:
Select * from Employee2 where sal>5000;
Integrity Constraints
Constraints are a set of rules. It is used to maintain the quality of information. Integrity constraints
ensure that the data insertion, updating, and other processes have to be performed in such a way that data
integrity is not affected. Thus, integrity constraint is used to guard against accidental damage to the
database.
There are the following categories of data integrity exist with each RDBMS:
Domain Integrity Constraints
o Check
o Not null
Entity Integrity Constraints
o Unique
o Primary key
8
Referential Integrity Constraints
o Foreign Key
1. Domain integrity:
It applies valid entries for a given column by checking the type, the format, or the range of values.
Domain constraints can be defined as the definition of a valid set of values for an attribute.
The data type of domain includes string, character, integer, time, date, currency, etc. The value of the
attribute must be available in the corresponding domain.
1. Check Constraint: CHECK constraint is used to restrict the value of a column between ranges. It
performs check on the values, before storing them into the database. It‟s like condition checking before
saving data into a column.
Create a table for account using following conditions.
Account number must be start with ‘A’ and
Bank balance should be greater than 1000.
CREATE TABLE account (acno NUMBER CHECK (acno LIKE „A%‟),
bal NUMBER CHECK (bal>1000));
2. NOT NULL Constraint: NOT NULL constraint restricts a column from having a NULL value. Once
NOT NULL constraint is applied to a column, you cannot pass a null value to that column. It enforces a
column to contain a proper value.
CREATE TABLE student (Sno NUMBER NOT NULL,
Sname VARCHAR(20) NOT NULL);
For the above table student we must provide value for Sno and Sname.
2. Entity Integrity
It specifies that there should be no duplicate rows in a table.
The entity integrity constraint states that primary key value can't be null.
This is because the primary key value is used to identify individual rows in relation and if the
primary key has a null value, then we can't identify those rows.
A table can contain a null value other than the primary key field.
1. UNIQUE Constraint: UNIQUE constraint ensures that a field or column will only have unique
values. A UNIQUE constraint field will not have duplicate data, but It can contain NULL value.
CREATE TABLE customer (cno NUMBER UNIQUE,
name VARCHAR(20) NOT NULL);
2. Primary Key Constraint: Primary key constraint uniquely identifies each record in a database. A
Primary Key must contain unique value and it must not contain NULL value. Usually Primary Key is used
to index the data inside the table.
9
CREATE TABLE dept (dno NUMBER PRIMARY KEY,
dname VARCHAR(20) NOT NULL, loc VARCHAR(20));
SUM()
It calculates the sum of a set of values.
Syntax:
Select SUM(columnname) from tablename;
To find total salary given to all employees
SELECT SUM(sal) FROM employee2;
10
SUM(DISTINCT column):
Sum of all distinct Non-Null values.
SELECT SUM(DISTINCT sal) FROM employee2;
COUNT( )
It counts the number of rows.
COUNT(*):
Returns total number of records.
Compute total number of employees or rows in the table
SELECT COUNT(*) FROM employee2;
COUNT(sal): Return number of Non Null values over the column salary
SELECT COUNT(sal) FROM employee2;
AVG()
It calculates the average of set of values.
Avg(sal)
Compute average salary in the employee2 table
SELECT AVG(sal)FROM employee2;
11
MIN( )
It returns the lowest value from a set of non-null values.
Compute lowest salary in the employee2 table
SELECT MIN(sal)FROM emp;
MAX()
It returns the highest value (maximum) in a set of non-NULL values.
Compute highest salary in the employee2 table
SELECT MAX(sal)FROM employee2;
GROUP BY
Using group by clause related rows can be grouped together with respect to the attribute specified on the
group by clause.Group by clause is used to group rows that have the same values.
Compute total salary of each DeptName in the “employee2” table
SELECT DeptName, SUM(sal) FROM employee2 GROUP BY DeptName ORDER BY DeptName;
12
Compute highest salary in each department in the “emp” table
SELECT DeptName,MAX(sal) FROM employee2 GROUP BY DeptName;
Compute total, average, highest & lowest salaries in each department in the “emp”
table
SELECT DeptName,SUM(sal),AVG(sal),MAX(sal),MIN(sal)
FROM employee2 GROUP BY DeptName;
13
Having Clause
Where clause can‟t be used with aggregated functions hence the „having‟ clause was added to SQL.
SELECT aggregated_function(),column_name
FROM table_name
GROUP BY column_name
[HAVING condition ] ;
Find the department whose average salary is greater than 5000.
SELECT avg(sal),DeptName FROM employee2
GROUP BY DeptName HAVING avg(sal) > 5000;
Virtual View
View is a logical table created from existing table or tables/ other views. View contains no data of its own,
but is like a window through which data from tables can be viewed or changed.
Syntax;
CREATE OR REPLACE VIEW view_name AS
SELECT list_of_Column_names
FROM Existing_Table_Name
WHERE Conditions
GROUP BY columns
HAVING conditions
ORDER BY columns ;
OR REPLACE
With the “or replace” option, a view can be created even if one exists with this name already, thus replacing
the old view.
Example: Create view for employees2 table who are working in the department Arts.
CREATE OR REPLACE VIEW Artsgroup AS
SELECT EmpNo,EmpName, sal, DeptName
FROM employee2 WHERE DeptName=’Arts';
14
View created.
0.02 seconds
SELECT * FROM ArtsGroup;
Example: Create view for employees2 table who are working in the department Commerce.
CREATE OR REPLACE VIEW CommerceGroup AS
SELECT EmpNo,EmpName, sal, DeptName
FROM employee2 WHERE DeptName=’Commerce';
View created.
SELECT * FROM CommerceGroup;
Updatable views
DML Operations on Views:
View is a logical table hence, any DML operation applied on table (such as Select, Insert, Update or Delete)
can be applied on views.
1.INSERT
INSERT INTO CommerceGroup VALUES(111,'Advaith',15000,'Commerce');
15
1 row(s) inserted.
SELECT * FROM CommerceGroup;
2. UPDATE
UPDATE CommerceGroup SET Sal=20000 WHERE EmpNo=111;
SELECT * FROM CommerceGroup;
3. DELETE
DELETE FROM CommerceGroup WHERE EmpNo=111;
SELECT * FROM CommerceGroup;
16
Advantages of View
1. A view is never stored it is only displayed. It doesn‟t require memory space
2. View is automatically updated each time when it is used
3. It is used to restrict view of the table i.e we can hide some of columns or rows in the table.
4. We can view the data without storing the data into the database object.
5. View is a virtual table formed from one or more base tables or views. So we can Join two or more
tables and display it as a one table to user.
6. Limit the access of table so that nobody can insert the rows into the table.
Disadvantages of view
1. View is completely depends on the original table.
2. When the base table is removed view becomes inactive.
Synonym
It is used to create another name to the database objects. Content of original table is modified if we modify
records in table.
Syntax:
CREATE SYNONYM <new_name> FOR <Existing _ name>
Ex:
CREATE SYNONYM departments FOR dept;
Sequence
It is used to insert sequence numbers into database tables.
Syntax:
CREATE SEQUENCE name
INCREMENT BY Value
START WITH initial_value
MINVALUE Value
MAXVALUE Value
CYCLE / NOCYCLE;
Eg:
CREATE SEQUENCE sq2 INCREMENT BY 1 START WITH 18033029402001;
17
INSERT INTO Student
VALUES (sq2.NEXTVAL,'Maheswari',‟Addakula',‟Accounts‟);
INSERT INTO Student
VALUES (sq2.NEXTVAL,'Afreen',‟Addakula‟,‟Commerce‟);
INSERT INTO Student
VALUES (sq2.NEXTVAL,'Anuradha',‟Warne',‟Computers‟);
SELECT * FROM Student;
Creating Index
Index is used to retrieve data from the database very fast. They are used to speed up searches
Syntax:
CREATE INDEX index_name ON table_name(column1, column2,…….);
Example:
CREATE INDEX id1 ON employee2(EmpName,sal);
Removing an Index
Syntax: DROP INDEX index_name;
Example: DROP INDEX id1;
18
DCL: Data Control Language (DCL)
DCL used to control access to data stored in a database. It apply database security in a multiple user
database environment
1. GRANT
It gives user's access privileges to database. It is used to provide access or privileges on the database objects
to the users.
Syntax:
GRANT privilege_name ON Object_name TO username;
Example: Before using DCL commands we need to learn how to create users.
Syntax for creating user:
CREATE USER user_name IDENTIFIED BY password;
Example:
CREATE USER niveditha IDENTIFIED BY ndc;
To grant connection to user
GRANT CONNECT TO niveditha;
To grant connection, all resources and DBA to user
GRANT CONNECT,RESOURCE, DBA TO niveditha;
To grant DML operations like SELECT, UPDATE operations on employee2 table to user
GRANT SELECT,UPDATE ON employee2 TO niveditha;
2. REVOKE
It is used to remove the user accessibility to database object. It is used to take back permissions from any
user.
Syntax:
REVOKE privilege_name ON Object_name FROM username;
Remove privileges from user
To cancel DML operations like SELECT, UPDATE operations on employee2 table from user
REVOKE SELECT,UPDATE ON employee2 FROM niveditha;
To cancel connection permission from user
REVOKE CONNECT FROM niveditha;
To cancel connection, Resources and DBA permissions from user
REVOKE CONNECT,RESOURCE, DBA FROM niveditha;
19
TCL (Transaction Control Language)
TCL statements are used to manage the changes made by DML statements. It allows statements to be
grouped together into logical transactions.
1. SAVEPOINT
SAVEPOINT command is used to temporarily save a transaction so that you can ROLLBACK to
that point whenever required. It Identify a point in a transaction to which you can later roll back.
Syntax: SAVEPOINT savepoint_name;
Example : SAVEPOINT sp1;
2. ROLLBACK
Restore database to original since the last COMMIT. It restores the database to last committed or
savepoint state To restore the database to last committed state use following command.
ROLLBACK;
It restores the database to last savepoint state.
Syntax: ROLLBACK TO savepoint_name;
Example: ROLLBACK TO sp1;
3. COMMIT
Commit mark the any DML changes as permanent. It permanently save any changes into database.
When we use any DML command like insert, update or delete the changes made by these commands are not
permanent until the current session is closed. The changes made by these commands can be rolled back. To
avoid that, we use the COMMIT to mark the changes as permanent.
COMMIT;
SUB QUERIES
A Subquery is a query within another SQL query and embedded within the WHERE clause.
Important Rule:
A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING
clause.
You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.
A subquery is a query within another query. The outer query is known as the main query, and the
inner query is known as a subquery.
Subqueries are on the right side of the comparison operator.
A subquery is enclosed in parentheses.
20
In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to
perform the same function as ORDER BY command.
Syntax:
SELECT column_name
FROM table_name
WHERE column_name OPERATOR ( SELECT column_name
FROM table_name
WHERE condition );
SELECT * FROM employee2;
Eg: find employee details whose salary is greater than laxmi’s salary
SELECT * FROM employee2
WHERE sal > (SELECT sal FROM employee2 WHERE EmpNo = 107);
21
SELECT * FROM employee2
WHERE sal > ALL (SELECT sal FROM employee
WHERE sal BETWEEN 5000 AND 15000);
Find second highest salary
SELECT MAX(sal) FROM employee2 WHERE sal < (SELECT MAX(sal) FROM employee2);
Inner Joins:
An inner join between two or more is the Cartesian product that satisfies the join condition in the WHERE
clause. Inner joins use a comparison operator like = (Equi Join) or <, <=, >, >=, < > (Non Equi Join) to
match rows from two tables based on the values in common columns from each table.
SELECT * FROM employee2, department
WHERE employee2.DeptName=department.DeptName;
22
Outer Joins:
An outer join is used to retrieve the rows with an unmatched value in the relevant column. There are TWO
types of outer joins.
1. Left Outer Join
2. Right Outer Join
Left Outer Join retrieves all rows from first (left) table and only matching rows from second (right) table.
SELECT * FROM employee2 LEFT JOIN department
ON employee2.DeptName=department.DeptName;
Right Outer Join retrieves all rows (Matching and Unlatching rows) from Second (Right) table and
only matching rows from First (Left) table.
SELECT * FROM employee2 RIGHT JOIN department
ON employee2.DeptName=department.DeptName;
23
Full Outer Join retrieves all rows (Matching and Unlatching rows) from first (left) and Second
(right) tables.
SELECT * FROM employee2 FULL JOIN department
ON employee2.DeptName=department.DeptName;
24