Category: Operators and Clauses

  • Alias Syntax

    You can rename a table or a column in a database temporarily by giving them another pseudo name. This pseudo name is known as Alias. The use of aliases is to address a specific table or a column in an SQL statement without changing their original name in the database. Aliases are created with the AS keyword.

    Aliases can be especially useful when working with complex queries involving multiple tables or columns with similar names. By assigning temporary names to these tables or columns, you can make your SQL query more readable and easier to understand.

    The SQL Aliasing

    Aliases are used to address database tables with a shorter or more meaningful name within an SQL query. The basic syntax of a table alias is as follows.

    SELECT column1, column2....FROM table_name AS alias_name;

    Example

    Assume we have created a table with name CUSTOMERS in MySQL database using CREATE TABLE statement as shown below −

    CREATETABLE CUSTOMERS (
       ID INTNOTNULL,
       NAME VARCHAR(20)NOTNULL,
       AGE INTNOTNULL,
       ADDRESS CHAR(25),
       SALARY DECIMAL(18,2),PRIMARYKEY(ID));

    Following query inserts values into this table using the INSERT statement −

    INSERTINTO CUSTOMERS VALUES(1,'Ramesh',32,'Ahmedabad',2000.00),(2,'Khilan',25,'Delhi',1500.00),(3,'Kaushik',23,'Kota',2000.00),(4,'Chaitali',25,'Mumbai',6500.00),(5,'Hardik',27,'Bhopal',8500.00),(6,'Komal',22,'Hyderabad',4500.00),(7,'Muffy',24,'Indore',10000.00);

    The CUSTOMERS table obtained is as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    2Khilan25Delhi1500.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    5Hardik27Bhopal8500.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    Now, we are creating the second table ORDERS using CREATE TABLE statement as shown below −

    CREATETABLE ORDERS (
       OID INTNOTNULL,
       DATES DATETIMENOTNULL,
       CUSTOMER_ID INTNOTNULL,
       AMOUNT INTNOTNULL,PRIMARYKEY(OID));

    Following query inserts values into this table using the INSERT statement −

    INSERTINTO ORDERS VALUES(102,'2009-10-08 00:00:00',3,3000),(100,'2009-10-08 00:00:00',3,1500),(101,'2009-11-20 00:00:00',2,1560),(103,'2008-05-20 00:00:00',4,2060);

    The ORDERS table obtained is as shown below −

    OIDDATECUSTOMER_IDAMOUNT
    1022009-10-08 00:00:0033000.00
    1002009-10-08 00:00:0031500.00
    1012009-11-20 00:00:0021560.00
    1032008-05-20 00:00:0042060.00

    Now, the following query shows the usage of a table alias. The CUSTOMERS table is aliased as ‘C’ and the ORDERS table is aliased as ‘O’ −

    SELECT C.ID, C.NAME, C.AGE, O.AMOUNT 
    FROM CUSTOMERS AS C, ORDERS AS O
    WHERE  C.ID = O.CUSTOMER_ID;

    Output

    This would produce the following result −

    IDNAMEAGEAMOUNT
    3Kaushik233000.00
    3Kaushik231500.00
    2Khilan251560.00
    4Chaitali252060.00

    Aliasing Column Names

    We can also use an alias for a column name in SQL to give it a different name in the result set of a query. The basic syntax of a column alias is as follows −

    SELECT column_name AS alias_name
    FROM table_name;

    Example

    Following is the usage of a column alias. Here, the NAME column is aliased as ‘CUSTOMER_NAME’ −

    SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME
    FROM CUSTOMERS;

    Output

    This would produce the following result −

    CUSTOMER_IDCUSTOMER_NAME
    1Ramesh
    2Khilan
    3Kaushik
    4Chaitali
    5Hardik
    6Komal
    7Muffy

    Aliasing with Self Join

    The SQL Self Join is used to join a table to itself as if the table were two tables. During this process, we need to use alias for one of the tables with a temporary name to avoid misunderstandings. This renaming is done using aliases.

    Syntax

    Following is the syntax for performing a self-join with aliases −

    SELECT column_name(s)FROM my_table a, my_table b
    ON a.join_column = b.join_column;

    Example

    Now, let us join the CUSTOMERS table to itself using the following Self Join query. Our aim is to establish a relationship among customers on the basis of their earnings. In here, we are using aliases with column names as well as with the table names −

    SELECT 
       a.ID, b.NAME as EARNS_HIGHER, 
       a.NAME as EARNS_LESS, 
       a.SALARY as LOWER_SALARY
    FROM CUSTOMERS a, CUSTOMERS b
    WHERE a.SALARY 
    Output
    Output of the above query isas follows −
    
    
    ID
    EARNS_HIGHER
    EARNS_LESS
    LOWER_SALARY
    
    
    2
    Ramesh
    Khilan
    1500.002
    Kaushik
    Khilan
    1500.006
    Chaitali
    Komal
    4500.003
    Chaitali
    Kaushik
    2000.002
    Chaitali
    Khilan
    1500.001
    Chaitali
    Ramesh
    2000.006
    Hardik
    Komal
    4500.004
    Hardik
    Chaitali
    6500.003
    Hardik
    Kaushik
    2000.002
    Hardik
    Khilan
    1500.001
    Hardik
    Ramesh
    2000.003
    Komal
    Kaushik
    2000.002
    Komal
    Khilan
    1500.001
    Komal
    Ramesh
    2000.006
    Muffy
    Komal
    4500.005
    Muffy
    Hardik
    8500.004
    Muffy
    Chaitali
    6500.003
    Muffy
    Kaushik
    2000.002
    Muffy
    Khilan
    1500.001
    Muffy
    Ramesh
    2000.00
  • EXCEPT

    The SQL EXCEPT Operator

    The EXCEPT operator in SQL is used to retrieve all the unique records from the left operand (query), except the records that are present in the result set of the right operand (query).

    In other words, this operator compares the distinct values of the left query with the result set of the right query. If a value from the left query is found in the result set of the right query, it is excluded from the final result.

    For better understanding consider two tables with records as shown in the following image −

    Except

    If we perform the EXCEPT operator on the above two tables to retrieve the names, it will display the distinct records only from the first table which are not in common with the records of the second table.

    Here, “Dev” is common in both tables. So, the EXECPT operator will eliminate it and retrieves only “Sara” and “Jay” as output.

    MySQL database does not support the EXCEPT operator. Instead of this, we can use the DISTINCT keyword along with the LEFT JOIN clause to retrieve distinct values from the left table.

    Syntax

    Following is the SQL syntax of the EXCEPT operator in Microsoft SQL server −

    SELECT column1, column2,..., columnN
    FROM table1, table2,..., tableN
    [Conditions]//optionalEXCEPTSELECT column1, column2,..., columnN
    FROM table1, table2,..., tableN
    [Conditions]//optional

    The number and order of columns in both SELECT statements should be the same.

    Example

    First of all, let us create a table named STUDENTS using the following query −

    CREATETABLE STUDENTS(
       ID INTNOTNULL, 
       NAME VARCHAR(20)NOTNULL, 
       SUBJECT VARCHAR(20)NOTNULL, 
       AGE INTNOTNULL, 
       HOBBY VARCHAR(20)NOTNULL,PRIMARYKEY(ID));

    Let’s insert some values into the table using the following query −

    INSERTINTO STUDENTS VALUES(1,'Naina','Maths',24,'Cricket'),(2,'Varun','Physics',26,'Football'),(3,'Dev','Maths',23,'Cricket'),(4,'Priya','Physics',25,'Cricket'),(5,'Aditya','Chemistry',21,'Cricket'),(6,'Kalyan','Maths',30,'Football'),(7,'Aditya','Chemistry',21,'Cricket'),(8,'Kalyan','Chemistry',32,'Cricket');

    The table produced is as shown below −

    IDNAMESUBJECTAGEHOBBY
    1NainaMathematics24Cricket
    2VarunPhysics26Football
    3DevMathematics23Cricket
    4PriyaPhysics25Cricket
    5AdityaChemistry21Cricket
    6KalyanMathematics30Football
    7AdityaChemistry21Cricket
    8KalyanChemistry32Cricket

    Now, let us create another table named STUDENTS_HOBBY using the following query −

    CREATETABLE STUDENTS_HOBBY(
       ID INTNOTNULL, 
       NAME VARCHAR(20)NOTNULL, 
       HOBBY VARCHAR(20)NOTNULL, 
       AGE INTNOTNULL,PRIMARYKEY(ID));

    Once the table is created, let us insert some values to the table using the query below −

    INSERTINTO STUDENTS_HOBBY VALUES(1,'Vijay','Cricket',18),(2,'Varun','Football',26),(3,'Surya','Cricket',19),(4,'Karthik','Cricket',25),(5,'Sunny','Football',26),(6,'Dev','Cricket',23);

    The table created is as follows −

    IDNAMEHOBBYAGE
    1VijayCricket18
    2VarunFootball26
    3SuryaCricket19
    4KarthikCricket25
    5SunnyFootball26
    6DevCricket23

    Now, let us perform the except operation on the above two tables −

    SELECT NAME, HOBBY, AGE FROM STUDENTS
    EXCEPTSELECT NAME, HOBBY, AGE FROM STUDENTS_HOBBY;

    Output

    Output of the above query is as shown below −

    NAMEHOBBYAGE
    AdityaCricket21
    KalyanCricket32
    KalyanFootball30
    NainaCricket24
    PriyaCricket25

    EXCEPT with BETWEEN Operator

    We can use the EXCEPT operator with the BETWEEN operator in SQL to exclude records that fall within a specified range.

    Example

    In the following SQL query, we are retrieving the records of students aged between 20 and 30 from the STUDENTS table, excluding those who are also aged between 20 and 30 from the STUDENTS_HOBBY table −

    SELECT NAME, HOBBY, AGE
    FROM STUDENTS
    WHERE AGE BETWEEN20AND30EXCEPTSELECT NAME, HOBBY, AGE 
    FROM STUDENTS_HOBBY
    WHERE AGE BETWEEN20AND30

    Output

    When we execute the program query, the output is obtained as follows −

    NAMEHOBBYAGE
    AdityaCricket21
    KalyanFootball30
    NainaCricket24
    PriyaCricket25

    Except with IN Operator

    The IN operator is used to filter a result set based on a list of specified values. We can also use the EXCEPT operator with the IN operator in SQL to exclude records that matches values in the specified list.

    Example

    Here, we are retrieving the records of students with Cricket as a hobby, from the STUDENTS table, excluding those who also have Cricket as hobby from the STUDENTS_HOBBY table −

    SELECT NAME, HOBBY, AGE FROM STUDENTS
    WHERE HOBBY IN('Cricket')EXCEPTSELECT NAME, HOBBY, AGE FROM STUDENTS_HOBBY
    WHERE HOBBY IN('Cricket')

    Output

    Following is the output of the above query −

    NAMEHOBBYAGE
    AdityaCricket21
    KalyanCricket32
    NainaCricket24
    PriyaCricket25

    EXCEPT with LIKE Operator

    The LIKE operator is used to perform pattern matching on a string. The EXCEPT operator can also be used with the LIKE operator in SQL to exclude rows that matches with the specified pattern.

    Example

    In here, we are retrieving records from the STUDENTS table where the values in the HOBBY column starts with ‘F’, while excluding similar rows from the STUDENTS_HOBBY table −

    SELECT ID, NAME, HOBBY, AGE FROM STUDENTS
    WHERE HOBBY LIKE'F%'EXCEPTSELECT ID, NAME, HOBBY, AGE FROM STUDENTS_HOBBY
    WHERE HOBBY LIKE'F%';

    Output

    The output for the above query is produced as given below −

    IDNAMEHOBBYAGE
    6KalyanFootball30

  • INTERSECT

    In mathematical set theory, the intersection of two sets is a collection of values that are common to both sets.

    In real-time scenarios, there will be a huge number of tables in a database that contains information. The user may find it challenging to gather common information from various tables. So we use the INTERSECT operator to accomplish that. It helps to retrieve the common data from various tables.

    The SQL INTERSECT Operator

    The INTERSECT operator in SQL is used to retrieve the records that are identical/common between the result sets of two or more tables.

    Let us consider the below tables as an example to get a better understanding −

    Intersect

    If we perform the intersection operation on both tables described above using the INTERSECT operator, it returns the common records which are Dev and Aarohi.

    MySQL database does not support the INTERSECT operator. Instead of this, we can use the DISTINCT operator along with the INNER JOIN clause to retrieve common records from two or more tables.

    Syntax

    Following is the SQL syntax of INTERSECT operator in Microsoft SQL Server −

    SELECT column1, column2,..., columnN
    FROM table1, table2,..., tableN
    INTERSECTSELECT column1, column2,..., columnN
    FROM table1, table2,..., tableN
    

    There are some mandatory rules for INTERSECT operations such as the number of columns, data types, and other columns must be the same in both SELECT statements for the INTERSECT operator to work correctly.

    Example

    First of all, let us create a table named STUDENTS using the following query −

    CREATETABLE STUDENTS(
       ID INTNOTNULL, 
       NAME VARCHAR(20)NOTNULL, 
       SUBJECT VARCHAR(20)NOTNULL, 
       AGE INTNOTNULL, 
       HOBBY VARCHAR(20)NOTNULL,PRIMARYKEY(ID));

    Let’s insert some values into the table using the following query −

    INSERTINTO STUDENTS VALUES(1,'Naina','Maths',24,'Cricket'),(2,'Varun','Physics',26,'Football'),(3,'Dev','Maths',23,'Cricket'),(4,'Priya','Physics',25,'Cricket'),(5,'Aditya','Chemistry',21,'Cricket'),(6,'Kalyan','Maths',30,'Football');

    The table produced is as shown below −

    IDNAMESUBJECTAGEHOBBY
    1NainaMathematics24Cricket
    2VarunPhysics26Football
    3DevMathematics23Cricket
    4PriyaPhysics25Cricket
    5AdithyaChemistry21Cricket
    6KalyanMathematics30Football

    Now, let us create another table named STUDENTS_HOBBY using the following query −

    CREATETABLE STUDENTS_HOBBY(
       ID INTNOTNULL, 
       NAME VARCHAR(20)NOTNULL, 
       HOBBY VARCHAR(20)NOTNULL, 
       AGE INTNOTNULL,PRIMARYKEY(ID));

    Once the table is created, let us insert some values to the table using the query below −

    INSERTINTO STUDENTS_HOBBY VALUES(1,'Vijay','Cricket',18),(2,'Varun','Football',26),(3,'Surya','Cricket',19),(4,'Karthik','Cricket',25),(5,'Sunny','Football',26),(6,'Dev','Cricket',23);

    The table created is as follows −

    IDNAMEHOBBYAGE
    1VijayCricket18
    2VarunFootball26
    3SuryaCricket19
    4KarthikCricket25
    5SunnyFootball26
    6DevCricket23

    Now, we are retrieving the common records from both the tables using the following query −

    SELECT NAME, AGE, HOBBY FROM STUDENTS_HOBBY
    INTERSECTSELECT NAME, AGE, HOBBY FROM STUDENTS;

    Output

    When we execute the above query, the output is obtained as follows −

    NAMEAGEHOBBY
    Dev23Cricket
    Varun26Football

    INTERSECT with BETWEEN Operator

    We can use the INTERSECT operator with the BETWEEN operator in SQL to find records that fall within a specified range.

    Example

    Now, let us retrieve the name, age, and hobby of students aged between 25 and 30 from both the ‘STUDENTS’ and ‘STUDENTS_HOBBY’ tables, returning only the common rows within the specified age range −

    SELECT NAME, AGE, HOBBY FROM STUDENTS_HOBBY
    WHERE AGE BETWEEN25AND30INTERSECTSELECT NAME, AGE, HOBBY FROM STUDENTS
    WHERE AGE BETWEEN20AND30;

    Output

    The output for the above query is produced as given below −

    NAMEAGEHOBBY
    Varun26Football

    INTERSECT with IN Operator

    We can also use the INTERSECT operator with the IN operator in SQL to find the common records that exists in the specified list of values. The IN operator is used to filter a result set based on a list of specified values.

    Example

    The following SQL query returns the name, age, and hobby of students who have ‘Cricket’ as their hobby in both ‘STUDENTS’ and ‘STUDENTS_HOBBY’ tables −

    SELECT NAME, AGE, HOBBY FROM STUDENTS_HOBBY
    WHERE HOBBY IN('Cricket')INTERSECTSELECT NAME, AGE, HOBBY FROM STUDENTS
    WHERE HOBBY IN('Cricket');

    Output

    When we execute the above query, the output is obtained as follows −

    NAMEAGEHOBBY
    Dev23Cricket

    INTERSECT with LIKE Operator

    The LIKE operator is used to perform pattern matching on a string. The INTERSECT operator can also be used with the LIKE operator in SQL to find the common rows that matches with the specified pattern.

    Example

    The query below retrieves the names that start with ‘V’ using the wildcard ‘%’ in the LIKE operator from the common names of both tables −

    SELECT NAME, AGE, HOBBY FROM STUDENTS_HOBBY
    WHERE NAME LIKE'v%'INTERSECTSELECT NAME, AGE, HOBBY FROM STUDENTS
    WHERE NAME LIKE'v%';

    Output

    The output for the above query is produced as given below −

    NAMEAGEHOBBY
    Varun26Football

  • UNION vs UNION ALL

    UNION and UNION ALL operators are just the SQL implementation of algebraic set operators. Both of them are used to retrieve the rows from multiple tables and return them as one single table. The difference between these two operators is that UNION only returns distinct rows while UNION ALL returns all the rows present in the tables.

    However, for these operators to work on these tables, they need to follow the conditions given below −

    • The tables to be combined must have the same number of columns with the same datatype.
    • The number of rows need not be the same.

    Once these criterion are met, UNION or UNION ALL operator returns the rows from multiple tables as a resultant table.

    Column names of first table will become column names of the resultant table, and contents of second table will be merged into resultant columns of same data type.

    What is UNION?

    UNION is a type of operator/clause in SQL, that works similar to the union operator in relational algebra. It just combines the information from multiple tables that are union compatible.

    Only distinct rows from the tables are added to the resultant table, as UNION automatically eliminates all the duplicate records.

    Syntax

    Following is the syntax of UNION operator in SQL −

    SELECT*FROM table1
    UNIONSELECT*FROM table2;

    Example

    Let us first create two tables COURSES_PICKED and EXTRA_COURSES_PICKED with the same number of columns having the same data types.

    Create table COURSES_PICKED using the following query −

    CREATETABLE COURSES_PICKED(
       STUDENT_ID INTNOTNULL, 
       STUDENT_NAME VARCHAR(30)NOTNULL, 
       COURSE_NAME VARCHAR(30)NOTNULL);

    Insert values into the COURSES_PICKED table with the help of the query given below −

    INSERTINTO COURSES_PICKED VALUES(1,'JOHN','ENGLISH'),(2,'ROBERT','COMPUTER SCIENCE'),(3,'SASHA','COMMUNICATIONS'),(4,'JULIAN','MATHEMATICS');

    The table will be displayed as shown below −

    STUDENT_IDSTUDENT_NAMECOURSE_NAME
    1JOHNENGLISH
    2ROBERTCOMPUTER SCIENCE
    3SASHACOMMUNICATIONS
    4JULIANMATHEMATICS

    Now, let us create another table EXTRA_COURSES_PICKED using the following query −

    CREATETABLE EXTRA_COURSES_PICKED(
       STUDENT_ID INTNOTNULL, 
       STUDENT_NAME VARCHAR(30)NOTNULL, 
       EXTRA_COURSE_NAME VARCHAR(30)NOTNULL);

    Following is the query to insert values into the “EXTRA_COURSES_PICKED” table −

    INSERTINTO EXTRA_COURSES_PICKED VALUES(1,'JOHN','PHYSICAL EDUCATION'),(2,'ROBERT','GYM'),(3,'SASHA','FILM'),(4,'JULIAN','MATHEMATICS');

    The table will be created as shown below −

    STUDENT_IDSTUDENT_NAMECOURSES_PICKED
    1JOHNPHYSICAL EDUCATION
    2ROBERTGYM
    3SASHAFILM
    4JULIANMATHEMATICS

    Now, let us combine both of these tables using the UNION query as follows −

    SELECT*FROM COURSES_PICKED
    UNIONSELECT*FROM EXTRA_COURSES_PICKED;

    Output

    The resultant table obtained after performing the UNION operation is as follows −

    STUDENT_IDSTUDENT_NAMECOURSE_NAME
    1JOHNENGLISH
    2ROBERTCOMPUTER SCIENCE
    3SASHACOMMUNICATIONS
    4JULIANMATHEMATICS
    1JOHNPHYSICAL EDUCATION
    2ROBERTGYM
    3SASHAFILM

    What is UNION ALL?

    UNION ALL is also an operator/clause in SQL, that is used to combine multiple tables into one table. However, this operator also preserves the duplicate rows in the resultant tables.

    Suppose there are two tables, one of which contains the number of games a player competed in internationally and the other contains the number of games a player played nationally.

    Union vs Unionall

    As we can see in the tables above, Kohli played 234 matches internationally and 234 matches nationally. Even though the data in these columns is the same, they are all separate matches. There is a need to include both rows in the resultant table displaying the total matches played by a player. So, we use the UNION ALL operator in such cases.

    Union vs Unionall1

    Syntax

    Following is the syntax of UNION ALL operator in SQL −

    SELECT*FROM table1
    UNIONALLSELECT*FROM table2;

    Example

    In the following example, let us perform UNION ALL operation on the same sample tables given above: “COURSES_PICKED” and “EXTRA_COURSES_PICKED”, using the given query below −

    SELECT*FROM COURSES_PICKED
    UNIONALLSELECT*FROM EXTRA_COURSES_PICKED;

    Output

    The resultant table is displayed as follows −

    STUDENT_IDSTUDENT_NAMECOURSE_NAME
    1JOHNENGLISH
    2ROBERTCOMPUTER SCIENCE
    3SASHACOMMUNICATIONS
    4JULIANMATHEMATICS
    1JOHNPHYSICAL EDUCATION
    2ROBERTGYM
    3SASHAFILM
    4JULIANMATHEMATICS

  •  UNION Operator

    The SQL UNION Operator

    The SQL UNION operator is used to combine data from multiple tables by eliminating duplicate rows (if any).

    To use the UNION operator on multiple tables, all these tables must be union compatible. And they are said to be union compatible if and only if they meet the following criteria −

    • The same number of columns selected with the same datatype.
    • These columns must also be in the same order.
    • They need not have same number of rows.

    Once these criterion are met, the UNION operator returns the rows from multiple tables as a resultant table which is void of all duplicate values from these tables.

    The column names in the final result set will be based on the column names selected in the first SELECT statement. If you want to use a different name for a column in the final result set, you can use an alias in the SELECT statement.

    Syntax

    The basic syntax of a UNION operator is as follows −

    SELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]UNIONSELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition];

    Here, the given condition could be any given expression based on your requirement.

    UNION on a Single Field

    If we want to use UNION to combine the result sets of two or more SELECT statements on a single field, we can simply include that field in the SELECT statement of each query. The UNION operator will automatically remove any duplicate values in the final result set.

    When using UNION on a single field, the column names in the result set will be determined by the column name in the first SELECT statement. Therefore, you may need to use an alias in the SELECT statement to ensure that the column name is meaningful for the final result set.

    Example

    Assume we have created a table with name CUSTOMERS in MySQL database using CREATE TABLE statement as shown below −

    CREATETABLE CUSTOMERS (
       ID INTNOTNULL,
       NAME VARCHAR(20)NOTNULL,
       AGE INTNOTNULL,
       ADDRESS CHAR(25),
       SALARY DECIMAL(18,2),PRIMARYKEY(ID));

    Following query inserts values into this table using the INSERT statement −

    INSERTINTO CUSTOMERS VALUES(1,'Ramesh',32,'Ahmedabad',2000.00),(2,'Khilan',25,'Delhi',1500.00),(3,'Kaushik',23,'Kota',2000.00),(4,'Chaitali',25,'Mumbai',6500.00),(5,'Hardik',27,'Bhopal',8500.00),(6,'Komal',22,'Hyderabad',4500.00),(7,'Muffy',24,'Indore',10000.00);

    The CUSTOMERS table is as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    2Khilan25Delhi1500.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    5Hardik27Bhopal8500.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    Now, creating the second table ORDERS using CREATE TABLE statement as shown below −

    CREATETABLE ORDERS (
       OID INTNOTNULL,DATEDATETIMENOTNULL,
       CUSTOMER_ID INTNOTNULL,
       AMOUNT INTNOTNULL,PRIMARYKEY(OID));

    Following query inserts values into this table using the INSERT statement −

    INSERTINTO ORDERS VALUES(102,'2009-10-08 00:00:00',3,3000),(100,'2009-10-08 00:00:00',3,1500),(101,'2009-11-20 00:00:00',2,1560),(103,'2008-05-20 00:00:00',4,2060);

    The ORDERS table is as follows −

    OIDDATECUSTOMER_IDAMOUNT
    1022009-10-08 00:00:0033000.00
    1002009-10-08 00:00:0031500.00
    1012009-11-20 00:00:0021560.00
    1032008-05-20 00:00:0042060.00

    Using the following query, let us combine the SALARY and AMOUNT columns from CUSTOMERS and ORDERS table (since these columns have similar datatypes) −

    SELECT SALARY FROM CUSTOMERS UNIONSELECT AMOUNT FROM ORDERS;

    Output

    Output of the above query is as follows −

    SALARY
    2000.00
    1500.00
    6500.00
    8500.00
    4500.00
    10000.00
    3000.00
    1560.00
    2060.00

    UNION on Multiple Fields

    When we use UNION on multiple fields, the number and order of the fields in each SELECT statement must match. Also, the data types of the fields in each SELECT statement must be compatible for the UNION to work correctly. If the data types are not compatible, you may need to use conversion functions such as CAST or CONVERT to ensure that the data types match.

    Example

    As the CUSTOMERS and ORDERS tables are not union-compatible individually, let us first join these two tables into a bigger table using Left Join and Right Join. The joined tables retrieved will have same number of columns with same datatypes, becoming union compatible. Now, these tables are combined using UNION query shown below −

    SELECT  ID, NAME, AMOUNT,DATEFROM CUSTOMERS
    LEFTJOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
    UNIONSELECT  ID, NAME, AMOUNT,DATEFROM CUSTOMERS
    RIGHTJOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

    Output

    This would produce the following result −

    IDNAMEAMOUNTDATE
    1RameshNULLNULL
    2Khilan15602009-11-20 00:00:00
    3Kaushik30002009-10-08 00:00:00
    3Kaushik15002009-10-08 00:00:00
    4Chaitali20602008-05-20 00:00:00
    5HardikNULLNULL
    6KomalNULLNULL
    7MuffyNULLNULL

    UNION with WHERE Clause

    We can use the WHERE clause with UNION operator to filter the results of each SELECT statement before combining them.

    Syntax

    Following is the syntax for using the WHERE clause with UNION operator −

    SELECT column1, column2, column3
    FROM table1
    WHERE column1 ='value1'UNIONSELECT column1, column2, column3
    FROM table2
    WHERE column1 ='value2';

    Example

    In the following query, we are retrieving the id’s of the customers where id is greater than 5 and 2 from the ‘CUSTOMERS’ and ‘ORDERS’ tables respectively −

    SELECT ID, SALARY FROM CUSTOMERS WHERE ID >5UNIONSELECT CUSTOMER_ID, AMOUNT FROM ORDERS WHERE CUSTOMER_ID >2;

    Output

    Following is the result produced −

    IDSALARY
    64500.00
    710000.00
    33000.00
    31500.00
    42060.00

    UNION with ORDER BY Clause

    When we use UNION with ORDER BY clause, it combines the sorted result sets of all SELECT statements and produces a single sorted result set.

    Example

    In here, we are retrieving the id’s of the customers where id is greater than 5 and 2 from the ‘CUSTOMERS’ and ‘ORDERS’ tables respectively, sorted low to high from their salary −

    SELECT ID, SALARY FROM CUSTOMERS WHERE ID >5UNIONSELECT CUSTOMER_ID, AMOUNT FROM ORDERS WHERE CUSTOMER_ID >2ORDERBY SALARY;

    Output

    Following is the output of the above query −

    IDSALARY
    31500.00
    42060.00
    33000.00
    64500.00
    710000.00

    The ORDER BY clause in a UNION statement applies to the entire result set, not just the last SELECT statement.

    UNION with Aliases

    We can use aliases in the SELECT statement of UNION operator to give a table or column a temporary name, which can be useful when working with multiple tables or columns with similar names.

    When using UNION with aliases, it’s important to note that the column aliases are determined by the first SELECT statement. Therefore, if you want to use different aliases for the same column in different SELECT statements, you need to use column aliases in all SELECT statements to ensure consistent column names in the final result set.

    Syntax

    Following is the syntax for using Union with Aliases −

    SELECT column1 AS alias1, column2 AS alias2
    FROM table1
    UNIONSELECT column3 AS alias1, column4 AS alias2
    FROM table2;

    Example

    The following query retrieves all the id’s from both tables, along with an indication of whether each id is of the customer or the order made by them −

    SELECT ID,'customer'AStypeFROM CUSTOMERS
    UNIONSELECT OID,'order'AStypeFROM ORDERS;

    Output

    Following is the output produced −

    IDtype
    1customer
    2customer
    3customer
    4customer
    5customer
    6customer
    7customer
    100order
    101order
    102order
    103order

    There are two other operators which are like the UNION operator.

    • SQL INTERSECT Operator − This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement.
    • SQL EXCEPT Operator − This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement.
  • BETWEEN Operator

    The SQL BETWEEN Operator

    The BETWEEN operator is a logical operator in SQL, that is used to retrieve the data within a specified range. The retrieved values can be integers, characters, or dates.

    You can use the BETWEEN operator to replace a combination of “greater than equal AND less than equal” conditions.

    Let us understand it in a better way by using the below example table −

    Between

    Suppose we want to list out the names from the above table who are aged BETWEEN 20 and 30. So, we will get “Varma(21)”, “Nikhil(25)”, and “Bhargav(29)” as a result.

    Syntax

    Following is the syntax of the BETWEEN operator in SQL −

    SELECT column1, column2, column3,....columnN
    FROM table_name
    WHEREcolumnBETWEEN value1 AND value2;

    Here,

    • value1 is the beginning value of the range.
    • value2 is the ending value of the range (inclusive).

    Example

    First of all, let us create a table named CUSTOMERS using the following query −

    CREATETABLE CUSTOMERS (
       ID INTNOTNULL,
       NAME VARCHAR(20)NOTNULL,
       AGE INTNOTNULL,
       ADDRESS CHAR(25),
       SALARY DECIMAL(18,2),PRIMARYKEY(ID));

    Once the table is created, let us insert some values into the table using the following INSERT query −

    INSERTINTO CUSTOMERS VALUES(1,'Ramesh',32,'Ahmedabad',2000.00),(2,'Khilan',25,'Delhi',1500.00),(3,'Kaushik',23,'Kota',2000.00),(4,'Chaitali',25,'Mumbai',6500.00),(5,'Hardik',27,'Bhopal',8500.00),(6,'Komal',22,'Hyderabad',4500.00),(7,'Muffy',24,'Indore',10000.00);

    The table created is as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    2Khilan25Delhi1500.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    5Hardik27Bhopal8500.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    Now, we are using the BETWEEN operator to retrieve the details of the CUSTOMERS whose AGE (numeric data) is between 20 and 25 −

    SELECT*FROM CUSTOMERS WHERE AGE BETWEEN20AND25;

    Output

    When we execute the above query, the output is obtained as follows −

    IDNAMEAGEADDRESSSALARY
    2Khilan25Delhi1500.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    Example

    Here, we are using the BETWEEN operator with characters. Let us retrieve the details of the customers whose names starts in between the alphabets “A” and “L” using the following query −

    SELECT*FROM CUSTOMERS WHERE NAME BETWEEN'A'AND'L';

    Output

    Following is the output of the above query −

    IDNAMEAGEADDRESSSALARY
    2Khilan25Delhi1500.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    5Hardik27Bhopal8500.00
    6Komal22Hyderabad4500.00

    BETWEEN Operator with IN Operator

    In SQL, we can combine the BETWEEN operator with the IN operator to select values that are within a specified range and also matches with values specified in the list of IN clause.

    Example

    In the following query, we are retrieving the details of all the customers whose salary is between 4000 and 10000. In addition, we are only retrieving the customers who lives in Hyderabad and Bhopal using the IN operator in SQL −

    SELECT*FROM CUSTOMERS
    WHERE SALARY BETWEEN4000AND10000AND ADDRESS IN('Hyderabad','Bhopal');

    Output

    On executing the above query, the output is displayed as follows −

    IDNAMEAGEADDRESSSALARY
    5Hardik27Bhopal8500.00
    6Komal22Hyderabad4500.00

    BETWEEN Operator with UPDATE Statement

    We can also use the BETWEEN operator with the UPDATE statement to update values within the specified range. The UPDATE statement is used to modify existing data in a database table.

    Example

    Let us update the salaries of the customers whose age lies between 25 to 30 using the following query −

    UPDATE CUSTOMERS SET SALARY =10000WHERE AGE BETWEEN25AND30;

    Output

    The output for the above query is as given below −

    Query OK, 3 rows affected (0.02 sec)
    Rows matched: 3  Changed: 3  Warnings: 0
    

    Verification

    Let us verify whether the salaries are updated or not using the following query −

    SELECT*FROM CUSTOMERS;

    The table for the above query produced as given below −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    2Khilan25Delhi10000.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai10000.00
    5Hardik27Bhopal10000.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    BETWEEN Operator with DELETE Statement

    We can also use the BETWEEN operator with the DELETE statement to delete rows within a specified range.

    Example

    Now, let us delete the customers whose age is between 20 and 24 using the DELETE statement −

    DELETEFROM CUSTOMERS 
    WHERE AGE BETWEEN20AND24;

    Output

    If we compile and run the above query, the result is produced as follows −

    Query OK, 3 rows affected (0.02 sec)
    

    Verification

    Let us verify whether the records with the specified age values are deleted or not, using the following query −

    SELECT*FROM CUSTOMERS;

    The table for the above query produced is as given below −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    2Khilan25Delhi1500.00
    4Chaitali25Mumbai6500.00
    5Hardik27Bhopal8500.00

    NOT BETWEEN Operator

    The NOT BETWEEN operator in SQL works exactly opposite to BETWEEN operator. This is used to retrieve the data which is not present in the specified range.

    Let us understand in a better way by using the below example table −

    Between

    Suppose we want to list out the students from the above table who are aged not between 20 and 30. So, we will get “Prudhvi(45) and Ganesh(33)” as result.

    Syntax

    Following is the syntax of the NOT BETWEEN operator in SQL −

    SELECT column_name1, column_name2, column_name3,......column_nameN
    FROM table_name
    WHERE column_name NOTBETWEEN value1 AND value2;

    Example

    Consider the previously created CUSTOMERS table and let us retrieve the details of customers whose age is not greater than or equal to 25 and less than or equal to 30 (numeric data) using the following query −

    SELECT*FROM CUSTOMERS 
    WHERE AGE NOTBETWEEN25AND30;

    Output

    When we execute the above query, the output is obtained as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    3Kaushik23Kota2000.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    NOT BETWEEN Operator with IN

    We can use the NOT BETWEEN operator in combination with the IN operator to select values that are outside a range and also do not match with the specified list of values.

    Example

    In the following query, we are selecting the customers whose salary is not between 1000 and 5000. In addition; we are not retrieving the customers who are living in Bhopal using the IN operator in SQL −

    SELECT*FROM CUSTOMERS 
    WHERE SALARY NOTBETWEEN1000AND5000AND ADDRESS NOTIN('Bhopal');

    Output

    On executing the above query, the output is displayed as follows −

    IDNAMEAGEADDRESSSALARY
    4Chaitali25Mumbai6500.00
    7Muffy24Indore10000.00

  • NOT NULL Constraint

    In a table, columns can typically accept NULL values by default. However, if you want to ensure that a particular column does not contain NULL values, you need to add the NOT NULL constraint/condition on that column.

    The SQL NOT NULL Constraint

    The NOT NULL constraint in SQL is used to ensure that a column in a table doesn’t contain NULL (empty) values, and prevent any attempts to insert or update rows with NULL values.

    Usually, if we don’t provide value to a particular column while inserting data into a table, by default it is considered as a NULL value. But, if we add the NOT NULL constraint on a column, it will enforce that a value must be provided for that column during the data insertion, and attempting to insert a NULL value will result in a constraint violation error.

    Syntax

    Following is the basic syntax of NOT NULL constraint while creating a table −

    CREATETABLE table_name (
       column1 datatype NOTNULL,
       column2 datatype,
       column3 datatype NOTNULL,...);

    Creating NOT NULL Constraint On a Table

    To add the NOT NULL constraint on a column of a table, we just need to add the keyword “NOT NULL” after the column’s data type in the column definition.

    Example

    First of all, let us create a table named CUSTOMERS using the following query −

    CREATETABLE CUSTOMERS(
       ID INTNOTNULL,
       NAME VARCHAR(20)NOTNULL,
       AGE  INTNOTNULL,
       ADDRESS CHAR(25),
       SALARY DECIMAL(20,2),PRIMARYKEY(ID));

    Let’s insert some values into the above created table using the following INSERT query −

    INSERTINTO CUSTOMERS VALUES(1,'Ramesh','32','Ahmedabad',2000),(2,'Khilan','25','Delhi',1500),(3,'Kaushik','23','Kota',2500),(4,'Chaitali','25','Mumbai',6500),(5,'Hardik','27','Bhopal',8500),(6,'Komal','22','Hyderabad',9000),(7,'Muffy','24','Indore',5500);

    The table will be created as shown below −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    2Khilan25Delhi1500.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    5Hardik27Bhopal8500.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    Verification

    To display the structure of a table in MySQL database, we use the DESCRIBE command. The DESCRIBE command provides a summary of the columns, data types, and various attributes of the table as shown below −

    DESCRIBE CUSTOMERS;

    As we can see in the output below, the table shows information about the column names of the table, their types, and whether they are nullable or not.

    FieldTypeNullKeyDefaultExtra
    IDintNOPRINULL
    NAMEvarchar(20)NONULL
    AGEintNONULL
    ADDRESSchar(25)YESNULL
    SALARYdecimal(20,2)YESNULL

    Removing a NOT NULL Constraint From the Table

    In SQL, to remove a NOT NULL constraint of a column in an existing table, we need to use the ALTER TABLE statement. Using this statement, we can modify the definition of a column i,e you can change the name, data type or constraint of an existing column.

    One of a way to remove the NOT NULL constraint on a column is to changing it to NULL.

    Syntax

    Following is the syntax to remove a not null constraint from the table in MySQL database −

    ALTERTABLE table_name
    MODIFYCOLUMN column_name datatype NULL;

    Were,

    • table_name is the name of the table that contains the columns we want to modify.
    • column_name is the name of the column that has the NOT NULL constraint you want to remove.
    • datatype is the data type of the column.

    Example

    Following is the query to modify the constraint on the NAME column of the CUSTOMERS table to NULL in MySQL database −

    ALTERTABLE CUSTOMERS MODIFYCOLUMN NAME VARCHAR(20)NULL;

    Output

    On executing the above query, the output is displayed as follows −

    Query OK, 0 rows affected (0.10 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Now, let us display the structure of the table named “CUSTOMERS” using the following query −

    DESCRIBE CUSTOMERS;

    As we can see in the table below, the column “NAME” is modified to nullable, which means NULL values are allowed in this column.

    FieldTypeNullKeyDefaultExtra
    IDintNOPRINULL
    NAMEvarchar(20)YESNULL
    AGEintNONULL
    ADDRESSchar(25)YESNULL
    SALARYdecimal(20,2)YESNULL

    Adding a NOT NULL Constraint to the Existing Table

    In the previous section, we have removed the NOT NULL constraint on a column by changing its definition using the ALTER TABLE statement. Similarly, we can add a NOT NULL constraint to a column in an existing table using the ALTER TABLE statement.

    Syntax

    Following is the SQL syntax to add the NOT NULL constraint to the existing column in MySQL database −

    ALTERTABLE table_name
    MODIFYCOLUMN column_name datatype NOTNULL;

    Example

    Assume the previously created table CUSTOMERS and let us modify the ADDRESS column ensuring that it does not allow null values using the following query −

    ALTERTABLE CUSTOMERS MODIFYCOLUMN ADDRESS CHAR(25)NOTNULL;

    Output

    When we execute the above query, the output is obtained as follows −

    Query OK, 0 rows affected (0.08 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    We can display the structure of the CUSTOMERS table using the following query −

    DESCRIBE CUSTOMERS;

    As we can see in the output below, the column “ADDRESS” is modified, which means NULL values are NOT allowed in this column.

    FieldTypeNullKeyDefaultExtra
    IDintNOPRINULL
    NAMEvarchar(20)NONULL
    AGEintNONULL
    ADDRESSchar(25)NONULL
    SALARYdecimal(20,2)YESNULL

  • IS NOT NULL

    A NULL value indicates a missing or unknown value. It appears to be blank and does not contain any data. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. For checking null values we can use two basic operators.

    • IS NULL
    • IS NOT NULL

    The SQL IS NOT NULL Operator

    The SQL IS NOT NULL operator is used to filter data by verifying whether a particular column has a not-null values. This operator can be used with SQL statements such as SELECT, UPDATE, and DELETE.

    By using the IS NOT NULL operator, we can only fetch the records that contain valid data in a particular column.

    Syntax

    Following is the syntax of the SQL IS NOT NULL operator −

    SELECT column_names
    FROM table_name
    WHERE column_name ISNOTNULL;

    Example

    Firstly, let us create a table named CUSTOMERS using the following query −

    CREATETABLE CUSTOMERS(
       ID INTNOTNULL, 
       NAME VARCHAR(20), 
       AGE INT, 
       ADDRESS CHAR(25), 
       SALARY DECIMAL(18,2),PRIMARYKEY(ID));

    Now, insert values into this table using the INSERT statement as follows −

    INSERTINTO CUSTOMERS VALUES(1,'Ramesh',32,'Ahmedabad',NULL),(2,'Khilan',25,NULL,1500.00),(3,'Kaushik',NULL,'Kota',2000.00),(4,'Chaitali',25,'Mumbai',NULL),(5,'Hardik',27,'Bhopal',8500.00),(6,'Komal',NULL,'Hyderabad',4500.00),(7,'Muffy',24,NULL,10000.00);

    The table will be created as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32AhmedabadNULL
    2Khilan25NULL1500.00
    3KaushikNULLKota2000.00
    4Chaitali25MumbaiNULL
    5Hardik27Bhopal8500.00
    6KomalNULLHyderabad4500.00
    7Muffy24NULL10000.00

    Example

    In the following query, we are going to return all the records from the CUSTOMERS table where the ADDRESS is not null −

    SELECT*FROM CUSTOMERS WHERE ADDRESS ISNOTNULL;

    Output

    On executing the above query, it will generate the output as shown below −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32AhmedabadNULL
    3KaushikNULLKota2000.00
    4Chaitali25MumbaiNULL
    5Hardik27Bhopal8500.00
    6KomalNULLHyderabad4500.00

    IS NOT NULL with COUNT() Function

    We can use the IS NOT NULL operator along with the SQL COUNT() function to count only the non-null values in a specific column.

    Syntax

    Following is the syntax of IS NOT NULL operator with the COUNT() function −

    SELECTCOUNT(column_name)FROM table_name
    WHERE condition ISNOTNULL;

    Example

    The following query returns the count of all rows in the CUSTOMERS table where the SALARY column is not null −

    SELECTCOUNT(*)FROM CUSTOMERS WHERE SALARY ISNOTNULL;

    Output

    The output produced is as shown below −

    COUNT(*)
    5

    IS NOT NULL with DELETE Statement

    In SQL, we can delete all rows that do not contain NULL values in a specific column using the DELETE statement with IS NOT NULL operator.

    Syntax

    Following is the syntax of the IS NOT NULL operator with the DELETE statement in SQL −

    DELETEFROM table_name
    WHERE columnname1, columnname2,...ISNOTNULL;

    Example

    In the following query, we are deleting records which are not null in the SALARY column of the CUSTOMERS table −

    DELETEFROM CUSTOMERS WHERE SALARY ISNOTNULL;

    Output

    We get the following result −

    Query OK, 5 rows affected (0.02 sec)
    

    Verification

    Execute the SELECT query given below to check whether the table has been changed or not −

    SELECT*FROM CUSTOMERS;

    If we compile and run the program, the result is produced as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32AhmedabadNULL
    4Chaitali25MumbaiNULL

    IS NOT NULL with UPDATE Statement

    We can use the UPDATE statement with the IS NOT NULL operator in SQL to update records with not-null records in a particular column.

    Syntax

    Following is the syntax of the IS NOT NULL operator with the UPDATE statement in SQL −

    UPDATE table_name
    SET column1 = value1, column2 = value2,...WHERE columnname1, columnname2,...ISNOTNULL;

    Example

    Truncate the CUSTOMERS table and reinsert all the 7 records into it again. The following query, increments all the values in the SALARY column of the with 5000, where the salary value is not null −

    UPDATE CUSTOMERS SET SALARY = SALARY+5000WHERE SALARY ISNOTNULL;

    Output

    When we execute the program above, the output is obtained as follows −

    Query OK, 5 rows affected (0.01 sec)
    Rows matched: 5  Changed: 5  Warnings: 0
    

    Verification

    To check whether the table has been updated or not, execute the SELECT query below −

    SELECT*FROM CUSTOMERS;

    The table is displayed as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32AhmedabadNULL
    2Khilan25NULL6500.00
    3KaushikNULLKota7000.00
    4Chaitali25MumbaiNULL
    5Hardik27Bhopal13500.00
    6KomalNULLHyderabad9500.00
    7Muffy24NULL15000.00

  • IS NULL

    Let’s assume a table with NULL values in some of its fields. These fields indicate that no values are present in them. SQL allows users to create new records or modify existing ones without specifying a value for a field. If no value is provided, the field is stored with a NULL value.

    In SQL, it is not possible to check NULL values with comparison operators such as =, <, or <>. Instead, we use the IS NULL and IS NOT NULL (negation of NULL values) operators.

    The SQL IS NULL Operator

    The SQL IS NULL operator is used to check whether a value in a column is NULL. It returns true if the column value is NULL; otherwise false.

    The NULL is a value that represents missing or unknown data, and the IS NULL operator allows us to filter for records that contain NULL values in a particular column.

    Syntax

    Following is the syntax of IS NULL operator −

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

    Example

    Firstly, let us create a table named CUSTOMERS using the following query −

    CREATETABLE CUSTOMERS(
     ID INTNOTNULL, 
     NAME VARCHAR(20), 
     AGE INT, 
     ADDRESS CHAR(25), 
     SALARY DECIMAL(18,2),PRIMARYKEY(ID));

    Now, insert values into this table using the INSERT statement as follows −

    INSERTINTO CUSTOMERS VALUES(1,'Ramesh',32,'Ahmedabad',NULL),(2,'Khilan',25,NULL,1500.00),(3,'Kaushik',NULL,'Kota',2000.00),(4,'Chaitali',25,'Mumbai',NULL),(5,'Hardik',27,'Bhopal',8500.00),(6,'Komal',NULL,'Hyderabad',4500.00),(7,'Muffy',24,NULL,10000.00);

    The table will be created as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32AhmedabadNULL
    2Khilan25NULL1500.00
    3KaushikNULLKota2000.00
    4Chaitali25MumbaiNULL
    5Hardik27Bhopal8500.00
    6KomalNULLHyderabad4500.00
    7Muffy24NULL10000.00

    IS NULL with SELECT Statement

    We can use the IS NULL operator with a SELECT statement to filter the records with NULL values.

    Example

    In the following query, we are retrieving all the records from the CUSTOMERS table where the ADDRESS is null −

    SELECT*FROM CUSTOMERS WHERE ADDRESS ISNULL;

    Output

    On executing the above query, it will generate the output as shown below −

    IDNAMEAGEADDRESSSALARY
    2Khilan25NULL1500.00
    7Muffy24NULL10000.00

    IS NULL with COUNT() Function

    We can also use the IS NULL operator with the COUNT() function in SQL to count the number of records with NULL values in a particular column.

    Syntax

    Following is the syntax of IS NULL operator with the COUNT() function −

    SELECTCOUNT(column_name)FROM table_name
    WHERE condition ISNULL;

    Example

    The following query returns the count of records have a blank field (NULL) in SALARY column of the CUSTOMERS table −

    SELECTCOUNT(*)FROM CUSTOMERS WHERE SALARY ISNULL;

    Output

    The output produced is as shown below −

    COUNT(*)
    2

    IS NULL with UPDATE Statement

    We can use the UPDATE statement with the “IS NULL” operator in SQL to update records with NULL values in a particular column.

    Syntax

    Following is the syntax of the IS NULL operator with the UPDATE statement in SQL −

    UPDATE table_name
    SET column1 = value1, column2 = value2,...WHERE columnname1, columnname2,...ISNULL;

    Example

    In the following query, we are updating the blank (NULL) records of the AGE column to a value of 48 −

    UPDATE CUSTOMERS SET AGE =48WHERE AGE ISNULL;

    Output

    When we execute the program above, the output is obtained as follows −

    Query OK, 2 rows affected (0.01 sec)
    Rows matched: 2  Changed: 2  Warnings: 0
    

    Verification

    To check whether the table has been updated or not, execute the SELECT query below −

    SELECT*FROM CUSTOMERS;

    The table is displayed as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32AhmedabadNULL
    2Khilan25NULL1500.00
    3Kaushik48Kota2000.00
    4Chaitali25MumbaiNULL
    5Hardik27Bhopal8500.00
    6Komal48Hyderabad4500.00
    7Muffy24NULL10000.00

    IS NULL with DELETE Statement

    We can also use the DELETE statement with IS NULL operator to delete records with NULL values in a particular column.

    Syntax

    Following is the syntax of the IS NULL operator with the DELETE statement in SQL −

    DELETEFROM table_name
    WHERE columnname1, columnname2,...ISNULL;

    Example

    In the following query, we are deleting the blank (NULL) records present in the SALARY column of CUSTOMERS table −

    DELETEFROM CUSTOMERS WHERE SALARY ISNULL;

    Output

    We get the following result −

    Query OK, 2 rows affected (0.01 sec)
    

    Verification

    Execute the SELECT query given below to check whether the table has been changed or not −

    SELECT*FROM CUSTOMERS;

    If we compile and run the program, the result is produced as follows −

    IDNAMEAGEADDRESSSALARY
    2Khilan25NULL1500.00
    3KaushikNULLKota2000.00
    5Hardik27Bhopal8500.00
    6KomalNULLHyderabad4500.00
    7Muffy24NULL10000.00

  • Not Equal

    The SQL NOT EQUAL Operator

    The SQL NOT EQUAL operator is used to compare two values and return true if they are not equal. It is represented by “<>” and “!=”. The difference between these two is that <> follows the ISO standard, but != doesn’t. So, it is recommended to use the <> operator.

    We can use the NOT EQUAL operator in WHERE clause to filter records based on a specific condition and in GROUP BY clause to group the results.

    The comparison is case-sensitive by default, while using the NOT EQUAL operator with text values.

    Syntax

    Following is the syntax of the NOT EQUAL operator in SQL −

    WHERE expression1 <> expression2;

    Example

    To understand it better let us consider the CUSTOMERS table which contains the personal details of customers including their name, age, address and salary etc. as shown below −

    CREATETABLE CUSTOMERS(
       ID   INTNOTNULL,
       NAME VARCHAR(20)NOTNULL,
       AGE  INTNOTNULL,
       ADDRESS  CHAR(25),
       SALARY   DECIMAL(18,2),PRIMARYKEY(ID));

    Now, insert values into this table using the INSERT statement as follows −

    INSERTINTO CUSTOMERS VALUES(1,'Ramesh',32,'Ahmedabad',2000.00),(2,'Khilan',25,'Delhi',1500.00),(3,'Kaushik',23,'Kota',2000.00),(4,'Chaitali',25,'Mumbai',6500.00),(5,'Hardik',27,'Bhopal',8500.00),(6,'Komal',22,'Hyderabad',4500.00),(7,'Muffy',24,'Indore',10000.00);

    The table will be created as follows −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    2Khilan25Delhi1500.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    5Hardik27Bhopal8500.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    NOT EQUAL with Text

    We can use the NOT EQUAL operator with text in SQL to compare two text values and return. We can use “<>” or “!=” in the WHERE clause of a SQL statement and exclude rows that match a specific text value.

    Example

    In the following query, we are retrieving all the records from the CUSTOMERS table whose NAME is not ‘Ramesh’ −

    SELECT*FROM CUSTOMERS WHERE NAME <>'Ramesh';

    Output

    The output of the above code is as shown below −

    IDNAMEAGEADDRESSSALARY
    2Khilan25Delhi1500.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    5Hardik27Bhopal8500.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    NOT EQUAL with GROUP BY Clause

    We can use the NOT EQUAL operator with the GROUP BY clause to group the results by the values that are not equal to the specified text value.

    The aggregate functions such as COUNT(), MAX(), MIN(), SUM(), and AVG() are frequently used with the GROUP BY statement.

    Example

    Here, we are retrieving the number of records with distinct ages (excluding ’22’) in the ‘CUSTOMERS’ table and grouping them by age value −

    SELECTCOUNT(ID), AGE FROM CUSTOMERS 
    WHERE AGE <>'22'GROUPBY AGE;

    Output

    On executing the above query, it will generate the output as shown below −

    COUNT(id)AGE
    132
    225
    123
    127
    124

    NOT EQUAL with Multiple Conditions

    The not equal operator can also be used with multiple conditions in a WHERE clause to filter out rows that match specific criteria.

    Example

    Now, we are retrieving all the customers whose salary is either “>2000” or “=2000“. At the same time, the customer must not be from “Bhopal” −

    SELECT*FROM CUSTOMERS 
    WHERE ADDRESS <>'Bhopal'AND(SALARY>'2000'OR SALARY='2000');

    Output

    Following is the output of the above code −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    3Kaushik23Kota2000.00
    4Chaitali25Mumbai6500.00
    6Komal22Hyderabad4500.00
    7Muffy24Indore10000.00

    Negating a Condition Using NOT EQUAL

    In SQL, the NOT EQUAL operator can also be combined with the NOT Operator to negate a condition. It filters out the rows that meet a specific condition.

    Example

    In the following query, we are retrieving all rows from the “CUSTOMERS” table where the “SALARY” is equal to ‘2000’ −

    SELECT*FROM CUSTOMERS WHERENOT SALARY !='2000';

    Output

    After executing the above code, we get the following output −

    IDNAMEAGEADDRESSSALARY
    1Ramesh32Ahmedabad2000.00
    3Kaushik23Kota2000.00