Teachnique
      CourseRoadmaps
      Login

      HomeIntroductionFeaturesVersionsVariablesInstallationAdministrationPHP SyntaxNode.js SyntaxJava SyntaxPython SyntaxConnectionWorkbench

      Create DatabaseDrop DatabaseSelect DatabaseShow DatabaseCopy DatabaseDatabase ExportDatabase ImportDatabase Info

      Create UsersDrop UsersShow UsersChange PasswordGrant PrivilegesShow PrivilegesRevoke PrivilegesLock User AccountUnlock User Account

      Create TablesShow TablesAlter TablesRename TablesClone TablesTruncate TablesTemporary TablesRepair TablesDescribe TablesAdd/Delete ColumnsShow ColumnsRename ColumnsTable LockingDrop TablesDerived Tables

      QueriesConstraintsInsert QuerySelect QueryUpdate QueryDelete QueryReplace QueryInsert IgnoreInsert on Duplicate Key UpdateInsert Into Select

      Create ViewsUpdate ViewsDrop ViewsRename Views

      IndexesCreate IndexDrop IndexShow IndexesUnique IndexClustered IndexNon-Clustered Index

      Where ClauseLimit ClauseDistinct ClauseOrder By ClauseGroup By ClauseHaving ClauseAND OperatorOR OperatorLike OperatorIN OperatorANY OperatorEXISTS OperatorNOT OperatorNOT EQUAL OperatorIS NULL OperatorIS NOT NULL OperatorBetween OperatorUNION OperatorUNION vs UNION ALLMINUS OperatorINTERSECT OperatorINTERVAL Operator

      Using JoinsInner JoinLeft JoinRight JoinCross JoinFull JoinSelf JoinDelete JoinUpdate JoinUnion vs Join

      Unique KeyPrimary KeyForeign KeyComposite KeyAlternate Key

      TriggersCreate TriggerShow TriggerDrop TriggerBefore Insert TriggerAfter Insert TriggerBefore Update TriggerAfter Update TriggerBefore Delete TriggerAfter Delete Trigger

      Data TypesVARCHARBOOLEANENUMDECIMALINTFLOATBITTINYINTBLOBSET

      Regular ExpressionsRLIKE OperatorNOT LIKE OperatorNOT REGEXP Operatorregexp_instr() Functionregexp_like() Functionregexp_replace() Functionregexp_substr() Function

      Fulltext SearchNatural Language Fulltext SearchBoolean Fulltext SearchQuery Expansion Fulltext Searchngram Fulltext Parser

      Date and Time FunctionsArithmetic OperatorsNumeric FunctionsString FunctionsAggregate Functions

      NULL ValuesTransactionsUsing SequencesHandling DuplicatesSQL InjectionSubQueryCommentsCheck ConstraintsStorage EnginesExport Table into CSV FileImport CSV File into DatabaseUUIDCommon Table ExpressionsOn Delete CascadeUpsertHorizontal PartitioningVertical PartitioningCursorStored FunctionsSignalResignalCharacter SetCollationWildcardsAliasROLLUPToday DateLiteralsStored ProcedureExplainJSONStandard DeviationFind Duplicate RecordsDelete Duplicate RecordsSelect Random RecordsShow ProcesslistChange Column TypeReset Auto-IncrementCoalesce() Function

      Useful FunctionsStatements ReferenceQuick GuideUseful ResourcesDiscussion

      Feedback

      Submit request if you have any questions.

      Course
      Cross Join

      MySQL Tutorial

      This SQL tutorial is structured for beginners to guide them from the foundational concepts to advanced data manipulation and querying techniques in SQL. By the end of this tutorial, you will have developed a robust understanding of SQL, equipping you with the knowledge to efficiently manage and analyze data across various database systems. This guide sets the stage for your growth into a skilled data professional, ready to tackle complex data challenges and contribute to the field of data analysis and database management.

       Cross Join

      MySQL Cross Join

      A MySQL Cross Join combines each row of the first table with each row of second table. It is a basic type of inner join that is used to retrieve the Cartesian product (or cross product) of two individual tables (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.
      

      Syntax

      Following is the basic syntax of the Cross Join query in MySQL −
      SELECT column_name(s)
      FROM table1
      CROSS JOIN table2
      

      Example

      In this example of cross join, let us first create a table named CUSTOMERS, which contains personal details of customers including their name, age, address and salary etc.
      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 MySQL −
      SELECT column_name(s)
      FROM table1
      CROSS JOIN table2
      CROSS JOIN table3
      CROSS JOIN table4
      .
      .
      .
      

      Example

      Let us now combine three tables CUSTOMERS, ORDERS and ORDER_RANGE, to demonstrate combining multiple tables using cross join.
      We will create the ORDER_RANGE table using the query below −
      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 as follows −
      SNO
      ORDER_RANGE
      1
      1-100
      2
      100-200
      3
      200-300
      Now we use the following cross join query on the given tables,
      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

      Cross Join Using Client Program

      We can also perform the Cross join operation on one or more tables using a client program.

      Syntax

      PHPNodeJSJavaPython
      To perform cross Join through a PHP program, we need to execute the SQL query with CROSS JOIN clause using the mysqli function query() as follows −
      $sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a CROSS JOIN tcount_tbl b";
      $mysqli->query($sql);
      

      Example

      Following are the programs −
      PHPNodeJSJavaPython
      $dbhost = 'localhost';
      $dbuser = 'root';
      $dbpass = 'password';
      $dbname = 'TUTORIALS';
      $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
      if ($mysqli->connect_errno) {
      printf("Connect failed: %s", $mysqli->connect_error);
      exit();
      }
      // printf('Connected successfully.');
      
      $sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
      FROM tutorials_tbl a CROSS JOIN tcount_tbl b';
      $result = $mysqli->query($sql);
      if ($result->num_rows > 0) {
      echo " following is the details after executing cross join! \n";
      while ($row = $result->fetch_assoc()) {
      printf("Id: %s, Author: %s, Count: %d", $row["tutorial_id"], $row["tutorial_author"], $row["tutorial_count"]);
      printf("\n");
      }
      } else {
      printf('No record found.');
      }
      mysqli_free_result($result);
      $mysqli->close();
      

      Output

      The output obtained is as follows −
      following is the details after executing cross join!
      Id: 102, Author: Sarika Singh, Count: 20
      Id: 101, Author: Aman kumar, Count: 20
      Id: 3, Author: Sanjay, Count: 20
      Id: 2, Author: Abdul S, Count: 20
      Id: 1, Author: John Poul, Count: 20
      Id: 102, Author: Sarika Singh, Count: 5
      Id: 101, Author: Aman kumar, Count: 5
      Id: 3, Author: Sanjay, Count: 5
      Id: 2, Author: Abdul S, Count: 5
      Id: 1, Author: John Poul, Count: 5
      Id: 102, Author: Sarika Singh, Count: 4
      Id: 101, Author: Aman kumar, Count: 4
      Id: 3, Author: Sanjay, Count: 4
      Id: 2, Author: Abdul S, Count: 4
      Id: 1, Author: John Poul, Count: 4
      Id: 102, Author: Sarika Singh, Count: 20
      Id: 101, Author: Aman kumar, Count: 20
      Id: 3, Author: Sanjay, Count: 20
      Id: 2, Author: Abdul S, Count: 20
      Id: 1, Author: John Poul, Count: 20
      Id: 102, Author: Sarika Singh, Count: 1
      Id: 101, Author: Aman kumar, Count: 1
      Id: 3, Author: Sanjay, Count: 1
      Id: 2, Author: Abdul S, Count: 1
      Id: 1, Author: John Poul, Count: 1
      Id: 102, Author: Sarika Singh, Count: 1
      Id: 101, Author: Aman kumar, Count: 1
      Id: 3, Author: Sanjay, Count: 1
      Id: 2, Author: Abdul S, Count: 1
      Id: 1, Author: John Poul, Count: 1