Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

UNIT 3

SQL (Structured Query Language)

Meaning – SQL commands - Data Definition Language - Data Manipulation Language -

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.

 SQL depends on tuple relational calculus and relational algebra.

SQL General Data Types


Each column in a database table is required to have a name and a data type. SQL developers have to decide
what types of data will be stored inside each and every table column when creating a SQL table. The data
type is a label and a guideline for SQL to understand what type of data is expected inside of each column,
and it also identifies how SQL will interact with the stored data. The following table lists the general data
types in SQL:

Data type Description


Fixed length character string, with user-
CHAR(n)
specified length n.
Variable length character strings, with user-
VARCHAR(n)
specified maximum length n.
NUMBER Integer numerical (no decimal). Precision 10
Stores year, month, and day values.
DATE Syntax: DD/Mon/YY
Ex: 28/Aug/2016
Approximate numerical, mantissa precision
FLOAT
16
INTEGER Integer numerical (no decimal). Precision 10

2
SQL Language Statements
 SQL commands are divided into 4 types. They are listed below.

1. DDL (Data Definition Language)


DDL : Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
 CREATE – It is used to create database objects in the database
 ALTER – It alters the structure of the database
 DROP – It is used delete objects from the database
 TRUNCATE – It is used remove all records from a table, including all spaces allocated for the
records are removed
i. CREATE: SQL command that adds a new table or View to an SQL database. Tables are a basic unit
of organization and storage of data in SQL.
CREATE TABLE tablename ( column1 datatype constraint,
Column2 datatype constraint, …………………
…………………………………………………………………
…………………………
PRIMARY KEY (column_name or names),
FOREIGN KEY(column_name),
REFERENCES Tablename (column_name) );
Example
Create employee table with Emp_ID, Ename, AGE, phno.
CREATE TABLE employee(Emp_ID number, EName Varchar2(20) NOT NULL,
AGE NUMBER NOT NULL, PHONE_NUM NUMBER ,
PRIMARY KEY(Emp_ID));
EMP_ID(PK) EMP_NAME AGE PHONE_NUM

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;

2. DML (Data Manipulation Language)


DML is used to manipulate records in the table. The following are DML Commands
1. INSERT – To add new records into table
2. UPDATE – For correction or modification of any records in tables.
3. DELETE – To remove records from table
4. SELECT - To retrieve records from table

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;

1. Select all columns and data.


To retrieve data of all the columns, use * like shown below:
 SELECT * FROM Employee
EMP_ID EMP_NAME AGE PHONE_NUM
1 Ramu 25 123456789
2 Rani 18 456321789
2. Retrieve selective columns using column names
We can select some of the columns from the table by providing the column names in the SELECT
query.
 SELECT EMP_ID, AGE FROM Employee;
EMP_ID AGE
1 25
2 18
3. Retrieve selective data.
To retrieve selected rows from the table use “WHERE” Clause.
Syntax:
 SELECT * FROM table_name WHERE condition;
Example :
 SELECT * FROM Employee WHERE EMP_ID=1;
EMP_ID EMP_NAME AGE PHONE_NUM
1 Ramu 25 123456789

iii. Update statement


This is useful for any correction or modification of any data in tables. We can update selected or all rows of
a table.
1. To Update all rows
2. To update selected rows use WHERE clause.
6
1) To Update all rows
Syntax:
 UPDATE table_name
SET col1= val1, col2 = val2, ….…. coln = valn ;
Example:
 UPDATE stu5 SET total=DBMS+Eng+Tel, average=total/3;
2) To update selected rows use WHERE clause.
Syntax:
 UPDATE table_name
SET col1= val1, col2 = val2, ….…. coln = valn
WHERE condition ;
Example:
 UPDATE stu5 SET grade = ‘First’
WHERE average > = 60 AND average < 70;

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.

Row Selection (WHERE clause) or WHERE clause


SELECT statements, we retrieve all data or rows in specified columns from a table. To select only some
rows or to specify a selection criterion, we use WHERE clause. The WHERE clause filters rows from the
FROM clause tables. Omitting the WHERE clause specifies that all rows are used.
There are five basic search conditions that can be used in a query
✓ Comparison: compares the value of an expression to the value of another expression
✓ Range: tests whether the value of an expression falls within a specified range of values.
✓ Set membership: tests whether a value matches any value in a set of values.

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));

3. Referential integrity: Foreign Key Constraint


A referential integrity constraint is specified between two or more tables. In the Referential integrity
constraints, if a foreign key in Table1 refers to the Primary Key of Table2, then every value of the Foreign
Key in Table1 must be null or be available in Table2.
 CREATE TABLE emp (eno NUMBER PRIMARY KEY,
ename VARCHAR(20) NOT NULL,doj DATE, sal NUMBER
dno NUMBER, FOREIGN KEY(dno) REFERENCES dept(dno));

Working with Aggregate Functions


It allows you perform calculation on a set of values and return a single value. In database management an
aggregate function is a function where the values of multiple rows are grouped together as input on certain
criteria to form a single value of more significant meaning.
 sum( ) returns the summation of all non-NULL values a set.
 count( ) returns the number of rows in a group, including rows with NULL values.
 avg( ) calculates the average of non-NULL values in a set.
 min( ) returns the lowest value (minimum) in a set of non-NULL values.
 max( ) returns the highest value (maximum) in a set of non-NULL values.
Now let us understand each Aggregate function with a example:
Example : SELECT * FROM employee2;

 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;

 Compute average salary of each department in the “employee2” table


 SELECT DeptName, AVG(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 lowest salary in each department in the “employee2” table


 SELECT DeptName,MIN(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);

Multi Row Sub Queries


In multi row subquery, it will return more than one value. In such cases we should include operators like
any, all, in or not in between the comparison operator and the subquery.
Example:

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);

WORKING WITH JOINS


Joins are used to retrieve records from multiple tables. There are 3 types of joins.
1. Self Join 2. Inner Join 3. Outer Join

Self Join: Joining a table with itself is a self join.


 SELECT e.EmpNo,e.EmpName,e.sal, m.EmpNo,m.EmoName,m.sal
FROM employee2 e, employee2 m
WHERE e.EmpNo=m.EmpNo;

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

You might also like