Division Operator in SQL

The division operator is used when we have to evaluate queries which contain the keyword ALL.

Some instances where division operator is used are:

  1. Which person has account in all the banks of a particular city?
  2. Which students have taken all the courses required to graduate?

In above specified problem statements, the description after the keyword 'all' defines a set which contains some elements and the final result contains those units which satisfy these requirements.

Another way how you can identify the usage of division operator is by using the logical implication of if...then. In context of the above two examples, we can see that the queries mean that,

  1. If there is a bank in that particular city, that person must have an account in that bank.
  2. If there is a course in the list of courses required to be graduated, that person must have taken that course.

Do not worry if you are not clear with all this new things right away, we will try to expain as we move on with this tutorial.

We shall see the second example, mentioned above, in detail.

Table 1: Course_Taken â†’ It consists of the names of Students against the courses that they have taken.

Student_NameCourse
RobertDatabases
RobertProgramming Languages
DavidDatabases
DavidOperating Systems
HannahProgramming Languages
HannahMachine Learning
TomOperating Systems

Table 2: Course_Required â†’ It consists of the courses that one is required to take in order to graduate.

Course
Databases
Programming Languages

Using Division Operator

So now, let’s try to find out the correct SQL query for getting results for the first requirement, which is:

Unfortunately, there is no direct way by which we can express the division operator. Let’s walk through the steps, to write the query for the division operator.

1. Find all the students

Create a set of all students that have taken courses. This can be done easily using the following command.

CREATE TABLE AllStudents AS SELECT DISTINCT Student_Name FROM Course_Taken

This command will return the table AllStudents, as the resultset:

Student_name
Robert
David
Hannah
Tom

2. Find all the students and the courses required to graduate

Next, we will create a set of students and the courses they need to graduate. We can express this in the form of Cartesian Product of AllStudents and Course_Required using the following command.

CREATE table StudentsAndRequired AS 
SELECT AllStudents.Student_Name, Course_Required.Course
FROM AllStudents, Course_Required

Now the new resultset – table StudentsAndRequired will be:

Student_NameCourse
RobertDatabases
RobertProgramming Languages
DavidDatabases
DavidProgramming Languages
HannahDatabases
HannahProgramming Languages
TomDatabases
TomProgramming Languages

3. Find all the students and the required courses they have not taken

Here, we are taking our first step for finding the students who cannot graduate. The idea is to simply find the students who have not taken certain courses that are required for graduation and hence they wont be able to graduate. This is simply all those tuples/rows which are present in StudentsAndRequired and not present in Course_Taken.

CREATE  table StudentsAndNotTaken AS 
SELECT * FROM StudentsAndRequired WHERE NOT EXISTS 
(Select * FROM Course_Taken WHERE StudentsAndRequired.Student_Name = Course_Taken.Student_Name 
AND StudentsAndRequired.Course = Course_Taken.Course)

The table StudentsAndNotTaken comes out to be:

Student_NameCourse
DavidProgramming Languages
HannahDatabases
TomDatabases
TomProgramming Languages

4. Find all students who cannot graduate

All the students who are present in the table StudentsAndNotTaken are the ones who cannot graduate. Therefore, we can find the students who cannot graduate as,

CREATE table CannotGraduate AS SELECT DISTINCT Student_Name FROM StudentsAndNotTaken
Student_name
David
Hannah
Tom

5. Find all students who can graduate

The students who can graduate are simply those who are present in AllStudents but not in CannotGraduate. This can be done by the following query:

CREATE Table CanGraduate AS SELECT * FROM AllStudents 
WHERE NOT EXISTS 
(SELECT * FROM CannotGraduate WHERE 
    CannotGraduate.Student_name = AllStudents.Student_name)

The results will be as follows:

Student_name
Robert

Hence we just learned, how different steps can lead us to the final answer. Now let us see how to write all these 5 steps in one single query so that we do not have to create so many tables.

SELECT DISTINCT  x.Student_Name FROM Course_Taken AS x WHERE NOT 
EXISTS(SELECT * FROM Course_Required AS y WHERE NOT 
EXISTS(SELECT * FROM Course_Taken AS z 
    WHERE z.Student_name = x.Student_name 
    AND z.Course = y.Course ))
Student_name
Robert

This gives us the same result just like the 5 steps above.

What is an SQL Sequence?

Sequence is a feature supported by some database systems to produce unique values on demand. Some DBMS like MySQL supports AUTO_INCREMENT in place of Sequence.

AUTO_INCREMENT is applied on columns, it automatically increments the column value by 1 each time a new record is inserted into the table.

Sequence is also some what similar to AUTO_INCREMENT but it has some additional features too.


Creating a Sequence

Syntax to create a sequence is,

CREATE SEQUENCE sequence-name
    START WITH initial-value
    INCREMENT BY increment-value
    MAXVALUE maximum-value
    CYCLE | NOCYCLE;
  • The initial-value specifies the starting value for the Sequence.
  • The increment-value is the value by which sequence will be incremented.
  • The maximum-value specifies the upper limit or the maximum value upto which sequence will increment itself.
  • The keyword CYCLE specifies that if the maximum value exceeds the set limit, sequence will restart its cycle from the begining.
  • And, NO CYCLE specifies that if sequence exceeds MAXVALUE value, an error will be thrown.

Using Sequence in SQL Query

Let’s start by creating a sequence, which will start from 1, increment by 1 with a maximum value of 999.

CREATE SEQUENCE seq_1
START WITH 1
INCREMENT BY 1
MAXVALUE 999
CYCLE;

Now let’s use the sequence that we just created above.

Below we have a class table,

IDNAME
1abhi
2adam
4alex

The SQL query will be,

INSERT INTO class VALUE(seq_1.nextval, 'anu');

Resultset table will look like,

IDNAME
1abhi
2adam
4alex
1anu

Once you use nextval the sequence will increment even if you don’t Insert any record into the table.

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

SQL Alias – AS Keyword

Alias is used to give an alias name to a table or a column, which can be a resultset table too. This is quite useful in case of large or complex queries. Alias is mainly used for giving a short alias name for a column or a table with complex names.

Syntax of Alias for table names,

SELECT column-name FROM table-name AS alias-name

Following is an SQL query using alias,

SELECT * FROM Employee_detail AS ed;

Syntax for defining alias for columns will be like,

SELECT column-name AS alias-name FROM table-name;

Example using alias for columns,

SELECT customer_id AS cid FROM Emp;

Example of Alias in SQL Query

Consider the following two tables,

The class table,

IDName
1abhi
2adam
3alex
4anu
5ashish

and the class_info table,

IDAddress
1DELHI
2MUMBAI
3CHENNAI
7NOIDA
8PANIPAT

Below is the Query to fetch data from both the tables using SQL Alias,

SELECT C.id, C.Name, Ci.Address from Class AS C, Class_info AS Ci where C.id = Ci.id;

and the resultset table will look like,

IDNameAddress
1abhiDELHI
2adamMUMBAI
3alexCHENNAI

SQL Alias seems to be quite a simple feature of SQL, but it is highly useful when you are working with more than 3 tables and have to use JOIN on them.

SQL AND & OR operator

The AND and OR operators are used with the WHERE clause to make more precise conditions for fetching data from database by combining more than one condition together.


AND operator

AND operator is used to set multiple conditions with the WHERE clause, alongside, SELECTUPDATE or DELETE SQL queries.


Example of AND operator

Consider the following Emp table

eidnameagesalary
401Anu225000
402Shane298000
403Rohan3412000
404Scott4410000
405Tiger359000
SELECT * FROM Emp WHERE salary < 10000 AND age > 25

The above query will return records where salary is less than 10000 and age greater than 25. Hope you get the concept here. We have used the AND operator to specify two conditions with WHERE clause.

eidnameagesalary
402Shane298000
405Tiger359000

OR operator

OR operator is also used to combine multiple conditions with WHERE clause. The only difference between AND and OR is their behaviour.

When we use AND to combine two or more than two conditions, records satisfying all the specified conditions will be there in the result.

But in case of OR operator, atleast one condition from the conditions specified must be satisfied by any record to be in the resultset.


Example of OR operator

Consider the following Emp table

eidnameagesalary
401Anu225000
402Shane298000
403Rohan3412000
404Scott4410000
405Tiger359000
SELECT * FROM Emp WHERE salary > 10000 OR age > 25 

The above query will return records where either salary is greater than 10000 or age is greater than 25.

402Shane298000
403Rohan3412000
404Scott4410000
405Tiger359000

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.