You are on page 1of 12

UNIT 4

SQL Structured Query Language)

Structured Query Language is a standard Database language which is used to create,


maintain and retrieve the relational database. Following are some interesting facts about
SQL. Initially created in the 1970s, SQL is regularly used not only by database
administrators, but also by developers writing data integration scripts and data analysts
looking to set up and run analytical queries. SQL is the programming language for
relational databases and perform various operations on the data in them.
SQL is case insensitive. But it is a recommended practice to use keywords (like SELECT,
UPDATE, CREATE, etc) in capital letters and use user defined things (liked table name,
column name, etc) in small letters.

SQL is used for the following.


• Modifying database table and index structures.
• Adding, updating and deleting rows of data and,
• Retrieving subsets of information from within relational database management
sytems.

What is Relational Database?


Relational database means the data is stored as well as retrieved in the form of relations
(tables). Table 1 shows the relational database with only one relation
called STUDENT which stores Roll_No, Name,Address,Phone and Age of students.

STUDENT

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

Table 1

SQL Commands
• SQL commands are instructions. It is used to communicate with the database. It is
also used to perform specific tasks, functions, and queries of data.
• SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

Types of SQl Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)
• DDL changes the structure of the table like creating a table, deleting a table, altering
a table, etc.
• All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
Here are some commands that come under DDL:
a) CREATE
b) ALTER
c) DROP
d) TRUNCATE
a. CREATE It is used to create a new table in the database (like table, index, function, views,
store procedure and triggers)
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);

b. DROP: It is used to delete both the structure and record stored in the table.
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:


ALTER TABLE table_name MODIFY(column_definitions....);
EXAMPLE:
• ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
• ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It 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 EMPLOYEE;

2. Data Manipulation Language


DML commands are used to modify the database. It is responsible for all form of changes in
the database.
The command of DML is not auto-committed that means it can't permanently save all the
changes in the database. They can be rollback.
Here are some commands that come under DML:
a) INSERT
b) UPDATE
c) DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.
Syntax:
INSERT INTO TABLE_NAME VALUE (value1, value2, value3, .... valueN);
For example:
INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHE
RE CONDITION]
For example:
UPDATE students SET User_Name = 'Sonoo' WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.


Syntax:
DELETE FROM table_name [WHERE condition];
For example:
DELETE FROM javatpoint WHERE Author="Sonoo";

3. Data Control Language


DCL commands are used to grant and take back authority from any database user.
Here are some commands that come under DCL:
a) Grant
b) Revoke
a. Grant: It is used to give user access privileges to a database.
Example:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

b. Revoke: It is used to take back permissions from the user.


Example:
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language


TCL commands can only use with DML commands like INSERT, DELETE and UPDATE
only.
These operations are automatically committed in the database that's why they cannot be
used while creating tables or dropping them.
Here are some commands that come under TCL:
a) COMMIT
b) ROLLBACK
c) SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
COMMIT;
Example:
DELETE FROM CUSTOMERS WHERE AGE = 25;
COMMIT;
b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.
Syntax:
ROLLBACK;
Example:
DELETE FROM CUSTOMERS WHERE AGE = 25;
ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;

5. Data Query Language


DQL is used to fetch the data from the database.
It uses only one command:
a) SELECT

a. SELECT: This is the same as the projection operation of relational algebra. It is used to
select the attribute based on the condition described by WHERE clause.
Syntax:
SELECT expressions FROM TABLES WHERE conditions;
For example:
SELECT emp_name FROM employee WHERE age > 20;

JOINS:
A join is used to combine rows from multiple tables. Join is performed whenever two
or more tables is listed in the FROM clause of an SQL statement. The sql JOIN clause
is used whenever we have to select data from 2 or more tables. The sql JOIN clause is
used to retrieve data from 2 or more tables joined by common fields. The most
common scenario is a primary key from one of the tables matches a foreign key in
second table.
A join is a mechanism that allows the tables to be linked together. The rows retrieved
after joining the two tables based on a condition in which one table act as a primary
table and other act as a foreign table. The columns in the first table which act as a
foreign key must match to the column in the second table which is defined as a
primary key referenced by foreign key.
Note:
• Join = Cross product + some condition
• Common Attributes

SQL Aliases

• SQL aliases are used to give a table, or a column in a table, a temporary name.
• Aliases are often used to make column names more readable.
• An alias only exists for the duration of that query.
• An alias is created with the AS keyword.
Alias Column Syntax

SELECT column_name AS alias_name


FROM table_name;

Alias Table Syntax


SELECT column_name(s)
FROM table_name AS alias_name;

Types of Joins are:


1. Natural Join
2. Self Join
3. Equi-Join
4. Outer Join
• Left outer join
• Right outer join
• Full outer join

1.NATURAL JOIN
Natural join is an SQL join operation that creates join on the base of the
common columns in the tables. To perform natural join there must be one common
attribute(Column) between two tables. Natural join will retrieve from multiple
relations. A NATURAL JOIN can be an INNER join, a LEFT OUTER join, or a RIGHT
OUTER join. The default is INNER join.
Features of Natural Join:
1. It will perform the Cartesian product.
2. It finds consistent tuples and deletes inconsistent tuples.
3. Then it deletes the duplicate attributes..
Natural Join: Guidelines

- The associated tables have one or more pairs of identically named columns.
- The columns must be the same data type.
- Don’t use ON clause in a natural join.

Syntax:

Select * from table1 natural join table2;

Example : Find the “Employee” names who are working in a “Department”

SELECT E_Name from Employee NATURAL JOIN Department


Employee Department
E_No E_Name Address E_No D_Name D_No
1 Rose Delhi 1 HR D1
2 Mary Mumbai 2 IT D2
3 John Delhi 3 Manager D3
4 Rohan Goa 5 HR D5
5 Jack Gurgaon

Output:
Rose
Mary
John
Jack

EQUI JOIN :
EQUI JOIN creates a JOIN for equality or matching column(s) values of the relative
tables. EQUI JOIN also create JOIN by using JOIN with ON and then providing the
names of the columns with their relative tables to check equality using equal sign
(=).
Syntax :
SELECT column_list
FROM table1, table2....
WHERE table1.column_name =
table2.column_name;
or
Syntax :
SELECT column_list
FROM table1
JOIN table2
[ON (join_condition)]
Example –

Let’s Consider the two tables given below.


Student :
ID NAME CLASS CITY
3 Hina 3 Delhi
4 Megha 2 Delhi
6 Gouri 2 Delhi
Record:
ID CLASS CITY
9 3 Delhi
10 2 Delhi
12 2 Delhi
Example –
SELECT student.name, student.id, record.class, record.city
FROM student, record
WHERE student.city = record.city;
Or
Example –
SELECT student.name, student.id, record.class, record.city
FROM student
JOIN record
ON student.city = record.city;
Output:
NAME ID CLASS CITY
Hina 3 3 Delhi
Megha 4 3 Delhi
Gouri 6 3 Delhi
Hina 3 2 Delhi
Megha 4 2 Delhi
Gouri 6 2 Delhi
Hina 3 2 Delhi
Megha 3 2 Delhi
Gouri 6 2 Delhi

2. Self Join
The SELF JOIN is used to join a table to itself as if the table were two tables;
temporarily renaming at least one table in the SQL statement. A self join uses
the inner join or left join clause. Because the query that uses the self join references
the same table, the table alias is used to assign different names to the same table
within the query.
Syntax:
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
T1 and T2 are different table aliases for the same table.

Example of “Self Join”


Employee:
Student_ID Course_ID Year
101 C1 2000
102 C2 2007
103 C2 2020
101 C1 2020

select * from employee as T1,employee as T2 where t1.e_id=t2.e_id;

Student_ID Course_ID Year Student_ID Course_ID Year


101 C1 2000 101 C1 2000
102 C2 2007 102 C2 2007
103 C2 2020 103 C2 2020
101 C1 2020 101 C1 2020

Outer Join:

• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or
right table

LEFT JOIN
The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from the right
side, if there is no match.

LEFT JOIN Syntax

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

Example of using left outer join:

Employee:

Emp_No E_name Address


1 Ram Kohima
2 Ravi Delhi
3 John Goa
4 Mary Kolkata
5 Lily Delhi

Department:

Dept_No Location E_No


1 Delhi 1
2 Mumbai 2
3 Delhi 4

Select E_name,address,Location,Dept_no from employee left outer join department


on(employee.emp_no=department.dept_no)

Output:

E_name Address Location Dept_no


Ram Kohima Delhi 1
Ravi Delhi Mumbai 2
Mary Kolkata Delhi 3
John Goa - -
Lily Delhi - -

SQL RIGHT JOIN

The RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records from the left table (table1). The result is 0 records from the left
side, if there is no match.

RIGHT JOIN Syntax

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Right outer join:

Example of using right outer join:

Employee:

Emp_No E_name Address


1 Ram Kohima
2 Ravi Delhi
3 John Goa

Department:

Dept_No Location E_No


1 Delhi 1
2 Mumbai 2
3 Delhi 3
4 Delhi 4
5 Mumbai 5
Select E_name,address,Location,Dept_no from employee right outer join department
on(employee.emp_no=department.dept_no)

Output:

E_name Address Location Dept_no


Ram Kohima Delhi 1
Ravi Delhi Mumbai 2
John Goa Delhi 3
- - Delhi 4
- - Mumbai 5

SQL FULL OUTER JOIN

The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.

Tip: FULL OUTER JOIN and FULL JOIN are the same.

FULL OUTER JOIN Syntax

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

Note: FULL OUTER JOIN can potentially return very large result-sets!

Example of using full outer join:

Employee:

Emp_No E_name Address


1 Ram Kohima
2 Ravi Delhi
3 John Goa
4 Mary Kolkata
5 Lily Delhi
Department:

Dept_No Location E_No


1 Delhi 1
2 Mumbai 2
3 Delhi 3
4 Delhi 6
5 Mumbai 7

Select E_name,address,Location,Dept_no from employee full outer join department


on(employee.emp_no=department.dept_no)

Output:

E_name Address Location Dept_no


Ram Kohima Delhi 1
Ravi Delhi Mumbai 2
John Goa Delhi 3
Mary kolkata - -
Lily Delhi - -
- - Delhi 4
- - Mumbai 5

You might also like