0% found this document useful (0 votes)
27 views21 pages

SQL Rollback and Join Examples

The document provides an overview of SQL rollback commands, detailing how to undo transactions that have not been committed. It includes examples of rollback usage with various SQL commands such as DELETE, TRUNCATE, DROP, ALTER, and INSERT, as well as explanations of SQL joins, including INNER JOIN, OUTER JOIN, CROSS JOIN, and SELF JOIN. Additionally, it covers the ROW_NUMBER() function for assigning unique sequential integers to query results.

Uploaded by

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

SQL Rollback and Join Examples

The document provides an overview of SQL rollback commands, detailing how to undo transactions that have not been committed. It includes examples of rollback usage with various SQL commands such as DELETE, TRUNCATE, DROP, ALTER, and INSERT, as well as explanations of SQL joins, including INNER JOIN, OUTER JOIN, CROSS JOIN, and SELF JOIN. Additionally, it covers the ROW_NUMBER() function for assigning unique sequential integers to query results.

Uploaded by

Jyoshma G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

It’s not an institute it’s a Gurukul.

SQL Rollback:
In SQL, a rollback is a command that is used to undo a transaction that has not yet been
committed to the database. When you execute a transaction in SQL, it can consist of one or
more SQL statements that modify the data in the database. If an error occurs during the
execution of the transaction, or if the transaction is aborted for some reason, the rollback
command can be used to undo all the changes that were made as part of the transaction.

The rollback command is typically used in conjunction with the "begin transaction" and
"commit transaction" commands, which are used to define the boundaries of a transaction.
When you execute a "begin transaction" command, SQL starts a new transaction. All the SQL
statements that are executed between the "begin transaction" and "commit transaction"
commands are part of the same transaction. If an error occurs during the execution of any of
these statements, the transaction can be rolled back using the "rollback" command.

For example, suppose you have a SQL transaction that consists of several statements that
update data in a database. If an error occurs during the execution of one of these
statements, you can issue a "rollback" command to undo all the changes that were made by
the transaction. This ensures that the database remains in a consistent state and that any
errors are properly handled.

General Syntax:
BEGIN TRANSACTION
-- Execute one or more SQL statements to modify data in MyTable
-- BEGIN TRANSACTION can be written as BEGIN TRAN in short
-- If an error occurs or the transaction needs to be rolled back, use the following
command:
ROLLBACK TRANSACTION

Now, we take some examples and rollback the data: We are using this table:
create table mytable
(
id int,
sname varchar(30),
city varchar(20),
Mob bigint
);
insert into mytable values(1,'Pravesh','bengaluru',8988999);
insert into mytable values(2,'nandini','pune',877888);
insert into mytable values(3,'ruby','mangalore',99999);
insert into mytable values(4,'Jyoti','delhi',99998);
insert into mytable values(5,'anmol','delhi',989898989);
insert into mytable values(6,'soumya','bengaluru',9852452);
insert into mytable values(7,'Dhanya','mumbai',8568458);
It’s not an institute it’s a Gurukul.

Our table is:

Example of ROLLBACK with different commands:


1. ROLLBACK on DELETE:
begin tran;
delete mytable where id=7;

select * from mytable;


It’s not an institute it’s a Gurukul.

rollback;

select * from mytable;

Query flow: We can see here rollback works on


delete in Microsoft SQL server
begin tran;
delete mytable where id=7;
select * from mytable;
rollback;
select * from mytable;

[Link] on TRUNCATE:

begin tran;
TRUNCATE TABLE mytable;
select * from mytable;
It’s not an institute it’s a Gurukul.

rollback;
select * from mytable;

We can see here rollback works on


truncate in Microsoft SQL server

[Link] on DROP:

begin tran;
DROP TABLE mytable;
select * from mytable;

rollback;
select * from mytable;

We can see here rollback works on


DROP in Microsoft SQL server
It’s not an institute it’s a Gurukul.
[Link] on ALTER:
begin tran;
ALTER TABLE mytable drop column city;
select * from mytable;

rollback;
select * from mytable;

We can see here rollback works on


ALTER in Microsoft SQL server

[Link] on UPDATE:

begin tran;
Update mytable set city='bengaluru';
select * from mytable;

rollback;
select * from mytable;

We can see here rollback works on


UPDATE in Microsoft SQL server
It’s not an institute it’s a Gurukul.
[Link] on INSERT:

begin tran;
insert into mytable values
(7,'Dhanya',
'mumbai',8568458);
select * from mytable;

rollback;
select * from mytable;

We can see here rollback works on


INSERT in Microsoft SQL server

Join,GroupBy,Having
SQL Join is a clause used to combine rows from two or more tables based on a related column
between them. Join helps to retrieve data from two or more tables based on a common field
between them.

There are mainly 4 types of SQL joins:

1. INNER JOIN
2. OUTER JOIN:
➢ LEFT JOIN (or LEFT OUTER JOIN)
➢ RIGHT JOIN (or RIGHT OUTER JOIN)
➢ FULL JOIN (or FULL OUTER JOIN)
3. CROSS JOIN (or CARTESIAN JOIN)
4. SELF JOIN
It’s not an institute it’s a Gurukul.
Lets we have 2 tables:

Table-1

CREATE TABLE [employee]


(
[Emp_ID] INT,
[Emp_Name] VARCHAR(512),
[Emp_No ] BIGINT
);

INSERT INTO [employee] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('101', 'Ashish


Kaktan', '9450425345 ');
INSERT INTO [employee] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('102', 'Raj
Choudhary', '8462309621 ');
INSERT INTO [employee] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('103', 'Vivek
Oberoi', '7512309034 ');
INSERT INTO [employee] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('104', 'Shantanu
Khandelwal', '9020330023 ');
INSERT INTO [employee] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('105', 'Khanak
Desai', '8451004522');

Table-2:
It’s not an institute it’s a Gurukul.
CREATE TABLE [Employment]
(
[Emp_ID] INT,
[Emp_Profile] VARCHAR(512),
[Emp_Country] VARCHAR(512),
[Emp_Join_Date ] VARCHAR(512)
);

INSERT INTO [Employment] ([Emp_ID], [Emp_Profile], [Emp_Country], [Emp_Join_Date ])


VALUES ('101', 'Content Writer', 'Germany', '2021-04-20 ');
INSERT INTO [Employment] ([Emp_ID], [Emp_Profile], [Emp_Country], [Emp_Join_Date ])
VALUES ('104', 'Data Analyst', 'India', '2022-12-11 ');
INSERT INTO [Employment] ([Emp_ID], [Emp_Profile], [Emp_Country], [Emp_Join_Date ])
VALUES ('105', 'Software Engineer', 'India', '2022-01-03 ');
INSERT INTO [Employment] ([Emp_ID], [Emp_Profile], [Emp_Country], [Emp_Join_Date ])
VALUES ('108', 'Development Executive', 'Europe', '2023-02-15 ');
INSERT INTO [Employment] ([Emp_ID], [Emp_Profile], [Emp_Country], [Emp_Join_Date ])
VALUES ('109', 'Marketing Manager', 'Mexico', '2020-05-23');

Question 1:

Get all the data which is present in both the tables:

select * from employee Inner JOIN Employment on employee.Emp_ID=Employment.Emp_ID;

Question 2:

Find out unique records if there are any duplicates from above only by name and id and country:

select Employment.emp_id,Emp_Name,Emp_Country from employee Inner JOIN Employment on


employee.Emp_ID=Employment.Emp_ID group by Employment.emp_id,Emp_Name,Emp_Country;
It’s not an institute it’s a Gurukul.

Question 3:

Return all employees details and their data matched in employment table :
select * from employee Left JOIN Employment on employee.Emp_ID=Employment.Emp_ID;

Question 4:

How many emp_profile data is filled in employee table give the report :
select * from employee RIGHT JOIN Employment on employee.Emp_ID=Employment.Emp_ID;

Question 5:

Make a complete report includes all the data which are present in both the table :
select * from employee FULL JOIN Employment on employee.Emp_ID=Employment.Emp_ID;
It’s not an institute it’s a Gurukul.
Question 6:

Give all the details which are uncommon :


select * from employee FULL JOIN Employment on employee.Emp_ID=Employment.Emp_ID where
employee.Emp_ID is null or Employment.Emp_ID is null;

Question 6:

Join three tables from below:

Table-1:

Join 3 tables:

:
CREATE TABLE [table1]
(
[Emp_ID] INT,
[Emp_Name] VARCHAR(512),
[Emp_No ] BIGINT
);

INSERT INTO [table1] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('101', 'Ashish Kaktan',
'9450425345 ');
INSERT INTO [table1] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('102', 'Raj Choudhary',
'8462309621 ');
INSERT INTO [table1] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('103', 'Vivek Oberoi',
'7512309034 ');
INSERT INTO [table1] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('104', 'Shantanu
Khandelwal', '9020330023 ');
INSERT INTO [table1] ([Emp_ID], [Emp_Name], [Emp_No ]) VALUES ('105', 'Khanak Desai',
'8451004522');
It’s not an institute it’s a Gurukul.

Table-2:

CREATE TABLE [table2]


(
[Emp_ID] INT,
[Emp_Profile] VARCHAR(512),
[Emp_Email ] VARCHAR(512)
);

INSERT INTO [table2] ([Emp_ID], [Emp_Profile], [Emp_Email ]) VALUES ('101', 'Content


Writer', 'ashish@[Link] ');
INSERT INTO [table2] ([Emp_ID], [Emp_Profile], [Emp_Email ]) VALUES ('104', 'Data
Analyst', 'shantanu@[Link] ');
INSERT INTO [table2] ([Emp_ID], [Emp_Profile], [Emp_Email ]) VALUES ('105', 'Software
Engineer', 'khanak@[Link] ');
INSERT INTO [table2] ([Emp_ID], [Emp_Profile], [Emp_Email ]) VALUES ('109',
'Development Executive', 'akshay@[Link] ');
INSERT INTO [table2] ([Emp_ID], [Emp_Profile], [Emp_Email ]) VALUES ('108', 'Marketing
Manager', 'nikita@[Link]');

Table3:
It’s not an institute it’s a Gurukul.

CREATE TABLE [table3]


(
[Emp_Country] VARCHAR(512),
[Emp_Email] VARCHAR(512),
[Emp_JoinDate ] VARCHAR(512)
);

INSERT INTO [table3] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('Germany',


'ashish@[Link]', '2021-04-20 ');
INSERT INTO [table3] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('India',
'shantanu@[Link]', '2022-12-11 ');
INSERT INTO [table3] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('India',
'khanak@[Link]', '2022-01-03 ');
INSERT INTO [table3] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('Europe',
'akshay@[Link]', '2023-02-15 ');
INSERT INTO [table3] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('Mexico',
'nikita@[Link]', '2020-05-23');

Question 7:

Join all the 3 tables and make report master table with full data

select * from [table1] full join table2 on table1.Emp_ID=table2.Emp_ID full join


table3 on table3.Emp_Email=table2.[Emp_Email ];
It’s not an institute it’s a Gurukul.

Cross JOIN:
Question 8:

Productid table:

CREATE TABLE [productid]


(
[Product] VARCHAR(512)
);

INSERT INTO [productid] ([Product]) VALUES ('Lipistic');


INSERT INTO [productid] ([Product]) VALUES ('kajal');
INSERT INTO [productid] ([Product]) VALUES ('bindi');
INSERT INTO [productid] ([Product]) VALUES ('bangal');

Color table:
It’s not an institute it’s a Gurukul.

CREATE TABLE [color]


(
[Color] VARCHAR(512)
);

INSERT INTO [color] ([Color]) VALUES ('red');


INSERT INTO [color] ([Color]) VALUES ('blue');
INSERT INTO [color] ([Color]) VALUES ('pink');
INSERT INTO [color] ([Color]) VALUES ('green');

Q8. How many color combinations are present:

select * from productid cross join color;


It’s not an institute it’s a Gurukul.

Self join:

CREATE TABLE [mytable1]


(
[Emp_ID] INT,
[Emp_Name] VARCHAR(512),
[Emp_Profile] VARCHAR(512),
[Emp_Country] VARCHAR(512),
[ManagerId ] INT
);

INSERT INTO [mytable1] ([Emp_ID], [Emp_Name], [Emp_Profile], [Emp_Country], [ManagerId


]) VALUES ('101', 'Ashish Kaktan', 'Content Writer', 'Germany', '104 ');
INSERT INTO [mytable1] ([Emp_ID], [Emp_Name], [Emp_Profile], [Emp_Country], [ManagerId
]) VALUES ('104', 'Raj Choudhary', 'Data Analyst', 'India', '108 ');
INSERT INTO [mytable1] ([Emp_ID], [Emp_Name], [Emp_Profile], [Emp_Country], [ManagerId
]) VALUES ('105', 'Vivek Oberoi', 'Software Engineer', 'India', '101 ');
INSERT INTO [mytable1] ([Emp_ID], [Emp_Name], [Emp_Profile], [Emp_Country], [ManagerId
]) VALUES ('108', 'Shantanu Khandelwal', 'Development Executive', 'Europe', '101 ');
INSERT INTO [mytable1] ([Emp_ID], [Emp_Name], [Emp_Profile], [Emp_Country], [ManagerId
]) VALUES ('109', 'Khanak Desai', 'Marketing Manager', 'Mexico', ' ');

Q9 write all the employee manager name:


SELECT e.Emp_ID, e.Emp_Name, m.Emp_Name as ManagerName
FROM mytable1 e JOIN mytable1 m ON e.[ManagerId ] = m.Emp_ID;
It’s not an institute it’s a Gurukul.

Q10. Fetch all table exclude manager details from above table
select Emp_ID,Emp_Name,Emp_Profile,Emp_Country from mytable1;

SQL ROW number:


In SQL, the ROW_NUMBER() function is used to assign a unique sequential integer to each row in the
query's result set. This function is typically used in scenarios where you need to identify or rank rows
based on a specific order, such as sorting by a column value.

The syntax for using ROW_NUMBER() function is as follows:

SELECT ROW_NUMBER() OVER (ORDER BY column_name) AS row_number, column1, column2, ...

FROM table_name;

Here, column_name is the column that you want to use for ordering the rows, and table_name is the
name of the table you are querying. The row_number column is the column that is added to the
result set by the ROW_NUMBER() function, which assigns a unique number to each row based on the
order specified by the ORDER BY clause.

You can use the ROW_NUMBER() function for various purposes, such as:

Paginating data: You can use the ROW_NUMBER() function to limit the number of rows returned by
a query, which is useful for pagination.

Ranking data: You can use the ROW_NUMBER() function to rank data based on a specific order, such
as sorting by a column value.

Grouping data: You can use the ROW_NUMBER() function to group data into partitions and then
assign a sequential number to each row within each partition. This can be useful for generating
reports or summaries of data.
It’s not an institute it’s a Gurukul.

Overall, the ROW_NUMBER() function is a powerful tool in SQL that can be used in a variety of
scenarios to manipulate and analyze data.

Example:

Here is the table:


CREATE TABLE Customer (
ID int,
Name varchar(255) default NULL,
Gender varchar(255) default NULL,
mobile varchar(100) default NULL,
Sales varchar(100) default NULL,
discount int default NULL,
profit int default NULL,
country varchar(100) default NULL,
postalZip varchar(10) default NULL,
region varchar(50) default NULL,
addr varchar(255) default NULL,
PRIMARY KEY ( id )
)

INSERT INTO customer ( ID , Name , Gender , mobile , Sales , discount , profit , country , postalZip
, region , addr )
VALUES
(100,'Shelly','Female','+912966563614','94 055',20,777,'India','476041','Maharastra','Ap #176-8059
Mauris, Street'),
(101,'Duncan','Male','+919789537182','11 405',7,416,'India','591863','Daman and Diu','351-6655 Mus.
Road'),
(102,'Harper','Female','+915918966525','49 374',46,466,'India','438710','Chhattisgarh','525-5916
Fringilla St.'),
(103,'Sybill','Female','+914459474563','91 802',27,49,'India','638117','Bihar','P.O. Box 332, 8755
Metus. Ave'),
(104,'Charde','Female','+917676783487','86 627',36,706,'India','256850','Chhattisgarh','379-6123 Sit
Street'),
(105,'Allegra','Female','+915627678872','63 707',24,967,'India','571238','Haryana','4554 Ac Ave'),
(106,'Ryder','Female','+913577439557','75 668',13,660,'India','787425','Dadra and Nagar
Haveli','P.O. Box 436, 2983 Libero Street'),
(107,'Whoopi','Male','+914566187345','22 650',38,385,'India','118133','Meghalaya','782 Ut St.'),
(108,'Donovan','Male','+913545894686','54 289',48,892,'India','282039','Delhi','Ap #742-7148 Ante
Street'),
(109,'Belle','Male','+913563424278','89 018',32,873,'India','248656','Kerala','607-4643 Congue
Road');
INSERT INTO customer ( ID , Name , Gender , mobile , Sales , discount , profit , country , postalZip
, region , addr )
VALUES
(110,'Rhonda','Female','+914164859664','37 165',23,921,'India','530978','Lakshadweep','Ap #323-5378
Ut Road'),
(111,'Lillith','Female','+918433882781','11 665',16,778,'India','943227','West Bengal','P.O. Box
624, 3014 Tellus. St.'),
(112,'Kelsey','Male','+915977253543','4 994',1,999,'India','384561','Meghalaya','Ap #673-8276 Orci
Avenue'),
(113,'Francis','Female','+914659474386','37 612',12,248,'India','631173','West Bengal','143-9808
Elementum, Street'),
(114,'Cole','Female','+915548456745','89 375',15,4,'India','321622','Daman and Diu','477-4174
Egestas Street'),
(115,'Kylie','Male','+917561938381','86 423',21,247,'India','918553','Dadra and Nagar Haveli','9165
Vestibulum Rd.'),
(116,'Upton','Male','+914622263234','53 645',13,873,'India','568459','Madhya Pradesh','P.O. Box 522,
9503 Sapien, St.'),
(117,'Talon','Male','+915313382673','75 105',30,335,'India','168933','Dadra and Nagar Haveli','568-
1023 Fusce Av.'),
(118,'Maggy','Male','+913415836533','53 801',27,469,'India','937753','Uttarakhand','496-7593
Interdum. Street'),
(119,'Oscar','Female','+916533162695','40 098',15,29,'India','237454','Himachal Pradesh','3238 At,
Avenue');
It’s not an institute it’s a Gurukul.
Q. Find out all the rank number:

--Row_number()
select id,name,sales,row_number() over (order by sales desc) as customer_rank from
customer;

Example:2
It’s not an institute it’s a Gurukul.

CREATE TABLE [table31]


(
[Emp_Country] VARCHAR(512),
[Emp_Email] VARCHAR(512),
[Emp_JoinDate ] VARCHAR(512)
);

INSERT INTO [table31] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('Germany',


'ashish@[Link]', '2021-04-20 ');
INSERT INTO [table3] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('India',
'shantanu@[Link]', '2022-12-11 ');
INSERT INTO [table31] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('India',
'khanak@[Link]', '2022-01-03 ');
INSERT INTO [table31] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('Europe',
'akshay@[Link]', '2023-02-15 ');
INSERT INTO [table31] ([Emp_Country], [Emp_Email], [Emp_JoinDate ]) VALUES ('INDIA',
'nikita@[Link]', '2020-05-23');

Q. How many people are from each country:


select * ,row_number() over(partition by emp_country order by emp_country) as
counts_of_countrymember from table31;
It’s not an institute it’s a Gurukul.
Groupby and having:

Example1:
--there is a date column and there are multiple dates for each city, for example,2-
march-2019,2-march-2020 dates are for the city Jaipur . How to get the latest date for
each city?

CREATE TABLE [pptqtns]


(
[id] INT,
[city] VARCHAR(512),
[dates ] VARCHAR(512)
);

INSERT INTO [pptqtns] ([id], [city], [dates ]) VALUES ('1', 'jaipur', '2019-03-02 ');
INSERT INTO [pptqtns] ([id], [city], [dates ]) VALUES ('2', 'delhi', '2018-02-03 ');
INSERT INTO [pptqtns] ([id], [city], [dates ]) VALUES ('3', 'jaipur', '2020-03-02 ');
INSERT INTO [pptqtns] ([id], [city], [dates ]) VALUES ('7', 'mumbai', '1999-12-25 ');
INSERT INTO [pptqtns] ([id], [city], [dates ]) VALUES ('4', 'delhi', '1998-12-25 ');
INSERT INTO [pptqtns] ([id], [city], [dates ]) VALUES ('5', 'jaipur', '1999-11-19 ');
INSERT INTO [pptqtns] ([id], [city], [dates ]) VALUES ('6', 'bhopal', '2020-05-06');

select * from [Link];


select city,max(dates) as latest_dates from [Link] group by city;
It’s not an institute it’s a Gurukul.
Example2:

create table studentdata


(id int primary key,
name varchar (20) not null,
mob bigint unique,
email varchar (20) unique,
age int check (age>18),
addr varchar(22) default 'INDIA'
);

insert into studentdata values (1,'pravesh',9991,'pravesh@[Link]',29,'bangalore');


insert into studentdata values (2,'jyoti',9992,'jyoti@[Link]',25,'delhi');
insert into studentdata values (3,'soumya',9993,'soumya@[Link]',24,'bangalore');
insert into studentdata values (4,'anmol',9994,'anmol@[Link]',24,'chandigarh');
insert into studentdata values (6,'dhanya',9996,'dhanya@[Link]',20,'vancover');
insert into studentdata values (5,'nandini',9995,'nandini@[Link]',20,'pune');
insert into studentdata values (7,'khushi',9998,'khushi@[Link]',40,'kolkata');
insert into studentdata values (8,'shorya',9985,'shorya@[Link]',40,'surat');
insert into studentdata (id,name, mob,email,age) values
(13,'rocky',1111,'rocky@[Link]',19);
insert into studentdata (id,name, mob,email,age) values
(14,'taylor',2222,'taylor@[Link]',30);

[Link] by student data by their age

--GROUP BY
select * from studentdata;

select addr,sum(age) as city_wise_STUDENTS_AGE from studentdata group by addr;

[Link] by student data by their age who are above 20 years

--HAVING (when you need to give condition and you are using aggregated functions and
group by)
select * from studentdata;
select addr,sum(age) as city_wise_STUDENTS_AGE from studentdata group by addr having
sum(age) >20;

You might also like