MySQL JOINS Are Used With SELECT Statement
MySQL JOINS Are Used With SELECT Statement
MySQL JOINS are used with SELECT statement. It is used to retrieve data from multiple tables. It is
performed whenever you need to fetch records from two or more tables.
joins:
o MySQL INNER JOIN (or sometimes called simple join)
o MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
o MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
o MySQL Inner JOIN (Simple Join)
o The MySQL INNER JOIN
o is used to return all rows from multiple tables where the join condition is satisfied. It is the
most common type of join.
o Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
mage representation:
Consider two tables "officers" and "students", having the following data.
Image representation:
Consider two tables "officers" and "students", having the following data.
Execute the following query:
1. SELECT officers.officer_name, officers.address, students.course_name, students
.student_name
2. FROM officers
3. RIGHT JOIN students
4. ON officers.officer_id = students.student_id;
Output:
SQL Subquery
The Subquery or Inner query is an SQL query placed inside another SQL query. It is embedded in the
HAVING or WHERE clause of the SQL statements.
Following are the important rules which must be followed by the SQL Subquery:
1. The SQL subqueries can be used with the following statements along with the SQL expression
operators:
SELECT statement,
UPDATE statement,
INSERT statement, and
DELETE statement.
2. The subqueries in SQL are always enclosed in the parenthesis and placed on the right side of the
SQL operators.
3. We cannot use the ORDER BY clause in the subquery. But, we can use the GROUP BY clause, which
performs the same function as the ORDER BY clause.
4. If the subquery returns more than one record, we have to use the multiple value operators before
the Subquery.
5. We can use the BETWEEN operator within the subquery but not with the subquery.
Example 1: This example uses the Greater than comparison operator with the Subquery.
Let's take the following table named Student_Details, which contains Student_RollNo.,
Stu_Name, Stu_Marks, and Stu_City column.
The following SQL query returns the record of those students whose marks are greater than the
average of total marks:
SELECT * FROM Student_Details WHERE Stu_Marks> ( SELECT AVG(Stu_Marks ) FROM
Student_Details);
Example 2: This example uses the IN operator with the subquery.
Let's take the following two tables named Faculty_Details and Department tables. The
Faculty_Details table contains ID, Name, Dept_ID, and address of faculties. And, the Department
table contains the Dept_ID, Faculty_ID, and Dept_Name.
WHERE Emp_ID = ANY( SELECT Emp_ID FROM Department WHERE Dept_ID = 407 OR Dept_ID =
406 );
Now, check the details of the New_Employee table by using the following SELECT statement: