SET Operations in SQL

SQL supports few Set operations which can be performed on the table data. These are used to get meaningful results from data stored in the table, under different special conditions.

In this tutorial, we will cover 4 different types of SET operations, along with example:

  1. UNION
  2. UNION ALL
  3. INTERSECT
  4. MINUS

UNION Operation

UNION is used to combine the results of two or more SELECT statements. However it will eliminate duplicate rows from its resultset. In case of union, number of columns and datatype must be same in both the tables, on which UNION operation is being applied.

union set operation in sql

Example of UNION

The First table,

IDName
1abhi
2adam

The Second table,

IDName
2adam
3Chester

Union SQL query will be,

SELECT * FROM First 
UNION
SELECT * FROM Second;

The resultset table will look like,

IDNAME
1abhi
2adam
3Chester

UNION ALL

This operation is similar to Union. But it also shows the duplicate rows.

union all set operation in sql

Example of Union All

The First table,

IDNAME
1abhi
2adam

The Second table,

IDNAME
2adam
3Chester

Union All query will be like,

SELECT * FROM First 
UNION ALL
SELECT * FROM Second;

The resultset table will look like,

IDNAME
1abhi
2adam
2adam
3Chester

INTERSECT

Intersect operation is used to combine two SELECT statements, but it only retuns the records which are common from both SELECT statements. In case of Intersect the number of columns and datatype must be same.

NOTE: MySQL does not support INTERSECT operator.

intersect set operatoin in sql

Example of Intersect

The First table,

IDNAME
1abhi
2adam

The Second table,

IDNAME
2adam
3Chester

Intersect query will be,

SELECT * FROM First 
INTERSECT
SELECT * FROM Second;

The resultset table will look like

IDNAME
2adam

MINUS

The Minus operation combines results of two SELECT statements and return only those in the final result, which belongs to the first set of the result.

minus set operation in sql

Example of Minus

The First table,

IDNAME
1abhi
2adam

The Second table,

IDNAME
2adam
3Chester

Minus query will be,

SELECT * FROM First 
MINUS
SELECT * FROM Second;

The resultset table will look like,

IDNAME
1abhi

DISTINCT keyword

The distinct keyword is used with SELECT statement to retrieve unique values from the table. Distinct removes all the duplicate records while retrieving records from any table in the database.


Syntax for DISTINCT Keyword

SELECT DISTINCT column-name FROM table-name;

Example using DISTINCT Keyword

Consider the following Emp table. As you can see in the table below, there is employee name, along with employee salary and age.

In the table below, multiple employees have the same salary, so we will be using DISTINCT keyword to list down distinct salary amount, that is currently being paid to the employees.

eidnameagesalary
401Anu225000
402Shane298000
403Rohan3410000
404Scott4410000
405Tiger358000
SELECT DISTINCT salary FROM Emp;

The above query will return only the unique salary from Emp table.

salary
5000
8000
10000

SQL Group By Clause

Group by clause is used to group the results of a SELECT query based on one or more columns. It is also used with SQL functions to group the result from one or more tables.

Syntax for using Group by in a statement.

SELECT column_name, function(column_name)
FROM table_name 
WHERE condition 
GROUP BY column_name

Example of Group by in a Statement

Consider the following Emp table.

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott449000
405Tiger358000

Here we want to find name and age of employees grouped by their salaries or in other words, we will be grouping employees based on their salaries, hence, as a result, we will get a data set, with unique salaries listed, along side the first employee’s name and age to have that salary. Hope you are getting the point here!

group by is used to group different row of data together based on any one column.

SQL query for the above requirement will be,

SELECT name, age 
FROM Emp GROUP BY salary

Result will be,

nameage
Rohan34
Shane29
Anu22

Example of Group by in a Statement with WHERE clause

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott449000
405Tiger358000

SQL query will be,

SELECT name, salary 
FROM Emp 
WHERE age > 25
GROUP BY salary

Result will be.

namesalary
Rohan6000
Shane8000
Scott9000

You must remember that Group By clause will always come at the end of the SQL query, just like the Order by clause.

SELECT SQL Query

SELECT query is used to retrieve data from a table. It is the most used SQL query. We can retrieve complete table data, or partial by specifying conditions using the WHERE clause.


Syntax of SELECT query

SELECT query is used to retieve records from a table. We can specify the names of the columns which we want in the resultset.

SELECT 
    column_name1, 
    column_name2, 
    column_name3, 
    ...
    column_nameN 
    FROM table_name;

Time for an Example

Consider the following student table,

s_idnameageaddress
101Adam15Chennai
102Alex18Delhi
103Abhi17Banglore
104Ankit22Mumbai
SELECT s_id, name, age FROM student;

The above query will fetch information of s_idname and age columns of the student table and display them,

s_idnameage
101Adam15
102Alex18
103Abhi17
104Ankit22

As you can see the data from address column is absent, because we did not specif it in our SELECT query.


Select all records from a table

A special character asterisk * is used to address all the data(belonging to all columns) in a query. SELECT statement uses * character to retrieve all records from a table, for all the columns.

SELECT * FROM student;

The above query will show all the records of student table, that means it will show complete dataset of the table.

s_idnameageaddress
101Adam15Chennai
102Alex18Delhi
103Abhi17Banglore
104Ankit22Mumbai

Select a particular record based on a condition

We can use the WHERE clause to set a condition,

SELECT * FROM student WHERE name = 'Abhi';

The above query will return the following result,

103Abhi17Rohtak

Performing Simple Calculations using SELECT Query

Consider the following employee table.

eidnameagesalary
101Adam265000
102Ricky428000
103Abhi2510000
104Rohan225000

Here is our SELECT query,

SELECT eid, name, salary+3000  FROM employee;

The above command will display a new column in the result, with 3000 added into existing salaries of the employees.

eidnamesalary+3000
101Adam8000
102Ricky11000
103Abhi13000
104Rohan8000

So you can also perform simple mathematical operations on the data too using the SELECT query to fetch data from table.

Commit, Rollback and Savepoint SQL commandscommit commands

Transaction Control Language(TCL) commands are used to manage transactions in the database. These are used to manage the changes made to the data in a table by DML statements. It also allows statements to be grouped together into logical transactions.


COMMIT command

COMMIT command is used to permanently save any transaction into the database.

When we use any DML command like INSERTUPDATE 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 command to mark the changes as permanent.

Following is commit command’s syntax,

COMMIT;

ROLLBACK command

This command restores the database to last commited state. It is also used with SAVEPOINT command to jump to a savepoint in an ongoing transaction.

If we have used the UPDATE command to make some changes into the database, and realise that those changes were not required, then we can use the ROLLBACK command to rollback those changes, if they were not commited using the COMMIT command.

Following is rollback command’s syntax,

ROLLBACK TO savepoint_name;

SAVEPOINT command

SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that point whenever required.

Following is savepoint command’s syntax,

SAVEPOINT savepoint_name;

In short, using this command we can name the different states of our data in any table and then rollback to that state using the ROLLBACK command whenever required.


Using Savepoint and Rollback

Following is the table class,

idname
1Abhi
2Adam
4Alex

Lets use some SQL queries on the above table and see the results.

INSERT INTO class VALUES(5, 'Rahul');

COMMIT;

UPDATE class SET name = 'Abhijit' WHERE id = '5';

SAVEPOINT A;

INSERT INTO class VALUES(6, 'Chris');

SAVEPOINT B;

INSERT INTO class VALUES(7, 'Bravo');

SAVEPOINT C;

SELECT * FROM class;

The resultant table will look like,

idname
1Abhi
2Adam
4Alex
5Abhijit
6Chris
7Bravo

Now let’s use the ROLLBACK command to roll back the state of data to the savepoint B.

ROLLBACK TO B;

SELECT * FROM class;

Now our class table will look like,

idname
1Abhi
2Adam
4Alex
5Abhijit
6Chris

Now let’s again use the ROLLBACK command to roll back the state of data to the savepoint A

ROLLBACK TO A;

SELECT * FROM class;

Now the table will look like,

idname
1Abhi
2Adam
4Alex
5Abhijit

So now you know how the commands COMMITROLLBACK and SAVEPOINT works.

Using DELETE SQL command

When you ask any question in Studytonight’s Forum it gets saved into a table. And using the Delete option, you can even delete a question asked by you. How do you think that works? Yes, using the Delete DML command.

Let’s study about the syntax and the usage of the Delete command.


DELETE command

DELETE command is used to delete data from a table.

Following is its general syntax,

DELETE FROM table_name;

Let’s take a sample table student:

s_idnameage
101Adam15
102Alex18
103Abhi17

Delete all Records from a Table

DELETE FROM student;

The above command will delete all the records from the table student.


Delete a particular Record from a Table

In our student table if we want to delete a single record, we can use the WHERE clause to provide a condition in our DELETE statement.

DELETE FROM student WHERE s_id=103;

The above command will delete the record where s_id is 103 from the table student.

S_idS_Nameage
101Adam15
102Alex18

Isn’t DELETE same as TRUNCATE

TRUNCATE command is different from DELETE command. The delete command will delete all the rows from a table whereas truncate command not only deletes all the records stored in the table, but it also re-initializes the table(like a newly created table).

For eg: If you have a table with 10 rows and an auto_increment primary key, and if you use DELETE command to delete all the rows, it will delete all the rows, but will not re-initialize the primary key, hence if you will insert any row after using the DELETE command, the auto_increment primary key will start from 11. But in case of TRUNCATE command, primary key is re-initialized, and it will again start from 1.

Using UPDATE SQL command

Let’s take an example of a real-world problem. These days, Facebook provides an option for Editing your status update, how do you think it works? Yes, using the Update SQL command.

Let’s learn about the syntax and usage of the UPDATE command.


UPDATE command

UPDATE command is used to update any record of data in a table. Following is its general syntax,

UPDATE table_name SET column_name = new_value WHERE some_condition;

Lets take a sample table student,

student_idnameage
101Adam15
102Alex
103chris14
UPDATE student SET age=18 WHERE student_id=102;
S_idS_Nameage
101Adam15
102Alex18
103chris14

In the above statement, if we do not use the WHERE clause, then our update query will update age for all the columns of the table to 18.


Updating Multiple Columns

We can also update values of multiple columns using a single UPDATE statement.

UPDATE student SET name='Abhi', age=17 where s_id=103; 

The above command will update two columns of the record which has s_id 103.

s_idnameage
101Adam15
102Alex18
103Abhi17

UPDATE Command: Incrementing Integer Value

When we have to update any integer value in a table, then we can fetch and update the value in the table in a single statement.

For example, if we have to update the age column of student table every year for every student, then we can simply run the following UPDATE statement to perform the following operation:

UPDATE student SET age = age+1; 

As you can see, we have used age = age + 1 to increment the value of age by 1.