Category: sql

  • Khóa học miễn phí SQL – Cross Join nhận dự án làm có lương

    SQL – Cross Join

    Table of content


    The SQL Cross Join

    An SQL Cross Join is a basic type of inner join that is used to retrieve the Cartesian product (or cross product) of two individual tables. That means, this join will combine each row of the first table with each row of second table (i.e. permutations).

    A Cartesian product, or a cross product, is the result achieved from multiplication of two sets. This is done by multiplying all the possible pairs from both the sets.

    The sample figure below illustrates the cross join in a simple manner.

    Cross Join

    As you can see, we considered two table columns: Hair Style and Hair Type. Each of these columns contain some records that need to be matched. Hence, using cross join, we combine each record in the “Hair Style” column with all records in the “Hair Type” column. The resultant table obtained is considered as the Cartesian product or Joined table.

    Syntax

    Following is the basic syntax of the Cross Join query in SQL −

    SELECT column_name(s)
    FROM table1
    CROSS JOIN table2;
    

    Example

    Assume we have created a table named CUSTOMERS, which contains the personal details of customers including their name, age, address and salary etc., using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

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

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 );
    

    The table will be created as −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00

    Let us create another table ORDERS, containing the details of orders made and the date they are made on.

    CREATE TABLE ORDERS (
       OID INT NOT NULL,
       DATE VARCHAR (20) NOT NULL,
       CUSTOMER_ID INT NOT NULL,
       AMOUNT DECIMAL (18, 2)
    );
    

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

    INSERT INTO ORDERS VALUES
    (100, ''2009-10-08 00:00:00'', 3, 1500.00),
    (101, ''2009-11-20 00:00:00'', 2, 1560.00);
    

    The table is displayed as follows −

    OID DATE CUSTOMER_ID AMOUNT
    100 2009-10-08 00:00:00 3 1500.00
    101 2009-11-20 00:00:00 2 1560.00

    Now, if we execute the following Cross Join query on these two tables given above, the cross join combines each row in CUSTOMERS table with each row in ORDERS table.

    SELECT  ID, NAME, AMOUNT, DATE
    FROM CUSTOMERS
    CROSS JOIN ORDERS;
    

    Output

    The resultant table is as follows −

    ID NAME AMOUNT DATE
    2 Khilan 1500.00 2009-10-08 00:00:00
    1 Ramesh 1560 2009-11-20 00:00:00
    2 Khilan 1560 2009-11-20 00:00:00
    1 Ramesh 1500.00 2009-10-08 00:00:00

    Joining Multiple Tables with Cross Join

    We can also join more than two tables using cross join. In this case, multiple-way permutations are displayed and the resultant table is expected to contain way more records than the individual tables.

    Syntax

    Following is the syntax to join multiple tables using cross join in SQL −

    SELECT column_name(s)
    FROM table1
    CROSS JOIN table2
    CROSS JOIN table3
    CROSS JOIN table4
    ....
    ....
    ....
    CROSS JOIN tableN;
    

    Example

    Assume we have created another table named ORDER_RANGE using the following query −

    CREATE TABLE ORDER_RANGE (
       SNO INT NOT NULL,
       ORDER_RANGE VARCHAR (20) NOT NULL
    );
    

    Now, we can insert values into this empty tables using the INSERT statement as follows −

    INSERT INTO ORDER_RANGE VALUES
    (1, ''1-100''),
    (2, ''100-200''),
    (3, ''200-300'');
    

    The ORDER_RANGE table is created as follows −

    SNO ORDER_RANGE
    1 1-100
    2 100-200
    3 200-300

    Following query combines the three tables CUSTOMERS, ORDERS and ORDER_RANGE, using cross join −

    SELECT ID, NAME, AMOUNT, DATE, ORDER_RANGE
    FROM CUSTOMERS
    CROSS JOIN ORDERS
    CROSS JOIN ORDER_RANGE;
    

    Output

    The resultant table is given below −

    ID NAME AMOUNT DATE ORDER_RANGE
    2 Khilan 1560 2009-11-20 00:00:00 1-100
    1 Ramesh 1560 2009-11-20 00:00:00 1-100
    2 Khilan 1500.00 2009-10-08 00:00:00 1-100
    1 Ramesh 1500.00 2009-10-08 00:00:00 1-100
    2 Khilan 1560 2009-11-20 00:00:00 100-200
    1 Ramesh 1560 2009-11-20 00:00:00 100-200
    2 Khilan 1500.00 2009-10-08 00:00:00 100-200
    1 Ramesh 1500.00 2009-10-08 00:00:00 100-200
    2 Khilan 1560 2009-11-20 00:00:00 200-300
    1 Ramesh 1560 2009-11-20 00:00:00 200-300
    2 Khilan 1500.00 2009-10-08 00:00:00 200-300
    1 Ramesh 1500.00 2009-10-08 00:00:00 200-300

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Full Join nhận dự án làm có lương

    SQL – Full Join

    Table of content


    The SQL Full Join

    SQL Full Join creates a new table by joining two tables as a whole. The joined table contains all records from both the tables and fills NULL values for missing matches on either side. In short, full join is a type of outer join that combines the result-sets of both left and right joins.

    MySQL does not support Full Outer Join. Instead, you can imitate its working by performing union operation between the result-sets obtained from Left Join and Right Join.

    Let us understand this concept in detail with the help of a Venn diagram below. Assume that we have two tables as two sets (represented by circles). The result-set (or newly joined table) obtained using full join is nothing but the union of these two sets.

    Full Join
    You can also achieve the equivalent result-set of FULL JOIN by performing the UNION operation on result-sets of the LEFT JOIN and RIGHT JOIN.

    Syntax

    Following is the basic syntax of Full Join in SQL −

    SELECT column_name(s)
    FROM table1
    FULL JOIN table2
    ON table1.column_name = table2.column_name;
    

    Example

    Assume we have created a table named CUSTOMERS, which contains the personal details of customers including their name, age, address and salary etc.Using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

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

    INSERT INTO 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 −

    ID NAME AGE ADDRESS SALARY
    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

    Let us create another table ORDERS, containing the details of orders made and the date they are made on.

    CREATE TABLE ORDERS (
       OID INT NOT NULL,
       DATE VARCHAR (20) NOT NULL,
       CUSTOMER_ID INT NOT NULL,
       AMOUNT DECIMAL (18, 2)
    );
    

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

    INSERT INTO ORDERS VALUES
    (102, ''2009-10-08 00:00:00'', 3, 3000.00),
    (100, ''2009-10-08 00:00:00'', 3, 1500.00),
    (101, ''2009-11-20 00:00:00'', 2, 1560.00),
    (103, ''2008-05-20 00:00:00'', 4, 2060.00);
    

    The table is displayed as follows −

    OID DATE CUSTOMER_ID AMOUNT
    102 2009-10-08 00:00:00 3 3000.00
    100 2009-10-08 00:00:00 3 1500.00
    101 2009-11-20 00:00:00 2 1560.00
    103 2008-05-20 00:00:00 4 2060.00

    Following query joins the two tables CUSTOMERS and ORDERS in SQL Server −

    SELECT ID, NAME, AMOUNT, DATE
    FROM CUSTOMERS
    FULL JOIN ORDERS
    ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
    

    Output

    The resultant table is produced as follows −

    ID NAME AMOUNT DATE
    1 Ramesh NULL NULL
    2 Khilan 1560 2009-11-20 00:00:00
    3 Kaushik 3000 2009-10-08 00:00:00
    3 Kaushik 1500 2009-10-08 00:00:00
    4 Chaitali 2060 2008-05-20 00:00:00
    5 Hardik NULL NULL
    6 Komal NULL NULL
    7 Muffy NULL NULL

    Joining Multiple Tables with Full Join

    The Full Join query can also be used to join more than just two tables. To do that, we sequentially combine two tables at a time, until all the tables are joined together.

    Note that in MySQL database, there is no provision to directly use the FULL JOIN keyword to perform join operation on multiple tables. Instead, calculate the UNION of LEFT JOIN and RIGHT JOIN on two tables at a time, until all the tables are joined.

    Syntax

    The syntax to join multiple tables using Full Join is given below −

    SELECT column1, column2, column3...
    FROM table1
    FULL JOIN table2
    ON condition_1
    FULL JOIN table3
    ON condition_2
    ....
    ....
    FULL JOIN tableN
    ON condition_N;
    

    Example

    To demonstrate Full Join, let us consider the sample tables CUSTOMERS and ORDERS that we previously created, and create another table name EMPLOYEE using the following query −

    CREATE TABLE EMPLOYEE (
       EID INT NOT NULL,
       EMPLOYEE_NAME VARCHAR (30) NOT NULL,
       SALES_MADE DECIMAL (20)
    );
    

    Now, we can insert values into this empty tables using the INSERT statement as follows −

    INSERT INTO EMPLOYEE VALUES
    (102, ''SARIKA'', 4500),
    (100, ''ALEKHYA'', 3623),
    (101, ''REVATHI'', 1291),
    (103, ''VIVEK'', 3426);
    

    The EMPLOYEE table created, will be as shown below −

    EID EMPLOYEE_NAMENAME SALES_MADE
    102 SARIKA 4500
    100 ALEKHYA 3623
    101 REVATHI 1291
    103 VIVEK 3426

    Let us join these three tables using the full join query given below −

    SELECT CUSTOMERS.ID, CUSTOMERS.NAME, ORDERS.DATE, EMPLOYEE.EMPLOYEE_NAME
    FROM CUSTOMERS
    FULL JOIN ORDERS
    ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
    FULL JOIN EMPLOYEE
    ON ORDERS.OID = EMPLOYEE.EID;
    

    Through this query, we will display the id, name of the customer along with the date on which the orders are made and the name of the employee who sold the item.

    Output

    The resultant table is obtained as follows −

    ID NAME DATE EMPLOYEE_NAME
    1 Ramesh NULL NULL
    2 Khilan 2009-11-20 00:00:00 REVATHI
    3 Kaushik 2009-10-08 00:00:00 ALEKHYA
    3 Kaushik 2009-10-08 00:00:00 SARIKA
    4 Chaitali 2008-05-20 00:00:00 VIVEK
    5 Hardik NULL NULL
    6 Komal NULL NULL
    7 Muffy NULL NULL

    Full Join with WHERE Clause

    Joins use the ON clause to filter records by default. Let us suppose there is a further requirement to filter these records based on a certain condition/constraint, we can also make use of the WHERE clause with Joins.

    Syntax

    The syntax of Full Join when used with WHERE clause is given below −

    SELECT column_name(s)
    FROM table1
    FULL JOIN table2
    ON table1.column_name = table2.column_name
    WHERE condition;
    

    Example

    Consider the previous two tables CUSTOMERS and ORDERS, and join them using the following Full Join query by applying some constraints using the WHERE clause.

    SELECT ID, NAME, DATE, AMOUNT FROM CUSTOMERS
    FULL JOIN ORDERS
    ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
    WHERE ORDERS.AMOUNT > 2000.00;
    

    Output

    The resultant table after applying the WHERE clause with full join contains the rows that has amount values greater than 2000.00 −

    ID NAME DATE AMOUNT
    3 Kaushik 2009-10-08 00:00:00 3000.00
    4 Chaitali 2008-05-20 00:00:00 2060.00

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Delete Join nhận dự án làm có lương

    SQL – DELETE JOIN

    Table of content


    Simple deletion operation in SQL can be performed on a single record or multiple records of a table. And to delete records from multiple tables, the most straightforward approach would be to delete records from one table at a time.

    However, SQL makes it easier by allowing the deletion operation to be performed on multiple tables simultaneously. This is achieved using Joins.

    The SQL DELETE… JOIN Clause

    The purpose of Joins in SQL is to combine records of two or more tables based on common columns/fields. Once the tables are joined, performing the deletion operation on the obtained result-set will delete records from all the original tables at a time.

    For example, consider a database of an educational institution. It consists of various tables: Departments, StudentDetails, LibraryPasses, LaboratoryPasses etc. When a set of students are graduated, all their details from the organizational tables need to be removed, as they are unwanted. However, removing the details separately from multiple tables can be cumbersome.

    To make it simpler, we will first retrieve the combined data of all graduated students from all the tables using Joins; then, this joined data is deleted from all the tables using DELETE statement. This entire process can be done in one single query.

    Syntax

    Following is the basic syntax of the SQL DELETE… JOIN statement −

    DELETE table(s)
    FROM table1 JOIN table2
    ON table1.common_field = table2.common_field;
    

    When we say JOIN here, we can use any type of Join: Regular Join, Natural Join, Inner Join, Outer Join, Left Join, Right Join, Full Join etc.

    Example

    To demonstrate this deletion operation, we must first create tables and insert values into them. We can create these tables using CREATE TABLE queries as shown below.

    Create a table named CUSTOMERS, which contains the personal details of customers including their name, age, address and salary etc. Using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

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

    INSERT INTO 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 −

    ID NAME AGE ADDRESS SALARY
    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

    Let us create another table ORDERS, containing the details of orders made and the date they are made on.

    CREATE TABLE ORDERS (
       OID INT NOT NULL,
       DATE VARCHAR (20) NOT NULL,
       CUSTOMER_ID INT NOT NULL,
       AMOUNT DECIMAL (18, 2)
    );
    

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

    INSERT INTO ORDERS VALUES
    (102, ''2009-10-08 00:00:00'', 3, 3000.00),
    (100, ''2009-10-08 00:00:00'', 3, 1500.00),
    (101, ''2009-11-20 00:00:00'', 2, 1560.00),
    (103, ''2008-05-20 00:00:00'', 4, 2060.00);
    

    The table is displayed as follows −

    OID DATE CUSTOMER_ID AMOUNT
    102 2009-10-08 00:00:00 3 3000.00
    100 2009-10-08 00:00:00 3 1500.00
    101 2009-11-20 00:00:00 2 1560.00
    103 2008-05-20 00:00:00 4 2060.00

    Following DELETE… JOIN query removes records from these tables at once −

    DELETE a
    FROM CUSTOMERS AS a INNER JOIN ORDERS AS b
    ON a.ID = b.CUSTOMER_ID;
    

    Output

    The output will be displayed in SQL as follows −

    Query OK, 3 rows affected (0.01 sec)
    

    Verification

    We can verify whether the changes are reflected in a table by retrieving its contents using the SELECT statement as follows −

    SELECT * FROM CUSTOMERS;
    

    The table is displayed as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Since, we only deleted records from CUSTOMERS table, the changes will not be reflected in the ORDERS table. We can verify it using the following query.

    SELECT * FROM ORDERS;
    

    The ORDERS table is displayed as −

    OID DATE CUSTOMER_ID AMOUNT
    102 2009-10-08 00:00:00 3 3000.00
    100 2009-10-08 00:00:00 3 1500.00
    101 2009-11-20 00:00:00 2 1560.00
    103 2008-05-20 00:00:00 4 2060.00

    DELETE… JOIN with WHERE Clause

    The ON clause in DELETE… JOIN query is used to apply constraints on the records. In addition to it, we can also use the WHERE clause to make the filtration stricter. Observe the query below. Here, we are deleting the records of customers, in the CUSTOMERS table, whose salary is lower than Rs. 2000.00.

    DELETE a
    FROM CUSTOMERS AS a INNER JOIN ORDERS AS b
    ON a.ID = b.CUSTOMER_ID
    WHERE a.SALARY < 2000.00;
    

    Output

    On executing the query, following output is displayed.

    Query OK, 1 row affected (0.01 sec)
    

    Verification

    We can verify whether the changes are reflected in a table by retrieving its contents using the SELECT statement as follows −

    SELECT * FROM CUSTOMERS;
    

    The CUSTOMERS table after deletion is as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.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

    Since we only deleted records from the CUSTOMERS table, the changes will not be reflected in the ORDERS table. We can verify it using the following query −

    SELECT * FROM ORDERS;
    

    The ORDERS table is displayed as −

    OID DATE CUSTOMER_ID AMOUNT
    102 2009-10-08 00:00:00 3 3000.00
    100 2009-10-08 00:00:00 3 1500.00
    101 2009-11-20 00:00:00 2 1560.00
    103 2008-05-20 00:00:00 4 2060.00

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Self Join nhận dự án làm có lương

    SQL – Self Join

    Table of content


    Self Join, as its name suggests, is a type of join that combines the records of a table with itself.

    Suppose an organization, while organizing a Christmas party, is choosing a Secret Santa among its employees based on some colors. It is designed to be done by assigning one color to each of its employees and having them pick a color from the pool of various colors. In the end, they will become the Secret Santa of an employee this color is assigned to.

    As we can see in the figure below, the information regarding the colors assigned and a color each employee picked is entered into a table. The table is joined to itself using self join over the color columns to match employees with their Secret Santa.

    Self Join

    The SQL Self Join

    The SQL Self Join is used to join a table to itself as if the table were two tables. To carry this out, alias of the tables should be used at least once.

    Self Join is a type of inner join, which is performed in cases where the comparison between two columns of a same table is required; probably to establish a relationship between them. In other words, a table is joined with itself when it contains both Foreign Key and Primary Key in it.

    Unlike queries of other joins, we use WHERE clause to specify the condition for the table to combine with itself; instead of the ON clause.

    Syntax

    Following is the basic syntax of SQL Self Join −

    SELECT column_name(s)
    FROM table1 a, table1 b
    WHERE a.common_field = b.common_field;
    

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

    Example

    Self Join only requires one table, so, let us create a CUSTOMERS table containing the customer details like their names, age, address and the salary they earn.

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

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

    INSERT INTO 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 −

    ID NAME AGE ADDRESS SALARY
    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

    Now, let us join this table using the following Self Join query. Our aim is to establish a relationship among the said Customers on the basis of their earnings. We are doing this with the help of the WHERE clause.

    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 < b.SALARY;
    

    Output

    The resultant table displayed will list out all the customers that earn lesser than other customers −

    ID EARNS_HIGHER EARNS_LESS LOWER_SALARY
    2 Ramesh Khilan 1500.00
    2 Kaushik Khilan 1500.00
    6 Chaitali Komal 4500.00
    3 Chaitali Kaushik 2000.00
    2 Chaitali Khilan 1500.00
    1 Chaitali Ramesh 2000.00
    6 Hardik Komal 4500.00
    4 Hardik Chaitali 6500.00
    3 Hardik Kaushik 2000.00
    2 Hardik Khilan 1500.00
    1 Hardik Ramesh 2000.00
    3 Komal Kaushik 2000.00
    2 Komal Khilan 1500.00
    1 Komal Ramesh 2000.00
    6 Muffy Komal 4500.00
    5 Muffy Hardik 8500.00
    4 Muffy Chaitali 6500.00
    3 Muffy Kaushik 2000.00
    2 Muffy Khilan 1500.00
    1 Muffy Ramesh 2000.00

    Self Join with ORDER BY Clause

    After joining a table with itself using self join, the records in the combined table can also be sorted in an order, using the ORDER BY clause.

    Syntax

    Following is the syntax for it −

    SELECT column_name(s)
    FROM table1 a, table1 b
    WHERE a.common_field = b.common_field
    ORDER BY column_name;
    

    Example

    Let us join the CUSTOMERS table with itself using self join on a WHERE clause; then, arrange the records in an ascending order using the ORDER BY clause with respect to a specified column, as shown in the following query.

    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 < b.SALARY
    ORDER BY a.SALARY;
    

    Output

    The resultant table is displayed as follows −

    ID EARNS_HIGHER EARNS_LESS LOWER_SALARY
    2 Ramesh Khilan 1500.00
    2 Kaushik Khilan 1500.00
    2 Chaitali Khilan 1500.00
    2 Hardik Khilan 1500.00
    2 Komal Khilan 1500.00
    2 Muffy Khilan 1500.00
    3 Chaitali Kaushik 2000.00
    1 Chaitali Ramesh 2000.00
    3 Hardik Kaushik 2000.00
    1 Hardik Ramesh 2000.00
    3 Komal Kaushik 2000.00
    1 Komal Ramesh 2000.00
    3 Muffy Kaushik 2000.00
    1 Muffy Ramesh 2000.00
    6 Chaitali Komal 4500.00
    6 Hardik Komal 4500.00
    6 Muffy Komal 4500.00
    4 Hardik Chaitali 6500.00
    4 Muffy Chaitali 6500.00
    5 Muffy Hardik 8500.00

    Not just the salary column, the records can be sorted based on the alphabetical order of names, numerical order of Customer IDs etc.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Update Join nhận dự án làm có lương

    SQL – UPDATE JOIN

    Table of content


    To update the data entered in a single database table using SQL, you can use the UPDATE statement. However, to update the data in multiple database tables, we need to use the UPDATE… JOIN clause.

    For instance, if a student changes their primary phone number and wishes to update it in their organizational database, the information needs to be modified in multiple tables like student records, laboratory records, canteen passes etc. Using the JOIN clause, you can combine all these tables into one, and then using UPDATE statement, you can update the student data in them simultaneously.

    The SQL UPDATE… JOIN Clause

    The UPDATE statement only modifies the data in a single table and JOINS in SQL are used to fetch the combination of rows from multiple tables, with respect to a matching field.

    If we want to update data in multiple tables, we can combine multiple tables into one using JOINS and then update them using UPDATE statement. This is also known as cross-table modification.

    Syntax

    Following is the basic syntax of the SQL UPDATE… JOIN statement −

    UPDATE table(s)
    JOIN table2 ON table1.join_column = table2.join_column
    SET table1.column1 = table2.new_value1,
        table1.column2 = table2.new_value2;
    

    Where, JOIN can be: Regular Join, Natural Join, Inner Join, Outer Join, Left Join, Right Join, Full Join etc.

    Example

    Assume we have created a table named CUSTOMERS, which contains the personal details of customers including their name, age, address and salary etc., using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

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

    INSERT INTO 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 −

    ID NAME AGE ADDRESS SALARY
    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

    Let us create another table ORDERS, containing the details of orders made and the date they are made on.

    CREATE TABLE ORDERS (
       OID INT NOT NULL,
       DATE VARCHAR (20) NOT NULL,
       CUSTOMER_ID INT NOT NULL,
       AMOUNT DECIMAL (18, 2)
    );
    

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

    INSERT INTO ORDERS VALUES
    (102, ''2009-10-08 00:00:00'', 3, 3000.00),
    (100, ''2009-10-08 00:00:00'', 3, 1500.00),
    (101, ''2009-11-20 00:00:00'', 2, 1560.00),
    (103, ''2008-05-20 00:00:00'', 4, 2060.00);
    

    The table is displayed as follows −

    OID DATE CUSTOMER_ID AMOUNT
    102 2009-10-08 00:00:00 3 3000.00
    100 2009-10-08 00:00:00 3 1500.00
    101 2009-11-20 00:00:00 2 1560.00
    103 2008-05-20 00:00:00 4 2060.00

    Following UPDATE… JOIN query increments the salary of customers by 1000 with respect to the inflation of their order amount by 500 −

    UPDATE CUSTOMERS
    JOIN ORDERS
    ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
    SET CUSTOMERS.SALARY = CUSTOMERS.SALARY + 1000,
    ORDERS.AMOUNT = ORDERS.AMOUNT + 500;
    

    Verification

    We can verify whether the changes are reflected in a table by retrieving its contents using the SELECT statement as follows −

    SELECT * FROM CUSTOMERS;
    

    The updated CUSTOMERS table is displayed as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 2500.00
    3 Kaushik 23 Kota 3000.00
    4 Chaitali 25 Mumbai 7500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Now, check whether the ORDERS table is updated using the following SELECT statement −

    SELECT * FROM ORDERS;
    

    The updated ORDERS table is displayed as follows −

    OID DATE CUSTOMER_ID AMOUNT
    102 2009-10-08 00:00:00 3 3500.00
    100 2009-10-08 00:00:00 3 2000.00
    101 2009-11-20 00:00:00 2 2060.00
    103 2008-05-20 00:00:00 4 2560.00

    UPDATE… JOIN with WHERE Clause

    While updating records from multiple tables, if we use the WHERE clause along with the UPDATE… JOIN statement we can filter the records to be updated (from the combined result set).

    Syntax

    The syntax of SQL UPDATE… JOIN with WHERE clause in MySQL database is as follows −

    UPDATE table(s)
    JOIN table2 ON column3 = column4
    SET table1.column1 = value1, table1.column2 = value2, ...
    WHERE condition;
    

    Example

    Now, let us execute the following query to increase the salary of customer whose id is 3

    UPDATE CUSTOMERS
    LEFT JOIN ORDERS
    ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
    SET CUSTOMERS.SALARY = CUSTOMERS.SALARY + 1000
    WHERE ORDERS.CUSTOMER_ID = 3;
    

    Verification

    We can verify whether the changes are reflected in a table by retrieving its contents using the SELECT statement as follows.

    SELECT * FROM CUSTOMERS;
    

    As we can see in the table below, SALARY value of “Kaushik” is increased by 1000 −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 3000.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 UPDATE… JOIN Clause in SQL Server

    The SQL UPDATE… JOIN Clause also works in SQL Server database. But, the syntax of the query is slightly different from that of MySQL. However, the working of it is exactly the same as MySQL query.

    In MySQL, the UPDATE statement is followed by the JOIN clause and SET statements respectively. Whereas, in MS SQL Server the SET statement is followed by the JOIN clause.

    Syntax

    Following is the syntax of the UPDATE… JOIN in SQL Server −

    UPDATE tables(s)
    SET column1 = value1, column2 = value2, ...
    FROM table1
    JOIN table2 ON table1.join_column = table2.join_column;
    

    Example

    In this example, we will update values of the CUSTOMERS and ORDERS table that we created above; using the following UPDATE… JOIN query −

    UPDATE CUSTOMERS
    SET SALARY = SALARY + 1000
    FROM CUSTOMERS
    JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
    

    Verification

    We can verify whether the changes are reflected in a table by retrieving its contents using the SELECT statement as follows.

    SELECT * FROM CUSTOMERS;
    

    The updated CUSTOMERS table is displayed as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 2500.00
    3 Kaushik 23 Kota 3000.00
    4 Chaitali 25 Mumbai 7500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Union vs Join nhận dự án làm có lương

    UNION vs JOIN

    Table of content


    SQL provides various relational operators to handle data that is spread across multiple tables in a relational database. Out of them, UNION and JOIN queries are fundamentally used to combine data from multiple tables.

    Even though they are both used for the same purpose, i.e. to combine tables, there are many differences between the working of these operators. The major difference is that the UNION operator combines data from multiple similar tables irrespective of the data relativity, whereas, the JOIN operator is only used to combine relative data from multiple tables.

    Working of UNION

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

    The tables are said to be union compatible if they follow the conditions given below −

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

    Once these criteria are met, UNION operator returns all the rows from multiple tables, after eliminating duplicate rows, as a resultant table.

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

    Syntax

    Following is the syntax of the SQL UNION operator −

    SELECT * FROM table1
    UNION
    SELECT * FROM table2;
    

    Example

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

    Create table COURSES_PICKED using the following query −

    CREATE TABLE COURSES_PICKED(
       STUDENT_ID INT NOT NULL,
       STUDENT_NAME VARCHAR(30) NOT NULL,
       COURSE_NAME VARCHAR(30) NOT NULL
    );
    

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

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

    Create table EXTRA_COURSES_PICKED using the following query −

    CREATE TABLE EXTRA_COURSES_PICKED(
       STUDENT_ID INT NOT NULL,
       STUDENT_NAME VARCHAR(30) NOT NULL,
       EXTRA_COURSE_NAME VARCHAR(30) NOT NULL
    );
    

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

    INSERT INTO EXTRA_COURSES_PICKED VALUES
    (1, ''JOHN'', ''PHYSICAL EDUCATION''),
    (2, ''ROBERT'', ''GYM''),
    (3, ''SASHA'', ''FILM''),
    (4, ''JULIAN'', ''PHOTOGRAPHY'');
    

    Now, let us combine the tables COURSES_PICKED and EXTRA_COURSES_PICKED, using the UNION query as follows −

    SELECT * FROM COURSES_PICKED
    UNION
    SELECT * FROM EXTRA_COURSES_PICKED;
    

    Output

    The resultant table obtained after performing the UNION operation is −

    STUDENT_ID STUDENT_NAME COURSE_NAME
    1 Jhon English
    1 Jhon Physical Education
    2 Robert Computer Science
    2 Robert Gym
    3 Shasha Communications
    3 Shasha Film
    4 Julian Mathematics
    4 Julian Photography

    Working of JOIN

    The Join operation is used to combine information from multiple related tables into one, based on their common fields. This operation can be used with various clauses like ON, WHERE, ORDER BY, GROUP BY etc.

    There are two types of Joins −

    • Inner Join
    • Outer Join

    The basic type of join is an Inner Join, which only retrieves the matching values of common columns. It is a default join.

    The result table of the Outer join includes both matched and unmatched rows from the first table. It is divided into subtypes like Left Join, Right Join, and Full Join.

    Syntax

    Following is the basic syntax of a Join operation in SQL −

    SELECT column_name(s)
    FROM table1
    JOIN table2
    ON table1.column_name = table2.column_name;
    

    Example

    In the following example, we will join the same tables we created above, i.e., COURSES_PICKED and EXTRA_COURSES_PICKED, using the query below –

    SELECT c.STUDENT_ID, c.STUDENT_NAME, COURSE_NAME, COURSES_PICKED
    FROM COURSES_PICKED c
    JOIN EXTRA_COURSES_PICKED e
    ON c.STUDENT_ID = e.STUDENT_ID;
    

    Output

    The resultant table will be displayed as follows −

    STUDENT_ID STUDENT_NAME COURSE_NAME COURSE_PICKED
    1 Jhon ENGLISH Physical Education
    2 Robert COMPUTER SCIENCE Gym
    3 Shasha COMMUNICATIONS Film
    4 Julian MATHEMATICS Photography

    UNION Vs JOIN

    As we saw in the examples given above, the UNION operator is only executable on tables that are union compatible, whereas, the JOIN operator joins two tables that need not be compatible but should be related.

    Let us summarize all the difference between these queries below −

    UNION JOIN
    UNION operation is only performed on tables that are union compatible, i.e., the tables must contain same number of columns with same data type. JOIN operation can be performed on tables that has at least one common field between them. The tables need not be union compatible.
    The data combined will be added as new rows of the resultant table. The data combined will be adjoined into the resultant table as new columns.
    This works as the conjunction operation. This works as an intersection operation.
    UNION removes all the duplicate values from the resultant tables. JOIN retains all the values from both tables even if they”re redundant.
    UNION does not need any additional clause to combine two tables. JOIN needs an additional clause ON to combine two tables based on a common field.
    It is mostly used in scenarios like, merging the old employees list in an organization with the new employees list. This is used in scenarios where merging related tables is necessary. For example, combining tables containing customers list and the orders they made.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Unique Key nhận dự án làm có lương

    SQL – Unique Key

    Table of content


    The SQL Unique Key

    The SQL Unique Key (or, Unique constraint) does not allow duplicate values in a column of a table. It prevents two records from having same values in a column.

    Unique Key is just an alternative to the Primary Key; as both Unique and Primary Key constraints ensure uniqueness in a column of the table.

    Suppose we have a table named CUSTOMERS to store the customer records in a Bank and if one of the column names is MOBILE_NO then, we can create a UNIQUE constraint on this column to prevent the entry of multiple records with the same mobile number.

    Features of Unique Keys

    Following is the list of some key features of the Unique Key in an SQL database −

    • The unique key is similar to the primary key in a table, but it can accept NULL values, whereas the primary key does not.

    • It accepts only one NULL value.

    • It cannot have duplicate values.

    • It can also be used as a foreign key in another table.

    • A table can have more than one Unique column.

    Creating SQL Unique Key

    You can create a Unique Key on a database table using the UNIQUE keyword in SQL. While creating a database table, specify this SQL keyword along with the column (where this key needs to be defined on).

    Syntax

    Following is the syntax to create a UNIQUE key constraint on a column in a table −

    CREATE TABLE table_name(
       column1 datatype UNIQUE KEY,
       column2 datatype,
       .....
       .....
       columnN datatype
    );
    

    Example

    Using the following SQL query, we are creating a table named CUSTOMERS with five fields ID, NAME, AGE, ADDRESS, and SALARY in it. Here, we are creating a Unique Key on the ID column.

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL UNIQUE KEY,
       NAME VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2)
    );
    

    Output

    Following is the output of the above SQL statement −

    Query OK, 0 rows affected (0.03 sec)
    

    Verification

    Since we have created a UNIQUE constraint on the column named ID, we cannot insert duplicate values in it. Let us verify by inserting the following records with duplicate ID values into the CUSTOMERS table −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (1, ''Khilan'', 25, ''Delhi'', 1500.00 );
    

    On execution, following error is displayed proving that the UNIQUE constraint is indeed defined on the ID column −

    ERROR 1062 (23000): Duplicate entry ''1'' for key ''customers.ID''
    

    Multiple Unique Keys

    We can create one or more Unique Keys on one or more columns in an SQL table.

    Syntax

    Following is the syntax to create unique key constraints on multiple columns in a table −

    CREATE TABLE table_name(
       column1 datatype UNIQUE KEY,
       column2 datatype UNIQUE KEY,
       .....
       .....
       columnN datatype
    );
    

    Example

    Assume we have created a table with the name CUSTOMERS in the SQL database using CREATE TABLE statement. A Unique key is defined on columns ID and NAME using the UNIQUE keyword as shown below −

    CREATE TABLE BUYERS (
       ID INT NOT NULL UNIQUE KEY,
       NAME VARCHAR(20) NOT NULL UNIQUE KEY,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2)
    );
    

    Output

    Following is the output of the above SQL statement −

    Query OK, 0 rows affected (0.03 sec)
    

    Verification

    Since we have created a UNIQUE constraint on the column named ID and NAME, we cannot insert duplicate values in it. Let us verify by inserting duplicate records into the BUYERS table using the following INSERT statement −

    INSERT INTO BUYERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (1, ''Rajesh'', 25, ''Delhi'', 1500.00 );
    

    Following error is displayed −

    ERROR 1062 (23000): Duplicate entry ''1'' for key ''customers.ID''
    

    In the same way if you try to insert the another record with duplicate value for the column NAME as −

    INSERT INTO BUYERS VALUES (2, ''Ramesh'', 36, ''Chennai'', 1700.00 );
    

    Following error is generated −

    ERROR 1062 (23000): Duplicate entry ''Ramesh'' for key ''buyers.NAME''
    

    Unique Key on an Existing Column

    Until now, we have only seen how to define a Unique Key on a column while creating a new table. But, we can also add a unique key on an existing column of a table. This is done using the ALTER TABLE… ADD CONSTRAINT statement.

    Syntax

    Following is the syntax to create a unique constraint on existing columns of a table −

    ALTER TABLE table_name ADD CONSTRAINT
    UNIQUE_KEY_NAME UNIQUE (column_name);
    

    Note − Here the UNIQUE_KEY_NAME is just the name of the UNIQUE KEY. It is optional to specify and is used to drop the constraint from the column in a table.

    Example

    In this example, we add a Unique Key on the ADDRESS column of the existing CUSTOMERS table −

    ALTER TABLE CUSTOMERS ADD CONSTRAINT
    UNIQUE_ADDRESS UNIQUE(ADDRESS);
    

    Output

    Following is the output of the above statement −

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

    Dropping an SQL Unique Key

    If you have already created a unique key on a column, you can drop it whenever it is not needed. To drop the Unique Key from the column of a table, you need to use the ALTER TABLE statement.

    Syntax

    Following is the SQL query to drop the UNIQUE constraint from the column of a table −

    ALTER TABLE table_name DROP CONSTRAINT UNIQUE_KEY_NAME;
    

    Example

    Consider the CUSTOMERS table created above, we have created the UNIQUE constraints on three columns named ID, NAME and ADDRESS; drop the UNIQUE constraints from the column ADDRESS by executing the following SQL query −

    ALTER TABLE CUSTOMERS DROP CONSTRAINT UNIQUE_ADDRESS;
    

    Output

    Following is the output of the above statement −

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

    Verification

    Now, let us insert two duplicate records of column ADDRESS −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Ahmedabad'', 1500.00 );
    

    If you verify the contents of the table, you can observe that both the records have the same ADDRESS as shown below −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Ahmedabad 1500.00

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – UNION vs UNION ALL nhận dự án làm có lương

    SQL – UNION vs UNION ALL

    Table of content


    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
    UNION
    SELECT * 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 −

    CREATE TABLE COURSES_PICKED(
       STUDENT_ID INT NOT NULL,
       STUDENT_NAME VARCHAR(30) NOT NULL,
       COURSE_NAME VARCHAR(30) NOT NULL
    );
    

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

    INSERT INTO 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_ID STUDENT_NAME COURSE_NAME
    1 JOHN ENGLISH
    2 ROBERT COMPUTER SCIENCE
    3 SASHA COMMUNICATIONS
    4 JULIAN MATHEMATICS

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

    CREATE TABLE EXTRA_COURSES_PICKED(
       STUDENT_ID INT NOT NULL,
       STUDENT_NAME VARCHAR(30) NOT NULL,
       EXTRA_COURSE_NAME VARCHAR(30) NOT NULL
    );
    

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

    INSERT INTO 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_ID STUDENT_NAME COURSES_PICKED
    1 JOHN PHYSICAL EDUCATION
    2 ROBERT GYM
    3 SASHA FILM
    4 JULIAN MATHEMATICS

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

    SELECT * FROM COURSES_PICKED
    UNION
    SELECT * FROM EXTRA_COURSES_PICKED;
    

    Output

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

    STUDENT_ID STUDENT_NAME COURSE_NAME
    1 JOHN ENGLISH
    2 ROBERT COMPUTER SCIENCE
    3 SASHA COMMUNICATIONS
    4 JULIAN MATHEMATICS
    1 JOHN PHYSICAL EDUCATION
    2 ROBERT GYM
    3 SASHA FILM

    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
    UNION ALL
    SELECT * 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
    UNION ALL
    SELECT * FROM EXTRA_COURSES_PICKED;
    

    Output

    The resultant table is displayed as follows −

    STUDENT_ID STUDENT_NAME COURSE_NAME
    1 JOHN ENGLISH
    2 ROBERT COMPUTER SCIENCE
    3 SASHA COMMUNICATIONS
    4 JULIAN MATHEMATICS
    1 JOHN PHYSICAL EDUCATION
    2 ROBERT GYM
    3 SASHA FILM
    4 JULIAN MATHEMATICS

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – INTERSECT Operator nhận dự án làm có lương

    SQL – INTERSECT

    Table of content


    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
    INTERSECT
    SELECT 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 −

    CREATE TABLE STUDENTS(
       ID INT NOT NULL,
       NAME VARCHAR(20) NOT NULL,
       SUBJECT VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       HOBBY VARCHAR(20) NOT NULL,
       PRIMARY KEY(ID)
    );
    

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

    INSERT INTO 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 −

    ID NAME SUBJECT AGE HOBBY
    1 Naina Mathematics 24 Cricket
    2 Varun Physics 26 Football
    3 Dev Mathematics 23 Cricket
    4 Priya Physics 25 Cricket
    5 Adithya Chemistry 21 Cricket
    6 Kalyan Mathematics 30 Football

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

    CREATE TABLE STUDENTS_HOBBY(
       ID INT NOT NULL,
       NAME VARCHAR(20) NOT NULL,
       HOBBY VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       PRIMARY KEY(ID)
    );
    

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

    INSERT INTO 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 −

    ID NAME HOBBY AGE
    1 Vijay Cricket 18
    2 Varun Football 26
    3 Surya Cricket 19
    4 Karthik Cricket 25
    5 Sunny Football 26
    6 Dev Cricket 23

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

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

    Output

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

    NAME AGE HOBBY
    Dev 23 Cricket
    Varun 26 Football

    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 BETWEEN 25 AND 30
    INTERSECT
    SELECT NAME, AGE, HOBBY FROM STUDENTS
    WHERE AGE BETWEEN 20 AND 30;
    

    Output

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

    NAME AGE HOBBY
    Varun 26 Football

    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'')
    INTERSECT
    SELECT NAME, AGE, HOBBY FROM STUDENTS
    WHERE HOBBY IN(''Cricket'');
    

    Output

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

    NAME AGE HOBBY
    Dev 23 Cricket

    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%''
    INTERSECT
    SELECT NAME, AGE, HOBBY FROM STUDENTS
    WHERE NAME LIKE ''v%
    

    Output

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

    NAME AGE HOBBY
    Varun 26 Football

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – EXCEPT Operator nhận dự án làm có lương

    SQL – EXCEPT

    Table of content


    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] //optional
    EXCEPT
    SELECT 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 −

    CREATE TABLE STUDENTS(
       ID INT NOT NULL,
       NAME VARCHAR(20) NOT NULL,
       SUBJECT VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       HOBBY VARCHAR(20) NOT NULL,
       PRIMARY KEY(ID)
    );
    

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

    INSERT INTO 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 −

    ID NAME SUBJECT AGE HOBBY
    1 Naina Mathematics 24 Cricket
    2 Varun Physics 26 Football
    3 Dev Mathematics 23 Cricket
    4 Priya Physics 25 Cricket
    5 Aditya Chemistry 21 Cricket
    6 Kalyan Mathematics 30 Football
    7 Aditya Chemistry 21 Cricket
    8 Kalyan Chemistry 32 Cricket

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

    CREATE TABLE STUDENTS_HOBBY(
       ID INT NOT NULL,
       NAME VARCHAR(20) NOT NULL,
       HOBBY VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       PRIMARY KEY(ID)
    );
    

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

    INSERT INTO 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 −

    ID NAME HOBBY AGE
    1 Vijay Cricket 18
    2 Varun Football 26
    3 Surya Cricket 19
    4 Karthik Cricket 25
    5 Sunny Football 26
    6 Dev Cricket 23

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

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

    Output

    Output of the above query is as shown below −

    NAME HOBBY AGE
    Aditya Cricket 21
    Kalyan Cricket 32
    Kalyan Football 30
    Naina Cricket 24
    Priya Cricket 25

    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 BETWEEN 20 AND 30
    EXCEPT
    SELECT NAME, HOBBY, AGE
    FROM STUDENTS_HOBBY
    WHERE AGE BETWEEN 20 AND 30
    

    Output

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

    NAME HOBBY AGE
    Aditya Cricket 21
    Kalyan Football 30
    Naina Cricket 24
    Priya Cricket 25

    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'')
    EXCEPT
    SELECT NAME, HOBBY, AGE FROM STUDENTS_HOBBY
    WHERE HOBBY IN(''Cricket'')
    

    Output

    Following is the output of the above query −

    NAME HOBBY AGE
    Aditya Cricket 21
    Kalyan Cricket 32
    Naina Cricket 24
    Priya Cricket 25

    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%''
    EXCEPT
    SELECT ID, NAME, HOBBY, AGE FROM STUDENTS_HOBBY
    WHERE HOBBY LIKE ''F%
    

    Output

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

    ID NAME HOBBY AGE
    6 Kalyan Football 30

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc