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 JOIN

SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of data. It is used for combining column from two or more tables by using values common to both tables.

JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required condition for joining table, is (n-1) where n, is number of tables. A table can also join to itself, which is known as, Self Join.


Types of JOIN

Following are the types of JOIN that we can use in SQL:

  • Inner
  • Outer
  • Left
  • Right

Cross JOIN or Cartesian Product

This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a table which consists of records which combines each row from the first table with each row of the second table.

Cross JOIN Syntax is,

SELECT column-name-list
FROM 
table-name1 CROSS JOIN table-name2;

Example of Cross JOIN

Following is the class table,

IDNAME
1abhi
2adam
4alex

and the class_info table,

IDAddress
1DELHI
2MUMBAI
3CHENNAI

Cross JOIN query will be,

SELECT * FROM 
class CROSS JOIN class_info;

The resultset table will look like,

IDNAMEIDAddress
1abhi1DELHI
2adam1DELHI
4alex1DELHI
1abhi2MUMBAI
2adam2MUMBAI
4alex2MUMBAI
1abhi3CHENNAI
2adam3CHENNAI
4alex3CHENNAI

As you can see, this join returns the cross product of all the records present in both the tables.


INNER Join or EQUI Join

This is a simple JOIN in which the result is based on matched data as per the equality condition specified in the SQL query.

Inner Join Syntax is,

SELECT column-name-list FROM 
table-name1 INNER JOIN table-name2 
WHERE table-name1.column-name = table-name2.column-name;

Example of INNER JOIN

Consider a class table,

IDNAME
1abhi
2adam
3alex
4anu

and the class_info table,

IDAddress
1DELHI
2MUMBAI
3CHENNAI

Inner JOIN query will be,

SELECT * from class INNER JOIN class_info where class.id = class_info.id;

The resultset table will look like,

IDNAMEIDAddress
1abhi1DELHI
2adam2MUMBAI
3alex3CHENNAI

Natural JOIN

Natural Join is a type of Inner join which is based on column having same name and same datatype present in both the tables to be joined.

The syntax for Natural Join is,

SELECT * FROM 
table-name1 NATURAL JOIN table-name2;

Example of Natural JOIN

Here is the class table,

IDNAME
1abhi
2adam
3alex
4anu

and the class_info table,

IDAddress
1DELHI
2MUMBAI
3CHENNAI

Natural join query will be,

SELECT * from class NATURAL JOIN class_info; 

The resultset table will look like,

IDNAMEAddress
1abhiDELHI
2adamMUMBAI
3alexCHENNAI

In the above example, both the tables being joined have ID column(same name and same datatype), hence the records for which value of ID matches in both the tables will be the result of Natural Join of these two tables.


OUTER JOIN

Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

  1. Left Outer Join
  2. Right Outer Join
  3. Full Outer Join

LEFT Outer Join

The left outer join returns a resultset table with the matched data from the two tables and then the remaining rows of the left table and null from the right table’s columns.

Syntax for Left Outer Join is,

SELECT column-name-list FROM 
table-name1 LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;

To specify a condition, we use the ON keyword with Outer Join.

Left outer Join Syntax for Oracle is,

SELECT column-name-list FROM 
table-name1, table-name2 on table-name1.column-name = table-name2.column-name(+);

Example of Left Outer Join

Here is the class table,

IDNAME
1abhi
2adam
3alex
4anu
5ashish

and the class_info table,

IDAddress
1DELHI
2MUMBAI
3CHENNAI
7NOIDA
8PANIPAT

Left Outer Join query will be,

SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id = class_info.id);

The resultset table will look like,

IDNAMEIDAddress
1abhi1DELHI
2adam2MUMBAI
3alex3CHENNAI
4anunullnull
5ashishnullnull

RIGHT Outer Join

The right outer join returns a resultset table with the matched data from the two tables being joined, then the remaining rows of the right table and null for the remaining left table’s columns.

Syntax for Right Outer Join is,

SELECT column-name-list FROM 
table-name1 RIGHT OUTER JOIN table-name2 
ON table-name1.column-name = table-name2.column-name;

Right outer Join Syntax for Oracle is,

SELECT column-name-list FROM 
table-name1, table-name2 
ON table-name1.column-name(+) = table-name2.column-name;

Example of Right Outer Join

Once again the class table,

IDNAME
1abhi
2adam
3alex
4anu
5ashish

and the class_info table,

IDAddress
1DELHI
2MUMBAI
3CHENNAI
7NOIDA
8PANIPAT

Right Outer Join query will be,

SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id = class_info.id);

The resultant table will look like,

IDNAMEIDAddress
1abhi1DELHI
2adam2MUMBAI
3alex3CHENNAI
nullnull7NOIDA
nullnull8PANIPAT

Full Outer Join

The full outer join returns a resultset table with the matched data of two table then remaining rows of both left table and then the right table.

Syntax of Full Outer Join is,

SELECT column-name-list FROM 
table-name1 FULL OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;

Example of Full outer join is,

The class table,

IDNAME
1abhi
2adam
3alex
4anu
5ashish

and the class_info table,

IDAddress
1DELHI
2MUMBAI
3CHENNAI
7NOIDA
8PANIPAT

Full Outer Join query will be like,

SELECT * FROM class FULL OUTER JOIN class_info ON (class.id = class_info.id);

The resultset table will look like,

IDNAMEIDAddress
1abhi1DELHI
2adam2MUMBAI
3alex3CHENNAI
4anunullnull
5ashishnullnull
nullnull7NOIDA
nullnull8PANIPAT

What are SQL Functions?

SQL provides many built-in functions to perform operations on data. These functions are useful while performing mathematical calculations, string concatenations, sub-strings etc. SQL functions are divided into two categories,

  1. Aggregate Functions
  2. Scalar Functions

Aggregate Functions

These functions return a single value after performing calculations on a group of values. Following are some of the frequently used Aggregrate functions.


AVG() Function

Average returns average value after calculating it from values in a numeric column.

Its general syntax is,

SELECT AVG(column_name) FROM table_name

Using AVG() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to find average salary will be,

SELECT avg(salary) from Emp;

Result of the above query will be,

avg(salary)
8200

COUNT() Function

Count returns the number of rows present in the table either based on some condition or without condition.

Its general syntax is,

SELECT COUNT(column_name) FROM table-name

Using COUNT() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to count employees, satisfying specified condition is,

SELECT COUNT(name) FROM Emp WHERE salary = 8000;

Result of the above query will be,

count(name)
2

Example of COUNT(distinct)

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query is,

SELECT COUNT(DISTINCT salary) FROM emp;

Result of the above query will be,

count(distinct salary)
4

FIRST() Function

First function returns first value of a selected column

Syntax for FIRST function is,

SELECT FIRST(column_name) FROM table-name;

Using FIRST() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query will be,

SELECT FIRST(salary) FROM Emp;

and the result will be,

first(salary)
9000

LAST() Function

LAST function returns the return last value of the selected column.

Syntax of LAST function is,

SELECT LAST(column_name) FROM table-name;

Using LAST() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query will be,

SELECT LAST(salary) FROM emp;

Result of the above query will be,

last(salary)
8000

MAX() Function

MAX function returns maximum value from selected column of the table.

Syntax of MAX function is,

SELECT MAX(column_name) from table-name;

Using MAX() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to find the Maximum salary will be,

SELECT MAX(salary) FROM emp;

Result of the above query will be,

MAX(salary)
10000

MIN() Function

MIN function returns minimum value from a selected column of the table.

Syntax for MIN function is,

SELECT MIN(column_name) from table-name;

Using MIN() function

Consider the following Emp table,

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to find minimum salary is,

SELECT MIN(salary) FROM emp;

Result will be,

MIN(salary)
6000

SUM() Function

SUM function returns total sum of a selected columns numeric values.

Syntax for SUM is,

SELECT SUM(column_name) from table-name;

Using SUM() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to find sum of salaries will be,

SELECT SUM(salary) FROM emp;

Result of above query is,

SUM(salary)
41000

Scalar Functions

Scalar functions return a single value from an input value. Following are some frequently used Scalar Functions in SQL.


UCASE() Function

UCASE function is used to convert value of string column to Uppercase characters.

Syntax of UCASE,

SELECT UCASE(column_name) from table-name;

Using UCASE() function

Consider the following Emp table

eidnameagesalary
401anu229000
402shane298000
403rohan346000
404scott4410000
405Tiger358000

SQL query for using UCASE is,

SELECT UCASE(name) FROM emp;

Result is,

UCASE(name)
ANU
SHANE
ROHAN
SCOTT
TIGER

LCASE() Function

LCASE function is used to convert value of string columns to Lowecase characters.

Syntax for LCASE is,

SELECT LCASE(column_name) FROM table-name;

Using LCASE() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404SCOTT4410000
405Tiger358000

SQL query for converting string value to Lower case is,

SELECT LCASE(name) FROM emp;

Result will be,

LCASE(name)
anu
shane
rohan
scott
tiger

MID() Function

MID function is used to extract substrings from column values of string type in a table.

Syntax for MID function is,

SELECT MID(column_name, start, length) from table-name;

Using MID() function

Consider the following Emp table

eidnameagesalary
401anu229000
402shane298000
403rohan346000
404scott4410000
405Tiger358000

SQL query will be,

SELECT MID(name,2,2) FROM emp;

Result will come out to be,

MID(name,2,2)
nu
ha
oh
co
ig

ROUND() Function

ROUND function is used to round a numeric field to number of nearest integer. It is used on Decimal point values.

Syntax of Round function is,

SELECT ROUND(column_name, decimals) from table-name;

Using ROUND() function

Consider the following Emp table

eidnameagesalary
401anu229000.67
402shane298000.98
403rohan346000.45
404scott4410000
405Tiger358000.01

SQL query is,

SELECT ROUND(salary) from emp;

Result will be,

ROUND(salary)
9001
8001
6000
10000
8000

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