SQL NOTES
SQL NOTES
Rows = Records
Columns = Fields/Attributes
We can create, update, delete, and retrieve data in databases like MySQL, Oracle,
PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.
SQL is a standard language for storing, manipulating and retrieving data in databases.
SQL enables users to perform a variety of tasks such as querying data, creating and
modifying database structures, and managing access permissions.
SQL became a standard of the American National Standards Institute (ANSI) in
1986, and of the International Organization for Standardization (ISO) in 1987
SQL was invented in 1970s and was first commercially distributed by Oracle.
The original name was given by IBM as Structured English Query Language,
abbreviated by the acronym SEQUEL.
Although SQL is an ANSI/ISO standard, there are different versions of the SQL
language.
However, to be compliant with the ANSI standard, they all support at least the
major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar
manner.
Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
In MySQL, example:
DELIMITER //
DELIMITER ;
sql
CopyEdit
CALL GetEmployeeById(101);
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database
systems that allow more than one SQL statement to be executed in the same call to
the server.
There are certain rules for SQL which would ensure consistency and functionality across
databases. By following these rules, queries will be well formed and well executed in any
database.
Statement Termination: Every SQL statement ends with a semicolon (;),
signaling the DBMS to execute the command.
Case Insensitivity: SQL keywords (e.g., SELECT, INSERT) are case-insensitive, but
database names and column names may be case-sensitive depending on the
DBMS.
Whitespace Flexibility: SQL statements can span multiple lines, but keywords
and identifiers must be separated by at least one space.
Unique Identifiers: Reserved words (e.g., SELECT, FROM) cannot be used as table
or column names unless enclosed in double quotes (“) or backticks (`), depending
on the DBMS.
• Unique Identifiers: Reserved words (e.g., SELECT, FROM) cannot be used as table or column names
unless enclosed in double quotes (“) or backticks (), depending on the DBMS. this means we can
use them as table names if enclosed in double queotes
ChatGPT said:
Yes, that's correct — reserved words in SQL (like SELECT, FROM, WHERE, etc.) can be used as table or
column names if you enclose them properly, depending on the database system you're using.
DBMS Delimiter for identifiers Example using reserved word SELECT as a table name
PostgreSQL Double quotes (") SELECT * FROM "SELECT";
MySQL Backticks (`) SELECT * FROM `SELECT`;
SQL Server Square brackets ([]) SELECT * FROM [SELECT];
Oracle Double quotes (") SELECT * FROM "SELECT";
Important Notes:
Using reserved words as identifiers (even when quoted) is not recommended for clarity and to avoid
confusion or future issues.
When using quotes/backticks, case sensitivity may also come into play (especially in PostgreSQL
and Oracle).
Example in PostgreSQL:
sql
CopyEdit
CREATE TABLE "SELECT" (
"FROM" INT,
"WHERE" TEXT
);
o Single-line comments: --
o Multi-line comments: /* … */
Data Integrity: Constraints like NOT NULL, UNIQUE, and PRIMARY KEY must be
defined correctly to maintain data consistency.
o Contain up to 30 characters.
Databases
Tables
Views
Indexes
Stored Procedures
Functions
Triggers
TRUNCATE → Deletes all records inside a table but keeps the structure
INSERT INTO Students (StudentID, Name, Age) VALUES (1, 'John Doe', 22);
EXPLAIN Describe the access path to EXPLAIN PLAN FOR SELECT * FROM
PLAN data table_name;
COMMIT;
SAVEPOINT Savepoint1;
-9,223,372,036,854,775,808 to
BIGINT Large integer numbers
9,223,372,036,854,775,807
SMALLMON
Smaller monetary values -214,748.3648 to 214,748.3647
EY
-1.79E+308 to
FLOAT Approximate numeric values
1.79E+308
Deleting a Database
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
Tip: Always back up the database to a different drive than the actual database. Then, if
you get a disk crash, you will not lose your backup file along with the database.
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
Tip: A differential back up reduces the back up time (since only the changes are backed
up).
Output
Till now we have seen how to create a clone of the source table. In the
above backup table, the data is also copied along with the table.
However, we can also create a backup table without copying the data.
3. Backup Table Without Data
So, to create a table without any data being copied we can use
the WHERE clause which needs to return a FALSE value. For example, we
can use WHERE 2<2 or WHERE 1=2.
In this example, we will create a backup table "geeks_student" of
"student_information" table by creating a copy of
"student_information" table and copying its all columns without data.
Query:
CREATE TABLE geeks_student AS SELECT * FROM student_information
WHERE 1!=1;
SELECT * FROM geeks_student;
Output
4. Backup Table with Specific Columns and No Data
In this example, we will create a backup table "geek_student" of
"student_information" table by creating a copy of
"student_information" table and copying specific columns without
data.
Query:
CREATE TABLE specific_empty_backup AS
SELECT ID, Student_Name FROM student_information WHERE 1=2;
SELECT * FROM specific_empty_backup;
Output
SQL Tables
In SQL, a table is a fundamental structure used to store data within a relational database. It organizes
information into rows and columns, facilitating efficient data management and retrieval
The CREATE TABLE command in SQL is used to define a new table
within a database.
A table’s structure, including column names, data types, and
constraints like NOT NULL, PRIMARY KEY, and CHECK, are defined
when it is created in SQL.
Syntax:
CREATE table table_name
(
Column1 datatype (size),
column2 datatype (size),
.
.
columnN datatype(size)
);
Key Terms
table_name: The name you assign to the new table.
column1, column2, … : The names of the columns in the table.
datatype(size): Defines the data type and size of each column.
Constraints in SQL
In SQL, constraints are rules applied to table columns to enforce data integrity and ensure the accuracy and
reliability of the data within the database. They define the limitations on the type of data that can be stored
in a table, preventing invalid data entry and maintaining consistency across related tables.
1. NOT NULL
Ensures that a column cannot have a NULL value. This constraint is used when a column must always
contain a value.
2. UNIQUE
Ensures that all values in a column are distinct. This constraint prevents duplicate values in a column.
3. PRIMARY KEY
Combines the NOT NULL and UNIQUE constraints. It uniquely identifies each record in a table. A table
can have only one primary key, which may consist of single or multiple columns (composite key).
sql
CopyEdit
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY
);
4. FOREIGN KEY
Establishes a relationship between two tables by linking a column in one table to the primary key of another
table. This constraint ensures referential integrity.
Ensures that all values in a column satisfy a specific condition. This constraint is used to limit the range of
values that can be placed in a column.
6. DEFAULT
Sets a default value for a column when no value is specified. This constraint is used to insert a default value
into a column if no value is specified during the insertion of a record.
Modifying Constraints
Adding a Constraint:
Dropping a Constraint:
Syntax:
To Create a Temporary Table
CREATE TABLE #EmpDetails (id INT, name VARCHAR(25))
To Insert Values Into Temporary Table
INSERT INTO #EmpDetails VALUES (01, 'Lalit'), (02, 'Atharva')
To Select Values from the Temporary Table
SELECT * FROM #EmpDetails
Types of Temporary Tables in SQL
There are 2 types of Temporary Tables: Local Temporary Table, and Global
Temporary Table.
1)Local Temporary Table
A Local Temp Table is available only for the session that has created it. It is
automatically dropped (deleted) when the connection that has created it, is
closed. To create Local Temporary Table Single "#" is used as the prefix of
a table name. Also, the user can drop this temporary table by using
the "DROP TABLE #EmpDetails" query. There will be Random Numbers
are appended to the Name of Table Name. If the Temporary Table is
created inside the stored procedure, it get dropped automatically upon the
completion of stored procedure execution.
Example:
CREATE PROCEDURE ProcTemp
AS
BEGIN
CREATE TABLE #EmpDetails
INSERT INTO #EmpDetails VALUES ( 01, 'Lalit'), ( 02, 'Atharva')
SELECT * FROM #EmpDetails
END
EXECUTE ProcTemp
2)Global Temporary Table:
To create a Global Temporary Table, add the "##" symbol before the table
name.
Example:
CREATE TABLE ##EmpDetails (id INT, name VARCHAR(25))
Global Temporary Tables are visible to all connections and Dropped when
the last connection referencing the table is closed. Global Table Name must
have an Unique Table Name. There will be no random Numbers suffixed at
the end of the Table Name.
Differences Between Local and Global Temporary
Tables
Local Temporary
Feature Table Global Temporary Table
Syntax:
DELETE FROM table_name
WHERE some_condition;
Parameter Explanation
Some_condition: A condition used to filter the rows you want to
delete.
table_name: The name of the table from which you want to delete
the rows
Note: We can delete single as well as multiple records depending on the
condition we provide in the WHERE clause. If we omit the WHERE clause
then all of the records will be deleted and the table will be empty.
ALTER Command in SQL?
The ALTER TABLE command in SQL allows us to modify the structure of an
existing table.
Here are some common tasks you can achieve using the ALTER command:
Renaming a table.
Changing a column name.
Adding or deleting columns.
Modifying the data type of a column.
Syntax for ALTER Command
1. Renaming a Table
ALTER TABLE table_name
RENAME TO new_table_name;
2. Renaming a Column
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
3. Adding a New Column
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE table_name
DROP COLUMN column_name;
4. Modifying a Column Data Type
ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype;
SQL SELECT
SQL select command to retrieve data from a database.
With the select command in SQL, users can access data and retrieve
specific records based on various conditions, making it an essential tool for
managing and analyzing data.
Syntax:
SELECT column1,column2.... FROM table_name ;
Example 1: Select Specific Columns
In this example, we will fetch only CustomerName, LastName from the
table Customer:
Query:
SELECT CustomerName, LastName
FROM Customer;
Example 2: Select All Columns
In this example, we will fetch all the fields from the table Customer:
Query:
SELECT * FROM Customer;
Example 3: SELECT Statement with WHERE Clause
Suppose we want to see table values with specific conditions then WHERE
Clause is used with select statement. In this example, filter customers who
are 21 years old.
Query:
SELECT CustomerName
FROM Customer
where Age = '21';
Example 4: SELECT with GROUP BY Clause
In this example, we will use SELECT statement with GROUP BY Clause to
Group rows and perform aggregation. Here, Count orders per customer.
Query:
SELECT Customer_id, COUNT(*) AS order_count
FROM Orders
GROUP BY Customer_id;
Example 5: SELECT Statement with HAVING Clause
Use HAVING to filter results after grouping. Consider the following
database for fetching departments with total salary above 50,000.
Use WHERE for row-level filtering, HAVING for group-level filtering.
Query:
SELECT Department, sum(Salary) as Salary
FROM employee
GROUP BY department
HAVING SUM(Salary) >= 50000;
Example 6: SELECT Statement with ORDER BY clause in SQL
In this example, we will use SELECT Statement with ORDER BY clause.
Here, Sort results by Age in descending order.
Query:
SELECT * FROM Customer ORDER BY Age DESC;
Tips to Master SELECT
Goal Technique
The SELECT TOP clause is useful on large tables with thousands of records. Returning a
large number of records can impact performance.
Note: Not all database systems support the SELECT TOP clause. MySQL supports
the LIMIT clause to select a limited number of records, while Oracle uses FETCH
FIRST n ROWS ONLY and ROWNUM.
Syntax:
SELECT column1, column2, ... TOP count
FROM table_name
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]];
Here,
column1, column2 = names of columns
count = number of records to be fetched
WHERE conditions: Optional. Filters the data based on conditions.
ORDER BY expression: Optional. Sorts the result set in ascending
or descending order.
NOT IN
By using the NOT keyword in front of the IN operator, you return all records that are
NOT any of the values in the list.
Example
Return all customers that are NOT from 'Germany', 'France', or 'UK':
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
NOT IN (SELECT)
The result in the example above returned 74 records, that means that there are 17
customers that haven't placed any orders.
Let us check if that is correct, by using the NOT IN operator.
Example
Return all customers that have NOT placed any orders in the Orders table:
SELECT * FROM Customers
WHERE CustomerID NOT IN (SELECT CustomerID FROM Orders);
As long as your data contains only the date portion, your queries will work as expected.
However, if a time portion is involved, it gets more complicated.
SQL Server comes with the following data types for storing a date or a date/time value in
the database:
Note: The date types are chosen for a column when you create a new table in your
database!
COMMIT;
SQL Clauses
SQL | WHERE Clause
Whether you're retrieving data, updating records, or deleting entries
from a database, the WHERE clause plays an important role in defining
which rows will be affected by the query. Without it, SQL queries would
return all rows in a table, making it difficult to target specific data.
The SQL WHERE clause is used to specify a condition while fetching or
modifying data in a database. It filters the rows that are affected by
the SELECT, UPDATE, DELETE, or INSERT operations. The condition can
range from simple comparisons to complex expressions, enabling precise
targeting of the data.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name
operator value;
Parameter Explanation:
1. column1,column2: fields in the table
2. table_name: name of table
3. column_name: name of field used for filtering the data
4. operator: operation to be considered for filtering
5. value: exact value or pattern to get related data in the result
Example 1: Where Clause with Logical Operators
To fetch records of Employee with age equal to 24.
Query:
SELECT * FROM Emp1 WHERE Age=24;
Query:
SELECT EmpID, Name, Country FROM Emp1 WHERE Age > 21;
= Equal to
BETWEE
In an inclusive Range
N
In the HAVING clause it will check In the WHERE condition it will check or
the condition in group of a row. execute at each row individual.
HAVING clause can only be used The WHERE Clause cannot be used with
with aggregate function. aggregate function like Having
Having Where
SQL ORDER BY
The ORDER BY clause in SQL is a powerful feature used to sort query
results in either ascending or descending order based on one or more
columns.
The ORDER BY statement in SQL is used to sort the fetched data in
either ascending or descending according to one or more columns. It is
very useful to present data in a structured manner.
SQL ORDER BY default mode is sorting data into ascending order. To sort
data in descending order use the DESC keyword with ORDER BY clause.
Syntax:
The syntax to use ORDER BY clause in SQL is:
SELECT * FROM table_name ORDER BY column_name ASC | DESC
Key Terms:
table_name: name of the table.
column_name: name of the column according to which the data is
needed to be arranged.
ASC: to sort the data in ascending order.
DESC: to sort the data in descending order.
Example 1 : Sort According To a Single Column using ORDER
BY Clause
SELECT * FROM students ORDER BY ROLL_NO DESC;
Example 2 : Sort According To Multiple Columns using
ORDER BY Clause
SELECT * FROM students ORDER BY age DESC , name ASC;
Note: ASC is the default value for the ORDER BY clause. So, if we don't
specify anything after the column name in the ORDER BY clause, the
output will be sorted in ascending order by default.
Sorting By Column Number (instead of name)
An integer that identifies the number of the column in the SelectItems in
the underlying query of the SELECT statement. Column number must be
greater than 0 and not greater than the number of columns in the result
table.
The rule checks for ORDER BY clauses that reference select list columns using the
column number instead of the column name. Further, changing the order of
columns in the SELECT list has no impact on the ORDER BY when the columns are
referred to by names instead of numbers.
Syntax:
The Syntax to use ORDER BY Clause with Column Number
ORDER BY Column_Number asc/desc
Query:
CREATE TABLE studentinfo
( Roll_no INT,
NAME VARCHAR(25),
Address VARCHAR(20),
CONTACTNO BIGINT NOT NULL,
Age INT );
SQL | GROUP BY
The SQL GROUP BY clause is a powerful tool used to organize data into groups
based on shared values in one or more columns. It's most often used with
aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform summary
operations on each group helping us extract meaningful insights from large
datasets.
The GROUP BY statement in SQL is used to arrange identical data into groups
based on specified columns. If a particular column has the same values in multiple
rows, the GROUP BY clause will group these rows together. It’s commonly used
with aggregate functions to calculate totals or averages per group. Key Points
About GROUP BY:
GROUP BY clause is used with the SELECT statement.
In the query, the GROUP BY clause is placed after the WHERE clause.
In the query, the GROUP BY clause is placed before the ORDER BY clause if
used.
In the query, the GROUP BY clause is placed before the Having clause.
Place condition in the having clause.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
GROUP BY column1, column2
Key Terms
1. function_name: Name of the function used for example, SUM() , AVG().
2. table_name: Name of the table.
3. condition: Condition used.
Example 1 : Group By Single Column
SELECT name, SUM(sal) FROM emp
GROUP BY name;
Example 2 : Group By Multiple Columns
Group by multiple columns is say, for example, GROUP BY column1, column2.
This means placing all the rows with the same values of columns column
1 and column 2 in one group. This SQL query groups student records by
both SUBJECT and YEAR and then counts the number of records (i.e.,
students) in each of those groups.
Query:
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
HAVING Clause in GROUP BY Clause
We know that the WHERE clause is used to place conditions on columns but what if
we want to place conditions on groups? This is where the HAVING clause comes
into use. We can use the HAVING clause to place conditions to decide which group
will be part of the final result set. Also, we can not use aggregate functions like
SUM(), COUNT(), etc. with the WHERE clause. So we have to use the HAVING
clause if we want to use any of these functions in the conditions.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
Key Terms
function_name: Name of the function used for example, SUM() , AVG().
table_name: Name of the table.
condition: Condition used.
Example:
SELECT NAME, SUM(sal) FROM Emp
GROUP BY name
HAVING SUM(sal)>50000;
SQL LIMIT Clause
The LIMIT clause in SQL is used to control the number of rows returned in
a query result.
What is the SQL LIMIT Clause?
The SQL LIMIT clause is used to control maximum number of
records returned by a query. It is commonly used for limiting query
results when only a subset of the data is required, such as
for pagination, filtering top values, or analyzing a smaller portion of a
large table. This can be particularly useful for tasks like:
Paginating results (e.g., showing 10 results per page)
Retrieving top records (e.g., the top 5 highest-rated products)
Sampling data (e.g., getting a random sample of rows for
analysis)
Syntax:
SQL OR Operator
The OR Operator in SQL displays the records where any one condition is
true, i.e. either condition1 or condition2 is True.
Syntax:
The syntax to use the OR operator in SQL is:
SELECT * FROM table_name WHERE condition1 OR condition2 OR...
conditionN;
table_name: name of the table
condition1,2,..N: first condition, second condition, and so on
SELECT * FROM Student
WHERE NAME = 'Ram' OR NAME = 'SUJIT';
Combining AND and OR Operators in SQL
SELECT * FROM table_name
WHERE condition1 AND (condition2 OR condition3);
SQL LIKE Operator
The SQL LIKE operator is used for performing pattern-based searches in a
database. It is used in combination with the WHERE clause to filter
records based on specified patterns, making it essential for any database-
driven application that requires flexible search functionality.
SQL LIKE operator is used with the WHERE clause to search for a
specified pattern in a column. LIKE operator finds and returns the rows that
fit in the given pattern.
LIKE operator is case-insensitive by default in most database systems.
This means that if you search for "apple" using the LIKE operator, it will
return results that include "Apple", "APPLE", "aPpLe", and so on.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE pattern;
column_name: The column to be searched.
pattern: The pattern to search for, which can include wildcard
characters.
For making the LIKE operator case-sensitive, you can use the "BINARY"
keyword in MySQL or the "COLLATE" keyword in other database
systems.
For example:
SELECT * FROM products WHERE name LIKE BINARY 'apple%'
Wildcard Characters with the SQL LIKE Operator
Wildcards are used with the LIKE operator to search for specific patterns
in strings. Wildcard characters substitute one or more characters in the
string. There are four wildcard characters in SQL:
1. % (Percent): Represents zero or more characters.
2. _ (Underscore): Represents a single character.
3. [] (Square Brackets): Represents any single character within
brackets.
4. - (Hyphen): Specify a range of characters inside brackets.
Examples of Wildcards
The below table shows some examples on how wild card can be written and
what do they mean:
Pattern Meaning
'a%t' Match strings that contain the start with 'a' and end with 't'.
'%wow Match strings that contain the substring 'wow' in them at any
%' position.
Match strings that start with 'a and contain at least 2 more
'a_ _%'
characters.
5 Sales
1 Technical
Now, we will write a query to fetch details of all employees who are
managers. This can be done by using nested SELCT queries with the IN
operator.
Query:
SELECT * FROM employee
WHERE Ssn IN (SELECT Ssn FROM manager);
Here, we have selected the Ssn of all managers from the manager table
and then, we have passed the result of this query to the main query in the
IN operator, which will fetch the details of all employees who have same
Ssn as fetched from the nested query.
Key takeaways about the SQL IN operator:
The SQL IN operator allows you to specify multiple values in a
WHERE clause.
It checks if a specified value matches any value in a list.
It simplifies querying for records that match multiple criteria
without needing to use multiple OR conditions.
The syntax is straightforward: WHERE column_name IN (value1,
value2, ...).
It is commonly used with SELECT, INSERT, UPDATE, and DELETE
statements for filtering or updating data based on multiple values.
Using the IN operator can make SQL queries more concise and
readable.
SQL IS NULL
The IS NULL operator is used to check if a column contains a NULL value. If
a column value is NULL, the operator returns TRUE; otherwise, it returns
FALSE. It's commonly used in WHERE clauses to filter rows that
contain NULL values in specific columns.
Syntax:
SQL IS NULL syntax is:
SELECT * FROM table_name
WHERE column_name IS NULL;
Note: A NULL value is different from a Zero Value and Blank Spaces. A
field that has NULL value means the field was left blank.
Example 1: IS NULL with WHERE clause
Query:
SELECT *
FROM students
WHERE email IS NULL;
Example 2: IS NULL Operator on Multiple Columns
Query:
SELECT *
FROM students
WHERE email IS NULL OR coding_score IS NULL;
Example 3: IS NULL with COUNT() Function
SELECT COUNT(*) AS count_empty_coding_score
FROM students
WHERE coding_score IS NULL;
Example 4: IS NULL with UPDATE Statement
Query:
UPDATE students
SET email = '[email protected]'
WHERE email IS NULL;
Example 5: IS NULL with DELETE Statement
Query:
DELETE FROM students
WHERE coding_score IS NULL;
Important Points About SQL IS NULL
SQl IS NULL is used to detect any rows that contain a NULL value in
its column.
IS NULL operator is mostly used with WHERE clause in SQL.
We can use IS NULL operator on multiple columns using OR
operator.
Using COUNT function we can count total number of NULL values in
SQL.
We can UPDATE or DELETE the NULL values, after filtering them
with IS NULL operator.
Duplicate
Includes all duplicates Removes duplicate records
Records
-- Valid insert
INSERT INTO Customers (CustomerID, Name, Age)
VALUES (1, 'John Doe', 25);
-- Invalid insert
INSERT INTO Customers (CustomerID, Name, Age)
VALUES (2, 'Jane Smith', 15); -- This will fail due to the CHECK
constraint
Example 2: CHECK Constraint with Multiple Columns
Query:
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Salary DECIMAL(10, 2),
CHECK (Age >= 18 AND Salary > 0)
);
-- Valid insert
INSERT INTO Employee (EmployeeID, Name, Age, Salary)
VALUES (1, 'Alice Johnson', 30, 50000);
-- Explicit value
INSERT INTO Geeks (ID, Name, Age, Location) VALUES (4, 'Mira', 23,
'Delhi');
SQL Joins
An SQL JOIN clause is used to query and access data from multiple tables
by establishing logical relationships between them. It can access data
from multiple tables simultaneously using common key values shared
across different tables.
1. SQL INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as
the condition is satisfied. This keyword will create the result-set by
combining all rows from both the tables where the condition satisfies i.e
value of the common field will be the same.
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER
JOIN.
Query:
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;