0% found this document useful (0 votes)
7 views

RDBMS UNIT 4 (1)

This document provides an overview of SQL commands, categorizing them into DDL, DML, DCL, and TCL, along with their respective functions and syntax. It covers various SQL operations such as creating, modifying, and deleting tables, as well as data manipulation commands like SELECT, INSERT, UPDATE, and DELETE. Additionally, it discusses SQL constraints and different types of joins used to combine data from multiple tables.

Uploaded by

merita.281984
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

RDBMS UNIT 4 (1)

This document provides an overview of SQL commands, categorizing them into DDL, DML, DCL, and TCL, along with their respective functions and syntax. It covers various SQL operations such as creating, modifying, and deleting tables, as well as data manipulation commands like SELECT, INSERT, UPDATE, and DELETE. Additionally, it discusses SQL constraints and different types of joins used to combine data from multiple tables.

Uploaded by

merita.281984
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT : 4

Introduction to SQL: Data Definition Commands – Data Manipulation Commands –


SELECT Queries - Additional Data Definition Commands – Additional SELECT Query
Keywords – Joining Database Tables. Advance SQL: Relational SET Operators: UNION –
UNION ALL – INTERSECT –MINUS. SQL Join Operators: Cross Join – Natural Join –
Join USING Clause –JOIN ON Clause – Outer Join.

SQL commands are very used to interact with the database. These commands allow
users to perform various actions on a database.

SQL commands or SQL sublanguage commands like DDL, DML, DCL, and TCL.

These SQL commands are mainly categorized into five categories:


1. DDL – Data Definition Language
2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language

DDL (Data Definition Language)


1. Data Definition Language (DDL):
 To define and modify the structure of a database, including creating
tables, modifying table structure, and dropping tables. It contains of
commands which defines the data.
 The SQL Commands are:
1. Create: It is used to create a table.
Syntax:
CREATE TABLE Table_name (column1 data_type(Size), column2
data_type(Size), ...);
Eg:
CREATE TABLE Employee(Name Varchar2(12), Addressl Varchar2
(20), Dob Date);

2. Drop: It is used to delete the table including all the attributes.


Syntax:
DROP TABLE Table_name;
Eg:
DROP TABLE Employee;

3. Alter: Alter is a reserve word which modifies the structure of the table.
Syntax:
(*) ALTER TABLE Table_name ADD (column_name
data_type);
Eg:
ALTER TABLE Stu_details ADD (adhar_num varchar2 (12));

(*) ALTER TABLE Table_name MODIFY(column_name


data_type);
Eg:
ALTER TABLE Stu_details MODIFY (Adhar_Num Varchar2 (20));
(*) To drop a column from a table.
(*) ALTER TABLE Table_name DROP COLUMN column_name;
Eg:
ALTER TABLE Stu_Details DROP COLUMN Adhar_Num

4. Rename: A table name can be changed using the reserve ‘rename’


Syntax:
RENAME TABLE Old_table_name TO New_table_name;
Eg:
RENAME TABLE Stu_details to Stu_Info;

5. TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.
Syntax:
TRUNCATE TABLE table_name;
Eg:
TRUNCATE TABLE Employee;
DML(Data Manipulation Language)
 DML commands are used to modify the database. It is responsible for all
form of changes in the database.
 The SQL Commands are
1. Insert:
This command is generally used after the create command to insert a set of
values into the table.
Syntax:
INSERT INTO table_name (column1, column2, ...) VALUES (value1,
value2, ...);
Eg:
INSERT INTO Book_det(Author, Subject) VALUES ("Sonoo", "DBMS");
2. Delete:
It is used to remove one or more row from a table. To delete rows from
the table, it must be in your schema or you must have delete privilege.
Syntax:
DELETE FROM table_name WHERE condition;
Eg:
DELETE FROM Book_det WHERE Author="Sonoo";

3. Update:
This command is used to update or modify the value of a column in
the table.
Syntax:
UPDATE table_name SET column1 = value1, column2 =
value2 WHERE condition;
Eg:
UPDATE studentsSET User_Name = 'Sonoo' WHERE
Student_Id = '3';
4. 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.
 It is used for retrieve the records from table.
 It is also known as Data Query Language(DQL).
 It including the ability to filter, sort, group, and join data from
multiple tables.
Syntax:
SELECT expressions FROM Tables_Name WHERE conditions;
Eg:
a. SELECT * FROM employees;
b. SELECT Emp_name FROM employee WHERE age > 20;

Data Control Language

DCL commands are used to grant and take back authority from any database user.
The commands that comes under DCL are Grant and Revoke

1. Grant: It is used to give permissions to the user.


Syntax:
GRANT <obj_priv> ON <obj_name> To <username>;

In the above syntax, <obj_priv> is the DML statement like Insert, Delete , update and
Select and <obj_name> is a table, view etc. and username is the name of the authorized user.

Eg:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_US
ER;
2. Revoke:
It is used to take back permissions from the user.

Syntax:
REVOKE <obj_priv> ON <obj_name> FROM <username>;

In the above syntax, obj_priv> is the DML statement like Insert, Delete , update and
Select and <obj_name> is a table, view etc. and username is the name of the user from whom
the permission is revoked.

Example

REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;


TCL (Transaction Control Language)
 Transactions group a set of tasks into a single execution unit.
 Each transaction begins with a specific task and ends when all the tasks in the group
are successfully completed.
 If any of the tasks fail, the transaction fails.
 Some TCL commands and their syntax are:

(1) BEGIN TRANSACTION Command


It indicates the start point of an explicit or local transaction.
Syntax:
BEGIN TRANSACTION transaction_name ;

(2) SET TRANSACTION Command


The values for the properties of the current transaction, such as the
transaction isolation level and access mode, are set using the SET
TRANSACTION Statement in MySQL.
Syntax:
SET TRANSACTION [ READ WRITE | READ ONLY ];

(3) COMMIT Command:


Commit command is used to save all the transactions to the database. It
makes your changes permanent and ends the transaction.
To permanently save the changes

Syntax:
COMMIT;

(4) ROLLBACK Command:


If any error occurs with any of the SQL grouped statements, all changes need to be aborted.
The process of reversing changes is called rollback. This command can only be used to undo
transactions since the last COMMIT or ROLLBACK command was issued.
Syntax for ROLLBACK command:
ROLLBACK;
Example:
Sample Table1

1. Following is an example which would delete those records from the table which have age
= 20 and then COMMIT the changes in the database.

Query
DELETE FROM Student WHERE AGE = 20;
COMMIT;
Output
Thus, two rows from the table would be deleted and the SELECT statement would look like,

2. Delete those records from the table which have age = 20 and then ROLLBACK the
changes in the database.
Query
DELETE FROM Student WHERE AGE = 20;
ROLLBACK;
5. SAVEPOINT Command:

It is used to roll the transaction back to a certain point without rolling back the entire
transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;

In the above syntax, SAVEPOINT_NAME is the name given to savepoint.

To selectively ROLLBACK a group of statements within a large transaction use the


following command is used.

Rollback TO <save_point_name>

Example:
DELETE FROM CUSTOMERS WHERE AGE = 15;
SAVEPOINT A;
DELETE FROM CUSTOMERS WHERE AGE = 35;
ROLLBCAK TO A;

SELECT Statement
 It is used to access records from one or more database tables and views.
 The SELECT statement retrieves selected data based on specified conditions.
 The result of a SELECT statement is stored in a result set or result table.
 The SELECT statement can be used to access specific columns or all columns from a
table.
 It can be combined with clauses like WHERE, GROUP BY, HAVING, and ORDER
BY for more refined data retrieval.
 The SELECT statement is versatile and allows users to fetch data based on various
criteria efficiently.
Syntax
The syntax for the SELECT statement is:
SELECT column1,column2…. FROM table_name ;

Examples:

1.Fetch All Table using SELECT Statement


Query:
SELECT * FROM Customer;

SELECT Statement with WHERE Clause


SELECT CustomerName FROM Customer where Age = '21';
Output:

SQL SELECT Statement with GROUP BY Clause


Query:
SELECT COUNT (item), Customer_id FROM Orders GROUP BY order_id;
Output:
SELECT Statement with HAVING Clause
Consider the following database for HAVING Clause:

Query:
SELECT Department, sum(Salary) as Salary
FROM employee
GROUP BY department
HAVING SUM(Salary) >= 50000;

Output:

SELECT Statement with ORDER BY clause in SQL


Query:
SELECT * FROM Customer ORDER BY Age DESC;
Output:
SQL Constraints

 SQL constraints are used to specify rules for the data in a table.
 Constraints are used to limit the type of data that can go into a table.
 This ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
 Constraints can be column level or table level.
 Column level constraints apply to a column, and table level constraints apply to the
whole table.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the database very quickly

1. NOT NULL Constraint

 A column can hold NULL values.


 The NOT NULL constraint enforces a column to NOT accept NULL values.
 This enforces a field to always contain a value, which means that you cannot insert a
new record, or update a record without adding a value to this field.

Eg: CREATE TABLE Persons ( ID int NOT NULL,


LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int );

2. UNIQUE Constraint
 The UNIQUE constraint ensures that all values in a column are different.
 Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for
a column or set of columns.
 A PRIMARY KEY constraint automatically has a UNIQUE constraint.
 But you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.

Eg:

CREATE TABLE Persons (ID int NOT NULL, LastName varchar(20) NOT NULL,
FirstName varchar(20), Age int, CONSTRAINT UC_Person UNIQUE (ID,LastName));

3. PRIMARY KEY Constraint

 The PRIMARY KEY constraint uniquely identifies each record in a table.


 Primary keys must contain UNIQUE values, and cannot contain NULL values.
 A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).

Eg:

CREATE TABLE Persons (ID int NOT NULL PRIMARY KEY, LastName varchar(10) NOT NULL,
FirstName varchar(10), Age int);

4. FOREIGN KEY Constraint

 A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
 The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.
Eg:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

5. CHECK Constraint

 The CHECK constraint is used to limit the value range that can be placed in a column.
 A CHECK constraint on a column it will allow only certain values for this column.
 A CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
Eg:
CREATE TABLE Persons (ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);

6. DEFAULT Constraint

 The DEFAULT constraint is used to set a default value for a column.


 The default value will be added to all new records, if no other value is specified.
 Eg:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

7. INDEX Statement

 The CREATE INDEX statement is used to create indexes in tables.


 Indexes are used to retrieve data from the database more quickly than otherwise. The
users cannot see the indexes, they are just used to speed up searches/queries.

Eg:

CREATE INDEX index_name


ON table_name (column1, column2, ...);

Oracle DISTINCT Clause

DISTINCT clause is used to remove the duplicate records from the result set. It is
only used with SELECT statement.

Syntax:
SELECT DISTINCT expressions FROM tables WHERE conditions;
Eg:

Customer table:

CREATE TABLE CUSTOMERS ( NAME ,AGE SALARY , STATE ) ;

Query:
SELECT DISTINCT name, age, salary FROM customers WHERE age >= '60'

ORDER BY Clause

ORDER BY Clause is used to sort or re-arrange the records in the result set. The
ORDER BY clause is only used with SELECT statement.

Syntax:

SELECT expressions FROM tables WHERE conditions ORDER BY expression


[ ASC | DESC ];

Eg:

Consider table supplier(supplier_id,firstname, lastname)

SELECT * FROM supplier ORDER BY last_name;


SELECT * FROM supplier ORDER BY last_name DESC;

GROUP BY Clause

GROUP BY clause is used with SELECT statement to collect data from multiple
records and group the results by one or more columns.

Syntax:

SELECT expression1, expression2, ... expression_n,


aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;
Eg:
Consider table salesdepartment (item,sale,billing_addr)
1. SELECT item, SUM(sale) AS "Total sales" FROM salesdepartment
GROUP BY item;
2. SELECT item, count(*) AS "Total sales" FROM salesdepartment
WHERE Billing_addr =’chennai’ GROUP BY item
Join:

A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

Table 1: Students

Student_ID StudentName Subject TeacherID

101 Alexandra Computer Science T201

102 Charles Economics T202

103 Tom Cruise Computer Science T201

104 Aron Finch Electronics T203

105 Siemen Bajoff Web designing T204

106 Christopher English Literature T205

107 Denim Fashion Designer T206

Table 2: Teachers

TeacherID TeacherName TeacherEmail

T201 Mr Davis [email protected]

T202 Mrs Jonas [email protected]

T201 Mr Davis [email protected]

T204 Mrs Lopez [email protected]

T205 Mrs Wiley [email protected]

T206 Mr Bean [email protected]

INNER JOIN
 The INNER JOIN keyword selects records that have matching values in both tables.
 SQL INNER JOIN also known as simple join is the most common type of join.
Syntax

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

Eg:

Select Student_ID, StudentName, TeacherName, TeacherEmail FROM Students INNER JOI


N
Teachers ON Students.TeacherID = Teachers.TeacherID;

After executing the query, it produces the below table.

Natural Join

It is a type of inner type that joins two or more tables based on the same column name and
has the same data type present on both tables.

Syntax:
Select * from tablename1 Natural JOIN tablename_2;
Eg:
Select * from Students Natural JOIN Teachers;

After executing the above query, it produces the following table.


LEFT JOIN

The LEFT JOIN is used to retrieve all records from the left table (table1) and the matched
rows or columns from the right table (table2). If both tables do not contain any matched rows
or columns, it returns the NULL.

Syntax:
Select column_1, column_2, column(s) FROM table_1 LEFT JOIN table_2 ON
table_1.column_name = table_2.column_name;
Eg:

Table 1: Product_Details

ProductID ProductName Amount

Pro101 Laptop 56000

Pro102 Mobile 38000

Pro103 Headphones 5000

Pro104 Television 25000

Pro105 iPad 60000

Table 2: Customer_Details
CustomerName CustomerAddress CustomerAge ProductID

Martin Guptill San Francisco, USA 26 Pro101

James Australia 29 Pro103

Ambati Williamson New Zealand 27 Pro102

Jofra Archer South Africa 24 Pro105

Kate Wiley Australia 20 Pro103

Eg. For LEFT JOIN

Select ID, ProductName, CustomerName, CustomerAddress, Amount FROM Product_Detail


s
LEFT JOIN Customer_Details ON Product_Details.ID = Customer_Details.ProductID;

RIGHT JOIN or RIGHT Outer JOIN:

The RIGHT JOIN is used to retrieve all records from the right table (table2) and the
matched rows or columns from the left table (table1). If both tables do not contain any
matched rows or columns, it returns the NULL.

Syntax:

Select column_1, column_2, column(s) FROM table_1 RIGHT JOIN table_2 ON table_1.c
olumn_name = table_2.column_name;

Table 1: Product_Details

ID ProductName Amount
Pro101 Laptop 56000

Pro102 Mobile 38000

Pro103 Headphones 5000

Pro104 Television 25000

Pro105 iPad 60000

Table 2: Customer_Details

CustomerName CustomerAddress CustomerAge ProductID

Martin Guptill San Francisco, USA 26 Pro101

James Australia 29 Pro103

Ambati Williamson New Zealand 27 Pro102

Jofra Archer South Africa 24 Pro105

Omen England 29 Pro107

Morgan England 20 Pro108

Eg. For RIGHT JOIN :

Select ID, ProductName, CustomerName, CustomerAddress, Amount FROM Product_Detail


RIGHT JOIN Customer_Details ON Product_Details.ID = Customer_Details.ProductID;

After executing the query, it produces the below table.

FULL JOIN or FULL Outer JOIN:

It is a combination result set of both LEFT JOIN and RIGHT JOIN. The joined tables
return all records from both the tables and if no matches are found in the table, it places
NULL. It is also called a FULL OUTER JOIN.
Syntax:

Select column_1, column_2, column(s) FROM table_1 FULL JOIN table_2 ON

table_1.column_name = table_2.column_name;

Table 1: Product_Details

ID ProductName Amount

Pro101 Laptop 56000

Pro102 Mobile 38000

Pro103 Headphones 5000

Pro104 Television 25000

Pro105 iPad 60000

CustomerName CustomerAddress CustomerAge ProductID

Martin Guptill San Francisco, USA 26 Pro101

James Australia 29 Pro103

Ambati Williamson New Zealand 27 Pro102

Jofra Archer South Africa 24 Pro105

Omen England 29 Pro107

Morgan England 20 Pro108

Table 2: Customer_Details
We have two tables: Product_Details and the Customer_Details Tables. Let's write the
SQL

Queries to join the table using the FULL JOIN as follows:

Select ID, ProductName, CustomerName, CustomerAddress, Amount FROM Product_Detail


s
FULL JOIN Customer_Details ON Product_Details.ID = Customer_Details.ProductID;

After executing the query, it produces the below table.

CROSS JOIN

It is also known as CARTESIAN JOIN, which returns the Cartesian product of two
or more joined tables. The CROSS JOIN produces a table that merges each row from the
first table with each second table row. It is not required to include any condition in CROSS
JOIN.

Syntax:

Select * from table_1 cross join table_2;

Or

Select column1, column2, column3 FROM table_1, table_2;

We have two tables: Product_Details and the Customer_Details Tables. Let's write the
SQL Queries to join the table using the FULL JOIN as follows:

Select ID, ProductName, CustomerName, CustomerAddress, Amount FROM Product_Detail


s,

Customer_Details;

After executing the query, it produces the below table.


SELF JOIN

It is a SELF JOIN used to create a table by joining itself as there were two tables. It makes
temporary naming of at least one table in an SQL statement.

Syntax:

Select column1, column2, column(s) FROM table_1 Tbl1, table_2 Tbl2 WHERE condition;

Tbl1 and Tbl2 are two different table aliases for the same table.

Table 1: Product_Details

ID ProductName Amount

Pro101 Laptop 56000

Pro102 Mobile 38000

Pro103 Headphones 5000

Pro104 Television 25000

Pro105 iPad 60000

Select TB.ID, TB.ProductName FROM Product_Details TB, Product_Details TB2


1. WHERE TB.AMOUNT < TB2.AMOUNT;

After executing the query, it produces the below table.

You might also like