0% found this document useful (0 votes)
3 views

sql

A database is a collection of inter-related data used for efficient data retrieval, insertion, and deletion, while a Database Management System (DBMS) is software that manages databases, providing functionalities like data definition, retrieval, and user administration. SQL (Structured Query Language) is the standard language for managing relational databases, allowing users to perform operations like creating, reading, updating, and deleting data. The document also discusses various SQL commands, their types, advantages, and constraints applied to ensure data integrity.

Uploaded by

absr.3112005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

sql

A database is a collection of inter-related data used for efficient data retrieval, insertion, and deletion, while a Database Management System (DBMS) is software that manages databases, providing functionalities like data definition, retrieval, and user administration. SQL (Structured Query Language) is the standard language for managing relational databases, allowing users to perform operations like creating, reading, updating, and deleting data. The document also discusses various SQL commands, their types, advantages, and constraints applied to ensure data integrity.

Uploaded by

absr.3112005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 325

DBMS

What is Database

► The database is a collection of inter-related data which is used to retrieve,


insert and delete the data efficiently. It is also used to organize the data in
the form of a table, schema, views, and reports, etc.

► For example: The college Database organizes the data about the admin,
staff, students and faculty etc.
► Using the database, you can easily retrieve, insert, and delete the
information.
Database Management System

► Database management system is a software which is used to manage the


database. For example: MySQL, Oracle, etc are a very popular commercial
database which is used in different applications.
► DBMS provides an interface to perform various operations like database
creation, storing data in it, updating data, creating a table in the database
and a lot more.
► It provides protection and security to the database. In the case of multiple
users, it also maintains data consistency.
Database Management System

► DBMS allows users the following tasks:


► Data Definition: It is used for creation, modification, and removal of
definition that defines the organization of data in the database.
► Data Updation: It is used for the insertion, modification, and deletion of the
actual data in the database.
► Data Retrieval: It is used to retrieve the data from the database which can be
used by applications for various purposes.
► User Administration: It is used for registering and monitoring users, maintain
data integrity, enforcing data security, dealing with concurrency control,
monitoring performance and recovering information corrupted by unexpected
failure.
Characteristics of DBMS

► It uses a digital repository established on a server to store and manage the


information.
► It can provide a clear and logical view of the process that manipulates data.
► DBMS contains automatic backup and recovery procedures.
► It contains ACID properties which maintain data in a healthy state in case of
failure.
► It can reduce the complex relationship between data.
► It is used to support manipulation and processing of data.
► It is used to provide security of data.
► It can view the database from different viewpoints according to the
requirements of the user.
Advantages of DBMS

► Controls database redundancy: It can control data redundancy because it stores all the
data in one single database file and that recorded data is placed in the database.
► Data sharing: In DBMS, the authorized users of an organization can share the data among
multiple users.
► Easily Maintenance: It can be easily maintainable due to the centralized nature of the
database system.
► Reduce time: It reduces development time and maintenance need.
► Backup: It provides backup and recovery subsystems which create automatic backup of
data from hardware and software failures and restores the data if required.
► multiple user interface: It provides different types of user interfaces like graphical user
interfaces, application program interfaces

Disadvantages of DBMS

► Cost of Hardware and Software: It requires a high speed of data processor


and large memory size to run DBMS software.
► Size: It occupies a large space of disks and large memory to run them
efficiently.
► Complexity: Database system creates additional complexity and
requirements.
► Higher impact of failure: Failure is highly impacted the database because in
most of the organization, all the data stored in a single database and if the
database is damaged due to electric failure or database corruption then the
data may be lost forever.

SQL

► SQL stands for Structured Query Language. It is used for storing and managing
data in relational database management system (RDMS).
► It is a standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables.
► All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL
as their standard database language.
► SQL allows users to query the database in a number of ways, using English-like
statements.

Rules:

► SQL follows the following rules:


► Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase.
► Statements of SQL are dependent on text lines. We can use a single SQL
statement on one or multiple text line.
► Using the SQL statements, you can perform most of the actions in a database.
► SQL depends on tuple relational calculus and relational algebra.
Characteristics of SQL

► SQL is easy to learn.


► SQL is used to access data from relational database management systems.
► SQL can execute queries against the database.
► SQL is used to describe the data.
► SQL is used to define the data in the database and manipulate it when
needed.
► SQL is used to create and drop the database and table.
► SQL is used to create a view, stored procedure, function in a database.
► SQL allows users to set permissions on tables, procedures, and views.
Advantages of SQL
► There are the following advantages of SQL:
► High speed
► Using the SQL queries, the user can quickly and efficiently retrieve a large amount of
records from a database.
► No coding needed
► In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.
► Well defined standards
► Long established are used by the SQL databases that are being used by ISO and ANSI.
► Portability
► SQL can be used in laptop, PCs, server and even some mobile phones.
► Interactive language
► SQL is a domain language used to communicate with the database. It is also used to
receive answers to the complex questions in seconds.
► Multiple data view
► Using the SQL language, the users can make different views of the database structure.
SQL Datatype
► SQL Datatype is used to define the values that a column can contain.
► Every column is required to have a name and data type in the database table.
1. Binary Datatypes
► There are Three types of binary Datatypes which are given below:
2. Approximate Numeric Datatype :
► The subtypes are given below:
3. Exact Numeric Datatype
► The subtypes are given below:
4. Character String Datatype
► The subtypes are given below:
5. Date and time Datatypes
► The subtypes are given below:
SQL Commands
► SQL commands are instructions. It is used to communicate with the database.
It is also used to perform specific tasks, functions, and queries of data.
► SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, set permission for users.
Types of SQL Commands
► There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)
► DDL changes the structure of the table like creating a table, deleting a table,
altering a table, etc.
► All the command of DDL are auto-committed that means it permanently save
all the changes in the database.
► Here are some commands that come under DDL:
► CREATE
► ALTER
► DROP
► TRUNCATE
1. Data Definition Language (DDL)
► a. CREATE It is used to create a new table in the database.
1. Data Definition Language (DDL)
► a. CREATE It is used to create a new table in the database.
1. Data Definition Language (DDL)
► If you create the table successfully, you can verify the table by looking at the
message by the SQL server. Else you can use DESC command as follows:
► SQL> DESC EMPLOYEE;
1. Data Definition Language (DDL)
► b. DROP: It is used to delete both the structure and record stored in the
table.
1. Data Definition Language (DDL)
► c. ALTER: It is used to alter the structure of the database. This change could
be either to modify the characteristics of an existing attribute or probably to
add a new attribute.
1. Data Definition Language (DDL)
► d. TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.
2. Data Manipulation Language
► DML commands are used to modify the database. It is responsible for all form
of changes in the database.
► The command of DML is not auto-committed that means it can't permanently
save all the changes in the database. They can be rollback.
► Here are some commands that come under DML:
► INSERT
► UPDATE
► DELETE
2. Data Manipulation Language
► a. INSERT: The INSERT statement is a SQL query. It is used to insert data into
the row of a table.
2. Data Manipulation Language
► a. INSERT: The INSERT statement is a SQL query. It is used to insert data into
the row of a table.
2. Data Manipulation Language
► The SQL INSERT statement is used to insert a single or multiple data in a
table. In SQL, You can insert the data in two ways:
► Without specifying column name
► By specifying column name
2. Data Manipulation Language
► 1. Without specifying column name
► If you want to specify all column values, you can specify or ignore the column
values.
2. Data Manipulation Language
► 1. Without specifying column name
► If you want to specify all column values, you can specify or ignore the column
values.
2. Data Manipulation Language
► 2. By specifying column name
► To insert partial column values, you must have to specify the column names.
2. Data Manipulation Language
► Output: After executing this query, the table will look like:
2. Data Manipulation Language
► b. UPDATE: This command is used to update or modify the value of a column
in the table.
2. Data Manipulation Language
► b. UPDATE: This command is used to update or modify the value of a column
in the table.
2. Data Manipulation Language
► b. UPDATE: This command is used to update or modify the value of a column
in the table.
2. Data Manipulation Language
► Updating single record
► Update the column EMP_NAME and set the value to 'Emma' in the row where
SALARY is 500000.
2. Data Manipulation Language
► Update the column EMP_NAME and set the value to 'Emma' in the row where
SALARY is 500000.
2. Data Manipulation Language
► Updating multiple records
► If you want to update multiple columns, you should separate each field
assigned with a comma. In the EMPLOYEE table, update the column
EMP_NAME to 'Kevin' and CITY to 'Boston' where EMP_ID is 5.
2. Data Manipulation Language
► Updating multiple records
2. Data Manipulation Language
► Without use of WHERE clause
► If you want to update all row from a table, then you don't need to use the
WHERE clause. In the EMPLOYEE table, update the column EMP_NAME as
'Harry'.
2. Data Manipulation Language
► Without use of WHERE clause
► If you want to update all row from a table, then you don't need to use the
WHERE clause. In the EMPLOYEE table, update the column EMP_NAME as
'Harry'.
2. Data Manipulation Language
► Without use of WHERE clause
► If you want to update all row from a table, then you don't need to use the
WHERE clause. In the EMPLOYEE table, update the column EMP_NAME as
'Harry'.
2. Data Manipulation Language
► c. DELETE: It is used to remove one or more row from a table.
2. Data Manipulation Language
► c. DELETE: It is used to remove one or more row from a table.
2. Data Manipulation Language
► The following query will DELETE an employee whose ID is 3.
2. Data Manipulation Language
► Now, the EMPLOYEE table would have the following records.
2. Data Manipulation Language
► If you don't specify the WHERE condition, it will remove all the rows from the
table.
2. Data Manipulation Language
► The SQL DELETE statement is used to delete rows from a table. Generally,
DELETE statement removes one or more records form a table.
2. Data Manipulation Language
► Deleting Single Record
► Delete the row from the table EMPLOYEE where EMP_NAME = 'Kristen'. This
will delete only the fourth row.
2. Data Manipulation Language
► Deleting Multiple Record
► Delete the row from the EMPLOYEE table where AGE is 30. This will delete
two rows(first and third row).
2. Data Manipulation Language
► Delete all of the records
► Delete all the row from the EMPLOYEE table. After this, no records left to
display. The EMPLOYEE table will become empty.
3. Data Control Language
► DCL commands are used to grant and take back authority from any database
user.

► Here are some commands that come under DCL:


► Grant
► Revoke
3. Data Control Language
► a. Grant: It is used to give user access privileges to a database.
4. Transaction Control Language
► TCL commands can only use with DML commands like INSERT, DELETE and
UPDATE only.
► These operations are automatically committed in the database that's why
they cannot be used while creating tables or dropping them.
► Here are some commands that come under TCL:
► COMMIT
► ROLLBACK
► SAVEPOINT
4. Transaction Control Language
► a. Commit: Commit command is used to save all the transactions to the
database.
4. Transaction Control Language
► b. Rollback: Rollback command is used to undo transactions that have not
already been saved to the database.
4. Transaction Control Language
► c. SAVEPOINT: It is used to roll the transaction back to a certain point
without rolling back the entire transaction.
5. Data Query Language
► DQL is used to fetch the data from the database.
► It uses only one command:
► SELECT
► a. SELECT: This is the same as the projection operation of relational algebra.
It is used to select the attribute based on the condition described by WHERE
clause.
5. Data Query Language
► DQL is used to fetch the data from the database.
► It uses only one command:
► SELECT
► a. SELECT: This is the same as the projection operation of relational algebra.
It is used to select the attribute based on the condition described by WHERE
clause.
5. Data Query Language
► In SQL, the SELECT statement is used to query or retrieve data from a table in
the database. The returns data is stored in a table, and the result table is
known as result-set.
► Here, the expression is the field name of the table that you want to select
data from.
5. Data Query Language
► Use the following syntax to select all the fields available in the table:
5. Data Query Language
► To fetch the EMP_ID of all the employees, use the following query:
5. Data Query Language
► To fetch the EMP_NAME and SALARY, use the following query:
5. Data Query Language
► To fetch all the fields from the EMPLOYEE table, use the following query:
Constraints in SQL
► Constraints in SQL means we are applying certain conditions or restrictions on the

database.

► This means that before inserting data into the database, we are checking for some

conditions.

► If the condition we have applied to the database holds true for the data which is to

be inserted, then only the data will be inserted into the database tables.
Constraints in SQL
► Constraints in SQL can be categorized into two types:

► Column Level Constraint:

Column Level Constraint is used to apply a constraint on a single column.

► Table Level Constraint:

Table Level Constraint is used to apply a constraint on multiple columns.


Some of the real-life examples of constraints
are as follows:
► Every person has a unique email id.

► This is because while creating an email account for any user, the email providing services such as Gmail,

Yahoo or any other email providing service will always check for the availability of the email id that the

user wants for himself.

► If some other user already takes the email id that the user wants, then that id cannot be assigned to

another user.

► This simply means that no two users can have the same email ids on the same email providing service.

► So, here the email id is the constraint on the database of email providing services.
Some of the real-life examples of constraints
are as follows:
► Whenever we set a password for any system, there are certain constraints that are to be followed.

► These constraints may include the following:

► There must be one uppercase character in the password.

► Password must be of at least eight characters in length.

► Password must contain at least one special symbol.


Constraints available in SQL are:

► NOT NULL

► UNIQUE

► PRIMARY KEY

► FOREIGN KEY

► CHECK
1. NOT NULL

► NULL means empty, i.e., the value is not available.

► Whenever a table's column is declared as NOT NULL, then the value for that column cannot be

empty for any of the table's records.

► There must exist a value in the column to which the NOT NULL constraint is applied.

► CREATE TABLE TableName (ColumnName1 datatype NOT NULL, ColumnName2 datatype,….,

ColumnNameN datatype);
1. NOT NULL

► Example:

► Create a student table and apply a NOT NULL constraint on one of the table's column
while creating a table.

► CREATE TABLE student(StudentID INT NOT NULL, Student_FirstName VARCHAR(20),


Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20),
Student_Email_ID VARCHAR(40));

► To verify that the not null constraint is applied to the table's column and the student
table is created successfully, we will execute the following query:
1. NOT NULL
1. NOT NULL
1. NOT NULL

To verify that the not null constraint is applied to the student table's column, we will execute the
following query:
2. UNIQUE

► Duplicate values are not allowed in the columns to which the UNIQUE constraint is

applied.

► The column with the unique constraint will always contain a unique value.

► This constraint can be applied to one or more than one column of a table, which

means more than one unique constraint can exist on a single table.

► Using the UNIQUE constraint, you can also modify the already created tables.
2. UNIQUE
► Syntax to apply the UNIQUE constraint on a single column:

► CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2 datatype,….,


ColumnNameN datatype);

► Example:

► Create a student table and apply a UNIQUE constraint on one of the table's column while
creating a table.

► mysql> CREATE TABLE student(StudentID INT UNIQUE, Student_FirstName VARCHAR(20),


Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_I
D VARCHAR(40));
2. UNIQUE

► To verify that the unique constraint is applied to the table's column and the
student table is created successfully, we will execute the following query:
2. UNIQUE

► Syntax to apply the UNIQUE constraint on more than one column:

► CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype,….,


ColumnNameN datatype, UNIQUE (ColumnName1, ColumnName 2));
2. UNIQUE

► Example:

► Create a student table and apply a UNIQUE constraint on more than one table's column
while creating a table.

► mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20),


Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20),
Student_Email_ID VARCHAR(40), UNIQUE(StudentID, Student_PhoneNumber));
2. UNIQUE

► Syntax to apply the UNIQUE constraint on an existing table's column:


2. UNIQUE
► Consider we have an existing table student, without any constraints applied to it. Later,
we decided to apply a UNIQUE constraint to one of the table's column. Then we will
execute the following query:
2. UNIQUE

► To verify that the unique constraint is applied to the table's column and the
student table is created successfully, we will execute the following query:
3. PRIMARY KEY
► PRIMARY KEY Constraint is a combination of NOT NULL and Unique constraints.

► NOT NULL constraint and a UNIQUE constraint together forms a PRIMARY constraint.

► The column to which we have applied the primary constraint will always contain a unique value
and will not allow null values.

► A column or columns is called primary key (PK) that uniquely identifies each row in the table.

► If you want to create a primary key, you should define a PRIMARY KEY constraint when you create
or modify a table.

► When multiple columns are used as a primary key, it is known as composite primary key.
3. PRIMARY KEY
► Points to remember for primary key:
► Primary key enforces the entity integrity of the table.
► Primary key always has unique data.
► A primary key length cannot be exceeded than 900 bytes.
► A primary key cannot have null value.
► There can be no duplicate value for a primary key.
► A table can contain only one primary key constraint.
3. PRIMARY KEY
► Main advantage of primary key:

► The main advantage of this uniqueness is that we get fast access.


3. PRIMARY KEY

► SQL primary key for one column:

► Syntax of primary key constraint during table creation:

► CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, ColumnName2 datatype,….,


ColumnNameN datatype);
3. PRIMARY KEY

► Example:

► Create a student table and apply the PRIMARY KEY constraint while creating a table.

mysql> CREATE TABLE student(StudentID INT PRIMARY KEY, Student_FirstName VARCHAR(20),


Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40))
;
3. PRIMARY KEY
► To verify that the primary key constraint is applied to the table's column and the student table is
created successfully, we will execute the following query:
3. PRIMARY KEY
► SQL primary key on ALTER TABLE

► When table is already created and you want to create a PRIMARY KEY constraint on the "S_Id"
column you should use the following SQL:

► Syntax to apply the primary key constraint on an existing table's column:


3. PRIMARY KEY
► Syntax to apply the primary key constraint on an existing table's column:
3. PRIMARY KEY
3. PRIMARY KEY
► How to DROP a PRIMARY KEY constraint?
► If you want to DROP (remove) a primary key constraint, you should use
following syntax:

SQL Server / Oracle / MS Access:


4. FOREIGN KEY

► A foreign key is used for referential integrity.

► When we have two tables, and one table takes reference from another table, i.e.,
the same column is present in both the tables and that column acts as a primary key
in one table. That particular column will act as a foreign key in another table.
4. FOREIGN KEY
► Syntax to apply a foreign key constraint during table creation:

► CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY,


ColumnNameN Datatype(SIZE), FOREIGN KEY( ColumnName ) REFERENCES
PARENT_TABLE_NAME(Primary_Key_ColumnName));
4. FOREIGN KEY

► Example:

► Create an employee table and apply the FOREIGN KEY constraint while creating a
table.

► To create a foreign key on any table, first, we need to create a primary key on a
table.

► mysql> CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY,
Emp_Name VARCHAR (40), Emp_Salary VARCHAR (40));
4. FOREIGN KEY
► To verify that the primary key constraint is applied to the employee table's column,
we will execute the following query:
4. FOREIGN KEY

► Now, we will write a query to apply a foreign key on the department table referring
to the primary key of the employee table, i.e., Emp_ID.

► mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY,


Dept_Name VARCHAR(40), Emp_ID INT NOT NULL, FOREIGN KEY(Emp_ID)
REFERENCES employee(Emp_ID));
4. FOREIGN KEY

► Syntax to apply the foreign key constraint on an existing table's column:

► ALTER TABLE Parent_TableName ADD FOREIGN KEY (ColumnName) REFERENCES


Child_TableName (ColumnName);
4. FOREIGN KEY

► Example:

► Consider we have an existing table employee and department. Later, we decided


to apply a FOREIGN KEY constraint to the department table's column.
4. FOREIGN KEY
5. CHECK

► Whenever a check constraint is applied to the table's column, and the user wants to
insert the value in it, then the value will first be checked for certain conditions before
inserting the value into that column.
► For example: if we have an age column in a table, then the user will insert any value
of his choice. The user will also enter even a negative value or any other invalid
value.
► But, if the user has applied check constraint on the age column with the condition age
greater than 18. Then in such cases, even if a user tries to insert an invalid value such
as zero or any other value less than 18, then the age column will not accept that
value and will not allow the user to insert it due to the application of check constraint
on the age column.
5. CHECK

► Syntax to apply check constraint on a single column:

► CREATE TABLE TableName (ColumnName1 datatype CHECK (ColumnName1 Condition)


, ColumnName2 datatype,…., ColumnNameN datatype);
5. CHECK

► Example:

► Create a student table and apply CHECK constraint to check for the age less than or
equal to 15 while creating a table.

► mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20),


Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20),
Student_Email_ID VARCHAR(40), Age INT CHECK( Age <= 15));
5. CHECK

► Syntax to apply check constraint on multiple columns:

► CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype CHECK


(ColumnName1 Condition AND ColumnName2 Condition),…., ColumnNameN datatype);
5. CHECK

► Example:

► Create a student table and apply CHECK constraint to check for the age less than or
equal to 15 and a percentage greater than 85 while creating a table.

► mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20),


Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20),
Student_Email_ID VARCHAR(40), Age INT, Percentage INT,
CHECK( Age <= 15 AND Percentage > 85));
5. CHECK
► Syntax to apply check constraint on an existing table's column:
5. CHECK
► Syntax to apply check constraint on an existing table's column:
SQL JOIN
► JOIN means to combine something.
► JOIN means "to combine two or more tables".
► The SQL JOIN clause takes records from two or more tables in a database and combines it together.

► ANSI standard SQL defines five types of JOIN :


► inner join,
► left outer join,
► right outer join,
► full outer join, and
► cross join.

► In the process of joining, rows of both tables are combined in a single table.
Why SQL JOIN is used?

► If you want to access more than one table through a select statement.

► If you want to combine two or more table then SQL JOIN statement is used.

► It combines rows of that tables in one table and one can retrieve the information by a SELECT
statement.

► The joining of two or more tables is based on common field between them.

► SQL INNER JOIN also known as simple join is the most common type of join.
Why SQL JOIN is used?

► 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.

► We can use SQL JOIN with multiple tables. It can also be paired with other clauses, the most popular
use will be using JOIN with WHERE clause to filter data retrieval.
How to use SQL join or SQL Inner Join?
► Let an example to deploy SQL JOIN process:
How to use SQL join or SQL Inner Join?
► Let an example to deploy SQL JOIN process:
How to use SQL join or SQL Inner Join?
► So if you follow this JOIN statement to join these two tables ?
How to use SQL join or SQL Inner Join?
► This will produce the following output:
How to use SQL join or SQL Inner Join?
► SQL JOIN Example
► Consider the two tables below as follows:
How to use SQL join or SQL Inner Join?
► SQL JOIN Example
► Consider the two tables below as follows:
How to use SQL join or SQL Inner Join?
► Both these tables are connected by one common key (column) i.e ROLL_NO.
► We can perform a JOIN operation using the given SQL query:
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.
SQL INNER JOIN
► Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.
SQL INNER JOIN
► INNER JOIN Example
► Let’s look at the example of INNER JOIN clause, and understand it’s working.
► This query will show the names and age of students enrolled in different courses.
SQL OUTER JOIN
► In the outer JOIN, all the content from both the tables is integrated together.

► Even though the records from both the tables are matched or not, the matching and
non-matching records from both the tables will be considered an output of the outer
join in SQL.

► There are three different types of outer join in SQL:


► Left Outer Join
► Right Outer Join
► Full Outer Join
SQL OUTER JOIN
► Consider we have the following tables with the given data:
SQL OUTER JOIN
► Table 2: department
SQL OUTER JOIN
SQL OUTER JOIN
1. Left Outer Join:

► LEFT JOIN returns all the rows of the table on the left side of the join and matches
rows for the table on the right side of the join. For the rows for which there is no
matching row on the right side, the result-set will contain null. LEFT JOIN is also
known as LEFT OUTER JOIN.

► Syntax of writing a query to perform left outer join:

► SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1


LEFT OUTER JOIN TableName2 ON TableName1.ColumnName =
TableName2.ColumnName;

► Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.
1. Left Outer Join:
1. Left Outer Join:
► Example 1:

► Write a query to perform left outer join considering employee table as the left table and
department table as the right table.

► Query:

► mysql> SELECT e.EmployeeID, e.Employee_Name, e.Employee_Salary, d.DepartmentID,


d.Department_Name FROM employee e LEFT OUTER JOIN department d ON
e.EmployeeID = d.Employee_ID;

► We have used the SELECT command to retrieve EmployeeID, Employee_Name, Employee_Salary,


DepartmentID, Department_Name present in the employee and department table. Then we have
used the LEFT OUTER JOIN keyword to perform the left outer join operation on the employee and
department table where 'e' and 'd' are aliases. These two tables are joined on the column
EmployeeID which is present in both the tables.
1. Left Outer Join:
► You will get the following output:

1. Left Outer Join:
► You will get the following output:

► EmployeeID, Employee_Name, Employee_Salary, Department_ID, Department_Name are


retrieved from employee and department tables.

► All the records from the employee table are retrieved.

► Only those records that have a corresponding EmployeeID in the employee table are
retrieved from the department table.

► Rest other records in the department table for which an employeeID doesn't match with
the employeeID of the employee table; then, it is displayed as NULL.
1. Left Outer Join:
► Example 2:
► Write a query to perform left outer join considering loan table as the left table and borrower table
as the right table.
► Query:
► mysql> SELECT l.LoanID, l.Branch, l.Amount, b.CustID, b.CustName FROM Loan l LEFT OUTER JOIN
Borrower b ON l.LoanID = b.LoanID;
► We have used the SELECT command to retrieve LoanID, Branch, Amount, CustID, CustName present
in the loan and borrower table. Then we have used the LEFT OUTER JOIN keyword to perform the
left outer join operation on the loan and borrower table where 'l' and 'b' are aliases. These two
tables are joined on the column LoanID which is present in both the tables.
1. Left Outer Join:
1. Left Outer Join:
► LoanID, Branch, Amount, CustID, CustName are retrieved from loan and borrower tables. All the
records from the loan table are retrieved. Only those records that have a corresponding LoanID in
the loan table are retrieved from the borrower table. Rest other records in the borrower table for
which a LoanID doesn't match with the LoanID of the loan table; are displayed as NULL.
1. Left Outer Join:
► Let’s look at the example of LEFT JOIN clause, and understand it’s working

► Student
► StudentCourse
1. Left Outer Join:
► Let’s look at the example of LEFT JOIN clause, and understand it’s working
2. Right Outer Join:
► Right outer join is the reverse of left outer join. If we use the right outer join to combine
two different tables, then we will get all the records from the right table. But we will get
only those records from the left table, which have the corresponding key in the right table.

► RIGHT JOIN returns all the rows of the table on the right side of the join and matching
rows for the table on the left side of the join.It is very similar to LEFT JOIN For the rows
for which there is no matching row on the left side, the result-set will contain null. RIGHT
JOIN is also known as RIGHT OUTER JOIN.

► Syntax of writing a query to perform right outer join:

► SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1 RIGHT


OUTER JOIN TableName2 ON TableName1.ColumnName = TableName2.ColumnName;
2. Right Outer Join:
► Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.
2. Right Outer Join:
► Example 1:
► Write a query to perform right outer join considering employee table as the left table
and department table as the right table.
► Query:
► mysql> SELECT e.EmployeeID, e.Employee_Name, e.Employee_Salary, d.DepartmentID,
d.Department_Name FROM employee e RIGHT OUTER JOIN department d ON
e.EmployeeID = d.Employee_ID;
2. Right Outer Join:
► We have used the SELECT command to retrieve EmployeeID, Employee_Name,
Employee_Salary, DepartmentID, Department_Name present in the employee and
department table. Then we have used the RIGHT OUTER JOIN keyword to perform the
right outer join operation on the employee and department table where 'e' and 'd' are
aliases. These two tables are joined on the column EmployeeID which is present in
both the tables.
2. Right Outer Join:
Example 1:
2. Right Outer Join:
► EmployeeID, Employee_Name, Employee_Salary, DepartmentID, Department_Name are
retrieved from employee and department tables. All the records from the department
table are retrieved. Only those records that have a corresponding EmployeeID in the
department table are retrieved from the employee table.
2. Right Outer Join:
► Example 2:
► Write a query to perform right outer join considering loan table as the left table and borrower table
as the right table.
► Query:
► mysql> SELECT l.LoanID, l.Branch, l.Amount, b.CustID, b.CustName FROM Loan l RIGHT OUTER JOIN
Borrower b ON l.LoanID = b.LoanID;
► We have used the SELECT command to retrieve LoanID, Branch, Amount, CustID, CustName present
in the loan and borrower table. Then we have used the RIGHT OUTER JOIN keyword to perform the
right outer join operation on the loan and borrower table where 'l' and 'b' are aliases. These two
tables are joined on the column LoanID which is present in both the tables.
2. Right Outer Join:
► You will get the following output:
2. Right Outer Join:
► You will get the following output:
► LoanID, Branch, Amount, CustID, CustName are retrieved from loan and borrower tables. All the
records from the borrower table are retrieved. Only those records that have a corresponding LoanID
in the borrower table are retrieved from the loan table. Rest other records in the loan table for
which a LoanID doesn't match with the LoanID of the borrower table; then, are displayed as NULL.
2. Right Outer Join:
► SQL RIGHT JOIN
► RIGHT JOIN returns all the rows of the table on the right side of the join and matching rows for the
table on the left side of the join. It is very similar to LEFT JOIN For the rows for which there is no
matching row on the left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER JOIN.
► Syntax:
► The syntax of RIGHT JOIN in SQL is:
2. Right Outer Join:
► RIGHT JOIN Example:
► Let’s look at the example of RIGHT JOIN clause, and understand it’s working

► Student
► StudentCourse
2. Right Outer Join:
► RIGHT JOIN Example:
► Let’s look at the example of RIGHT JOIN clause, and understand it’s working
3. Full Outer Join:
► If we use a full outer join to combine two different tables, then we will get all the records from
both the table,e., we will get all the records from the left table as well as the right table.
► MySQL doesn't support FULL OUTER JOIN directly. So to implement full outer join in MySQL, we
will execute two queries in a single query. The first query will be of LEFT OUTER JOIN, and the
second query will be of RIGHT OUTER JOIN. We will combine the first and second query with the
UNION operator to see the results of FULL OUTER JOIN.
► Syntax of writing a query to perform full outer join:
► SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1 LEFT OUTER JOI
N TableName2 ON TableName1.ColumnName = TableName2.ColumnName UNION SELECT TableNam
e1.columnName1, TableName2.columnName2 FROM TableName1 RIGHT OUTER JOIN TableName2 O
N TableName1.ColumnName = TableName2.ColumnName;
3. Full Outer Join:
► SQL FULL JOIN
► FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The
result-set will contain all the rows from both tables. For the rows for which there is no matching,
the result-set will contain NULL values.
3. Full Outer Join:
► Example 1:
► Write a query to perform full outer join considering the employee table as the left table and
department table as the right table.
► Query:
► mysql> SELECT e.EmployeeID, e.Employee_Name, e.Employee_Salary, d.DepartmentID, d.Department
_Name FROM department d LEFT OUTER JOIN employee e ON e.EmployeeID = d.Employee_ID UNION
SELECT e.EmployeeID, e.Employee_Name, e.Employee_Salary, d.DepartmentID, d.Department_Name
FROM department d RIGHT OUTER JOIN employee e ON e.EmployeeID = d.Employee_ID;
3. Full Outer Join:
► We have used the SELECT command to retrieve EmployeeID, Employee_Name,
Employee_Salary, DepartmentID, Department_Name present in the employee and
department table.

► Then we have used the LEFT OUTER JOIN keyword to perform the left outer join
operation on the employee and department table where 'e' and 'd' are aliases.

► Then we have written a SELECT query to perform right outer join operation on
employee and department table where 'e' and 'd' are aliases.

► These two tables are joined on the column EmployeeID which is present in both the
tables. Both the SELECT queries are combined using the UNION operator.
3. Full Outer Join:
3. Full Outer Join:
► EmployeeID, Employee_Name, Employee_Salary, Department_ID, Department_Name
are retrieved from employee and department tables.
► All the records from the employee table are retrieved as a result of the left outer
join.
► Only those records that have a corresponding EmployeeID in the employee table are
retrieved from the department table.
► Rest other records in the department table for which an employeeID doesn't match
with the employeeID of the employee table; then, are displayed as NULL.

► All the records from the department table are retrieved as a result of the right
outer join. Only those records that have a corresponding EmployeeID in the
department table are retrieved from the employee table.
3. Full Outer Join:
► Example 2:
► Write a query to perform full outer join considering loan table as the left table and borrower table
as the right table.
► Query:
► mysql> SELECT l.LoanID, l.Branch, l.Amount, b.CustID, b.CustName FROM Loan l LEFT OUTER JOIN
Borrower b ON l.LoanID = b.LoanID UNION SELECT l.LoanID, l.Branch, l.Amount, b.CustID,
b.CustName FROM Loan l RIGHT OUTER JOIN Borrower b ON l.LoanID = b.LoanID
► We have used the SELECT command to retrieve LoanID, Branch, Amount, CustID, CustName present
in the loan and borrower table. Then we have used the LEFT OUTER JOIN keyword to perform the
left outer join operation on the loan and borrower table where 'l' and 'b' are aliases. Then we have
written a SELECT query to perform the right outer join operation on the loan and borrower table
where 'l' and 'b' are aliases. These two tables are joined on the column LoanID which is present in
both the tables. Both the SELECT queries are combined using the UNION operator.
3. Full Outer Join:
3. Full Outer Join:
► LoanID, Branch, Amount, CustID, CustName are retrieved from loan and borrower tables.

► All the records from the loan table are retrieved as a result of the left outer join.

► Only those records that have a corresponding LoanID in the loan table are retrieved from the
borrower table.
► Rest other records in the borrower table for which a LoanID doesn't match with the LoanID of the
loan table; are displayed as NULL.

► All the records from the borrower table are retrieved as a result of the right outer join. Only those
records that have a corresponding LoanID in the borrower table are retrieved from the loan table.

► Rest other records in the loan table for which a LoanID doesn't match with the LoanID of the
borrower table, are displayed as NULL.
3. Full Outer Join:
► LoanID, Branch, Amount, CustID, CustName are retrieved from loan and borrower tables.

► All the records from the loan table are retrieved as a result of the left outer join.

► Only those records that have a corresponding LoanID in the loan table are retrieved from the
borrower table.
► Rest other records in the borrower table for which a LoanID doesn't match with the LoanID of the
loan table; are displayed as NULL.

► All the records from the borrower table are retrieved as a result of the right outer join. Only those
records that have a corresponding LoanID in the borrower table are retrieved from the loan table.

► Rest other records in the loan table for which a LoanID doesn't match with the LoanID of the
borrower table, are displayed as NULL.
3. Full Outer Join:
► Syntax
► The syntax of SQL FULL JOIN is:
3. Full Outer Join:
► Here,
► table1: First table.
► table2: Second table
► matching_column: Column common to both the tables.
► FULL JOIN Example
► Let’s look at the example of FULL JOIN clause, and understand it’s working
3. Full Outer Join:
SQL WHERE
► A WHERE clause in SQL is a data manipulation language statement.
► WHERE clauses are not mandatory clauses of SQL DML statements. But it can be used to limit the
number of rows affected by a SQL DML statement or returned by a query.
► Actually. it filters the records. It returns only those queries which fulfill the specific conditions.
► WHERE clause is used in SELECT, UPDATE, DELETE statement etc.
SQL WHERE
► WHERE clause uses some conditional selection
SQL WHERE
► SQL AND

► The SQL AND condition is used in SQL query to create two or more conditions to be met.
► It is used in SQL SELECT, INSERT, UPDATE and DELETE
► Let's see the syntax for SQL AND:
► SELECT columns FROM tables WHERE condition 1 AND condition 2;
► The SQL AND condition require that both conditions should be met.
► The SQL AND condition also can be used to join multiple tables in a SQL statement.
► To understand this concept practically, let us see some examples.
SQL WHERE
► Consider we have an employee table created into the database with the following data:
SQL "AND" example with "SELECT" statement
► This is how an SQL "AND" condition can be used in the SQL SELECT statement.
► Example 1:
► Write a query to get the records from emp tables in which department of the employee is IT and
location is Chennai.
SQL "AND" example with "SELECT" statement
► Write a query to get the records from emp tables in which department of the employee is IT and
location is Chennai.

► In the emp table, there are three employees whose department is IT. But we have specified the
AND condition according to which the employee's location should not be other than Chennai. So,
there are only two employees whose department is IT and Location is Chennai.
SQL "AND" example with "SELECT" statement
► Example 2:
► Write a query to get the records from emp tables in which department of the employee is IT and
location is Mumbai.

In the emp table, there are three employees whose department is IT. Among these three employees,
there is only one employee whose location is Mumbai. Due to the presence of the AND operator used
in the query, a record must satisfy both conditions.
SQL "AND" example with "UPDATE" statement
► This is how the "AND" condition can be used in the SQL UPDATE statement.
► Example 1:
► Write a query to update the records in emp tables in which department of the employee is
Marketing, and the first name is Suraj. For that particular employee, set the updated value of the
location as Delhi.
► Query:

1.mysql> UPDATE emp SET Location = "Delhi" WHERE Department = "Marketing" AND First_Name = "Suraj";
SQL "AND" example with "UPDATE" statement
► We will use the SELECT query to verify the updated record.
SQL "AND" example with "UPDATE" statement
► Example 2:
► Write a query to update the records in the emp table in which department of the employee is
Finance and ID is 7. For that particular employee, set the updated value of the department as HR.
► Query:

► We will use the SELECT query to verify the updated record.


SQL "AND" example with "UPDATE" statement
SQL "AND" example with "DELETE" statement
► This is how an SQL "AND" condition can be used in the SQL DELETE statement.
► Example 1:
► Write a query to delete the records from the emp table in which the last name of the employee is
Jain, and the Location is Bangalore.
► Query:
SQL "AND" example with "DELETE" statement
► We will use the SELECT query to verify the deleted record.
SQL "AND" example with "DELETE" statement
► Example 2:
► Write a query to delete the records from the emp table in which department of the employee is IT
and Location is Mumbai.
► Query:

► We will use the SELECT query to verify the deleted record.


SQL "AND" example with "DELETE" statement
SQL OR
► The SQL OR condition is used in SQL query to create a SQL statement where records are returned
when any one condition met.

► It can be used in SELECT statement, INSERT statement, UPDATE statement or DELETE statement.

► Let's see the syntax for the OR condition:


SQL OR
SQL OR
► This is how an SQL "OR" condition can be used in the SQL SELECT statement.
► Example 1:
► Write a query to get the records from emp tables in which department of the employee is IT or
location is Chennai.
► Query:
SQL OR
► Example 2:
► Write a query to get the records from emp tables in which department of the employee is
Marketing or location is Noida.
► Query:
SQL OR
SQL "OR" example with SQL UPDATE
► This is how the "OR" condition can be used in the SQL UPDATE statement.
► Example 1:
► Write a query to update the records in emp tables in which department of the employee is Marketing,
or the last name is Tarle. For that particular employee, set the updated value of the location as Delhi.

► Query:

► mysql> UPDATE emp SET Location = "Delhi" WHERE Department = "Marketing" OR Last_Name = "Tarle";

► We will use the SELECT query to verify the updated record.


SQL "OR" example with SQL UPDATE
SQL "OR" example with SQL UPDATE
► Example 2:
► Write a query to update the records in the emp table in which department of the employee is Finance, or
the first name is Sandhya. For that particular employee, set the updated value of the department as HR.
► Query:
► mysql> UPDATE emp SET Department = "HR" WHERE Department = "Finance" OR First_Name = "Sandhya";

► We will use the SELECT query to verify the updated record.


SQL "OR" example with SQL UPDATE
SQL "OR" example with SQL DELETE
► This is how an SQL "OR" condition can be used in the SQL DELETE statement.
► Example 1:
► Write a query to delete the records from the emp table in which the last name of the employee is Jain or
Location is Bangalore.
► Query:

► We will use the SELECT query to verify the deleted record.


SQL "OR" example with SQL DELETE
SQL "OR" example with SQL DELETE
► Example 2:
► Write a query to delete the records from the emp table in which department of the employee is marketing
and Location is Delhi.
► Query:

► We will use the SELECT query to verify the deleted record.


SQL "OR" example with SQL DELETE
SQL Aggregate Functions
► SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table.
It returns a single value.
► It is also used to summarize the data.
► Types of SQL Aggregation Function
SQL Aggregate Functions
► 1. COUNT FUNCTION

► COUNT function is used to Count the number of rows in a database table. It can work on both numeric and
non-numeric data types.

► COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table. COUNT(*)
considers duplicate and Null.

► Syntax

► COUNT(*)
► or
► COUNT( [ALL|DISTINCT] expression )
SQL Aggregate Functions
SQL Aggregate Functions
► Example: COUNT()
SQL Aggregate Functions
► Example: COUNT with WHERE
SQL Aggregate Functions
► Example: COUNT() with DISTINCT
SQL Aggregate Functions
► Example: COUNT() with GROUP BY
SQL Aggregate Functions
► Example: COUNT() with HAVING
SQL Aggregate Functions
► 2. SUM Function

► Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.

► Syntax
SQL Aggregate Functions
► Example: SUM()

► Output:
SQL Aggregate Functions
► Example: SUM() with WHERE
SQL Aggregate Functions
► Example: SUM() with GROUP BY
SQL Aggregate Functions
► Example: SUM() with HAVING
SQL Aggregate Functions
► 3. AVG function
► The AVG function is used to calculate the average value of the numeric type. AVG function returns the
average of all non-Null values.

► Syntax
SQL Aggregate Functions
► Example:

► Output:
SQL Aggregate Functions
► 4. MAX Function

MAX function is used to find the maximum value of a certain column. This function determines the largest
value of all selected values of a column.
SQL Aggregate Functions
SQL Aggregate Functions
► 5. MIN Function

MIN function is used to find the minimum value of a certain column. This function determines the smallest
value of all selected values of a column.
SQL Aggregate Functions
► Example:
SQL Aggregate Functions
► Example:
SQL String Functions
► SQL String functions are the predefined functions that allow the database users for string manipulation.
These functions only accept, process, and give results of the string data type.
► Following are the most important string functions in Structured Query Language:

► ASCII(), CHAR_LENGTH(), CHARACTER_LENGTH(), CONCAT(), CONCAT_WS(),

FIND_IN_SET(), FORMAT(), INSERT(), INSTR(), LCASE(), LEFT(), LOCATE(),

LOWER(), LPAD(), LTRIM(), MID(), POSITION(), REPEAT(), REPLACE(), REVERSE(),

RIGHT(), RPAD(), RTRIM(), SPACE(), STRCMP(), SUBSTR(), SUBSTRING(),

SUBSTRING_INDEX(), UCASE(), UPPER()


SQL String Functions

Faculty_Id Faculty_First_Name Faculty_Last_Name Faculty_Dept_Id Faculty_Address Faculty_City Faculty_Salary

1001 Arush Sharma 4001 Aman Vihar Delhi 20000

1002 Bulbul Roy 4002 Nirman Vihar Delhi 38000

1004 Saurabh Roy 4001 Sector 128 Mumbai 45000

1005 Shivani Singhania 4001 Vivek Vihar Kolkata 42000

1006 Avinash Sharma 4002 Sarvodya Calony Delhi 28000

1007 Shyam Besas 4003 Krishna Nagar Lucknow 35000


ASCII String Function
► This function in SQL returns the ASCII value of the character in the output. It gives the ASCII value of the
left-most character of the string.
ASCII String Function
► This function in SQL returns the ASCII value of the character in the output. It gives the ASCII value of the
left-most character of the string.

► This query shows the ASCII code of the first character of all cities of the Faculty_City column.
CHAR_LENGTH String Function
► This string function returns the length of the specified word. It shows the number of characters from the
word.

► SELECT CHAR_LENGTH(‘LDCE');
► Output:
► 4
CHAR_LENGTH String Function
► Example 2: This example uses CHAR_LENGTH() with the Faculty_Last_Name column of the above
Faculty_Info table.

► This query shows the total number of characters of the last name of each faculty.
► Output:
CHAR_LENGTH String Function
CHARACTER_LENGTH String Function
► This string function returns the length of the given string. It shows the number of all characters and spaces
from the sentence.
CHARACTER_LENGTH String Function
► Example 1: The following SELECT query shows the total number of characters and spaces of the specified
string:

► SELECT CHARACTER_LENGTH(‘Welcome to LDCE’);

► Output:

► 15
CHARACTER_LENGTH String Function
► Example 2: The following SELECT query uses CHARACTER_LENGTH() with the Faculty_Addresss column of
the above Faculty_Info table.

► This SQL statement shows the total number of characters and spaces of the address of each faculty.
CHARACTER_LENGTH String Function
CONCAT String Function
► This string function concatenates two strings or words and forms a new string in the result.

► Syntax2: This syntax uses CONCAT() with multiple strings:



CONCAT String Function
► Examples of CONCAT string function:

► Example 1: The following SELECT query appends the multiple strings into a single string:

► SELECT CONCAT(‘Welcome', ' to', ‘ LDCE.');

► Output:

► Welcome to LDCE.
CONCAT String Function
► Example 2: The following SELECT query uses CONCAT() with the Faculty_First_Name and
Faculty_Last_Name columns of above Faculty_Info table:

► SELECT Faculty_First_Name, Faculty_Last_Name CONCAT(Faculty_First_Name, Faculty_Last_Name) AS


Append_First_LastName FROM Faculty_Info;

► This SQL statement merges the first name and last name of each faculty as shown in the below table:
CONCAT String Function
► Output:
CONCAT_WS String Function
► This string function concatenates multiple strings or words with the help of concatenating symbol. This
function uses another parameter that denotes the concatenate symbol.

► Syntax of CONCAT_WS String Function:


► Syntax1: This syntax uses CONCAT_WS() with table columns:
SQL ORDER BY Clause
► Whenever we want to sort the records based on the columns stored in the tables of the SQL database, then
we consider using the ORDER BY clause in SQL.

► The ORDER BY clause in SQL will help us to sort the records based on the specific column of a table. This
means that all the values stored in the column on which we are applying ORDER BY clause will be sorted,
and the corresponding column values will be displayed in the sequence in which we have obtained the
values in the earlier step.

► Using the ORDER BY clause, we can sort the records in ascending or descending order as per our
requirement. The records will be sorted in ascending order whenever the ASC keyword is used with ORDER
by clause. DESC keyword will sort the records in descending order.

► If no keyword is specified after the column based on which we have to sort the records, in that case,
the sorting will be done by default in the ascending order.
SQL ORDER BY Clause
► Syntax to sort the records in ascending order:

► Syntax to sort the records in descending order:


SQL ORDER BY Clause
► Syntax to sort the records in ascending order without using ASC keyword:
SQL ORDER BY Clause
► Syntax to sort the records in ascending order:

► Syntax to sort the records in descending order:


SQL ORDER BY Clause
► Consider we have customers table with the following records:
SQL ORDER BY Clause
► Example 1:
► Write a query to sort the records in the ascending order of the customer names stored in the customers
table.
► Query:

► Here in a SELECT query, an ORDER BY clause is applied on the column 'Name' to sort the records. ASC
keyword will sort the records in ascending order.
SQL ORDER BY Clause
► You will get the following output:

All the records present in the customers table are displayed in the ascending order of the customer's name.
SQL ORDER BY Clause
► Example 2:
► Write a query to sort the records in the ascending order of the addresses stored in the customers table.
► Query:

► Here in a SELECT query, an ORDER BY clause is applied to the 'Address' column to sort the records. No
keyword is used after the ORDER BY clause. Hence, the records, by default, will be sorted in ascending
order.
SQL ORDER BY Clause
► You will get the following output:
SQL ORDER BY Clause
► Example 3:
► Write a query to sort the records in the descending order of the customer salary stored in the
customers table.
► Query:

► Here in a SELECT query, an ORDER BY clause is applied on the column ?Salary? to sort the records. DESC
keyword will sort the records in descending order.
SQL ORDER BY Clause
► You will get the following output:
SQL ORDER BY Clause
► Example 4:
► Write a query to sort the records in the descending order of the customer age stored in the customers
table.
► Query:

► Here in a SELECT query, an ORDER BY clause is applied on the column 'Age' to sort the records. DESC
keyword will sort the records in descending order.
SQL ORDER BY Clause
► You will get the following output:

HAVING Clause in SQL
► The HAVING clause places the condition in the groups defined by the GROUP BY clause in the SELECT
statement.

► This SQL clause is implemented after the 'GROUP BY' clause in the 'SELECT' statement.

► This clause is used in SQL because we cannot use the WHERE clause with the SQL aggregate functions.

► Both WHERE and HAVING clauses are used for filtering the records in SQL queries.
Difference between HAVING and WHERE Clause
The main difference is that the WHERE clause uses condition for filtering records before any groupings are
made, while HAVING clause uses condition for filtering values from a group.
Syntax of HAVING clause in SQL
► Examples of HAVING clause in SQL

► We have taken the following four different examples which will help you how to use the HAVING clause
with different SQL aggregate functions:

► Example 1: Let's take the following Employee table, which helps you to analyze the HAVING clause with
SUM aggregate function:

► SELECT column_Name1, column_Name2, ....., column_NameN aggregate_function_name(column_Name)


FROM table_name GROUP BY column_Name1 HAVING condition;
Syntax of HAVING clause in SQL

► If you want to add the salary of employees for each city, you have to write the following query:
Syntax of HAVING clause in SQL
Syntax of HAVING clause in SQL
► Now, suppose that you want to show those cities whose total salary of employees is more than 5000. For
this case, you have to type the following query with the HAVING clause in SQL:

► The output of the above SQL query shows the following table in the output:
Syntax of HAVING clause in SQL
► Example 2: Let's take the following Student_details table, which helps you to analyze the HAVING clause
with the COUNT aggregate function:
Syntax of HAVING clause in SQL
► Suppose, you want to count the number of students from the above table according to their age. For this,
you have to write the following query:

► The above query will show the following output:


Syntax of HAVING clause in SQL
► Now, suppose that you want to show the age of those students whose roll number is more than and equals
2.
► For this case, you have to type the following query with the HAVING clause in SQL:

► The output of the above SQL query shows the following table in the output:
Syntax of HAVING clause in SQL
► Example 3: Let's take the following Employee table, which helps you to analyze the HAVING clause with
MIN and MAX aggregate function:
Syntax of HAVING clause in SQL
► MIN Function with HAVING Clause:
► If you want to show each department and the minimum salary in each department, you have to write the
following query:

► The output of the above query shows the following output:


Syntax of HAVING clause in SQL
► Now, suppose that you want to show only those departments whose minimum salary of employees is
greater than 4000. For this case, you have to type the following query with the HAVING clause in SQL:

► The above SQL query shows the following table in the output:
Syntax of HAVING clause in SQL
► MAX Function with HAVING Clause:
► In the above employee table, if you want to list each department and the maximum salary in each
department. For this, you have to write the following query:

► The above query will show the following output:


Syntax of HAVING clause in SQL
► Now, suppose that you want to show only those departments whose maximum salary of employees is less
than 8000. For this case, you have to type the following query with the HAVING clause in SQL:

► The output of the above SQL query shows the following table in the output:
SQL SELECT Statement
► The SELECT statement is the most commonly used command in Structured Query Language. It is used to
access the records from one or more database tables and views. It also retrieves the selected data that
follow the conditions we want.

► SELECT Column_Name_1, Column_Name_2, ....., Column_Name_N FROM Table_Name;

► If you want to access all rows from all fields of the table, use the following SQL SELECT syntax with *
asterisk sign:

► SELECT * FROM table_name;


SQL SELECT Statement
SELECT Statement with WHERE clause
► The WHERE clause is used with SELECT statement to return only those rows from the table, which satisfy
the specified condition in the query.

► SELECT * FROM Name_of_Table WHERE [condition];

► In the syntax, we specify the condition in the WHERE clause using SQL logical or comparison operators.

► SELECT * FROM Employee_Details WHERE Emp_Panelty = 500;


SELECT Statement with WHERE clause
► This SELECT query displays the following table in result:
SQL SELECT Statement with GROUP BY clause
► The GROUP BY clause is used with the SELECT statement to show the common data of the column from
the table:

► SELECT column_Name_1, column_Name_2, ....., column_Name_N aggregate_function_name


(column_Name2) FROM table_name GROUP BY column_Name1;
SQL SELECT Statement with GROUP BY clause
► The following SELECT with GROUP BY query lists the number of cars of the same price:

► SELECT COUNT (Car_Name), Car_Price FROM Cars_Details GROUP BY Car_Price;


SQL SELECT Statement with HAVING clause
► The HAVING clause in the SELECT statement creates a selection in those groups which are defined by the
GROUP BY clause.

► SELECT column_Name_1, column_Name_2, ....., column_Name_N aggregate_function_name(column_Nam


e_2) FROM table_name GROUP BY column_Name1 HAVING ;
SQL SELECT Statement with HAVING clause
► The following query shows the total salary of those employees having more than 5000 from the above
Employee_Having table:

► SELECT SUM (Employee_Salary), Employee_City FROM Employee_Having GROUP BY Employee_City HAVING


SUM(Employee_Salary)>50000;
► This HAVING query with SELECT statement shows the following table:
SELECT Statement with ORDER BY clause
► The ORDER BY clause with the SQL SELECT statement shows the records or rows in a sorted manner.
► The ORDER BY clause arranges the values in both ascending and descending order. Few database systems
arrange the values of column in ascending order by default.
► SELECT Column_Name_1, Column_Name_2, ....., column_Name_N FROM table_name WHERE [Condition]
ORDER BY[column_Name_1, column_Name_2, ....., column_Name_N asc | desc ];
SELECT Statement with ORDER BY clause
► SELECT * FROM Employee_Order ORDER BY Emp_Salary DESC;
► This SQL query shows the following table in result:
SQL SELECT UNIQUE
► Actually, there is no difference between DISTINCT and UNIQUE.

► we can say that SELECT UNIQUE statement is used to retrieve a unique or distinct element from the table.

► SELECT UNIQUE column_name FROM table_name;


SQL SELECT DISTINCT
► The SQL DISTINCT command is used with SELECT key word to retrieve only distinct or unique data.

► In a table, there may be a chance to exist a duplicate value and sometimes we want to retrieve only unique
values. In such scenarios, SQL SELECT DISTINCT statement is used.

► SELECT DISTINCT column_name ,column_name FROM table_name;


SQL SELECT DISTINCT
► Here is a table of students from where we want to retrieve distinct information For example: distinct
home-town.

► SELECT DISTINCT home_town FROM students

► Now, it will return two rows.


SQL SELECT COUNT
► The SQL COUNT() is a function that returns the number of records of the table in the output.
► This function is used with the SQL SELECT statement.
► Let's take a simple example: If you have a record of the voters in the selected area and want to count the
number of voters, then it is very difficult to do it manually, but you can do it easily by using SQL SELECT
COUNT query.

► SELECT COUNT(column_name) FROM table_name;

► In the syntax, we have to specify the column's name after the COUNT keyword and the name of the table on
which the Count function is to be executed.
Examples of Select Count Function in SQL
► Example 1: In this example, we have a table called Bike with three columns:
Examples of Select Count Function in SQL
► Suppose, you want to count the total number of bike colors from Bike Table. For this operation, you have to
write the following SQL statement:

► SELECT COUNT (Bike_Color) AS TotalBikeColor FROM Bikes ;

► This query will show the following output on the screen:


Examples of Select Count Function in SQL
► Suppose, you want to count the total values of the Bike_Cost column from the above Bike Table. For this
operation, you have to write the following statement in SQL:

► SELECT COUNT (Bike_Cost) AS TotalBikeCost FROM Bikes ;

► This query will show the following output on the screen:

► The output of this query is four because two values of the Bike_Cost column are NULL and, these two NULL
values are excluded from the count function. That's why this query shows four instead of 6 in the output.
Examples of Select Count Function in SQL
► Example 2: In this example, we have an Employee_details table with four columns:
Examples of Select Count Function in SQL
► Suppose, you want to count the total values of the Emp_City column of the above Employee_details table.
For this query, you have to write the following statement in Structured Query Language:

► SELECT COUNT (Emp_City) AS TotalCity FROM Employee_details ;

► This query will show the following output on the screen:

► The output of this query is two because the three values of the Emp_City column are NULL. And, these
three NULL values are excluded from the count function. That's why this query shows two instead of 5 in the
output.
Examples of Select Count Function in SQL
► Select Count(*) Function in SQL
► The count(*) function in SQL shows all the Null and Non-Null records present in the table.
► SELECT COUNT(*) FROM table_name;
► In this example, we have the following Bike table with three columns:
Examples of Select Count Function in SQL
► Suppose, you want to count the total number of records from the Bike Table. For this condition, you have to
write the following statement in Structured Query Language:

► SELECT COUNT (*) FROM Bikes ;

► This query will show the following output on the screen:


SQL Count() Function With WHERE Clause
► We can also use the Count() function with the WHERE clause. The Count Function with WHERE clause in the
SELECT statement shows those records that matched the specified criteria.

► SELECT COUNT(column_name) FROM table_name WHERE [condition];


Examples of Count Function With WHERE clause in
SQL
► Example 1: In this example, we have the following Bike table with three columns:
Examples of Count Function With WHERE clause in
SQL
► Suppose, you want to count the total number of bikes whose color is black. For this, you have to type the
following statement in SQL:

► SELECT COUNT (Bike_Name) AS TotalBikeBlackColor FROM Bikes WHERE Bike_Color = 'Black';

► This query will show the following output on the screen:


Examples of Count Function With WHERE clause in
SQL
► Example 2: In this example, we have an Employee_details table with four columns:
Examples of Count Function With WHERE clause in
SQL
► Suppose, you want to count the total number of those employees who belong to Delhi city. For this, you
have to write the following SQL statement:
► SELECT COUNT (Emp_Name) AS TotalEmpCity FROM Employee_details WHERE Emp_City = 'Delhi';
► This query will show the following output on the screen:
SQL Count Function With DISTINCT keyword
► The DISTINCT keyword with the COUNT function shows only the numbers of unique rows of a column.

► SELECT COUNT(DISTINCT column_name) FROM table_name WHERE [condition];


Examples of Count Function With DISTINCT keyword in
SQL
► Example 1:
► In this example, we have taken the following Cars table with three columns:
Examples of Count Function With DISTINCT keyword in
SQL
► Suppose, you want to count the unique colors of a car from the above table. For this query, you have to
write the below statement in SQL:

► SELECT COUNT (DISTINCT Car_Color) AS Unique_Car_Color FROM Cars ;

► This query will show the following output on the screen:


Examples of Count Function With DISTINCT keyword in
SQL
► Example 2:
► In this example, we have taken an Employee table with four columns:
Examples of Count Function With DISTINCT keyword in
SQL
► Suppose, you want to count the unique values of the Emp_Salaryfield from the Employee_details table. For
this, you have to write the following statement in Structured Query Language:

► SELECT COUNT (DISTINCT Emp_Salary) AS Unique_Salary FROM Employee ;

► This query will show the following output on the screen:


SQL SELECT TOP

► The SELECT TOP statement in SQL shows the limited number of records or rows from the database table.
The TOP clause in the statement specifies how many rows are returned.

► It shows the top N number of rows from the tables in the output. This clause is used when there are
thousands of records stored in the database tables.

► Let's take a simple example: If a Student table has a large amount of data about students, the select TOP
statement determines how much student data will be retrieved from the given table.

► SELECT TOP number | percent column_Name1, column_Name2, ....., column_NameN FROM table_name
WHERE [Condition] ;
Examples of TOP Clause in SQL

► Example 1: In this example, we have a table called Cars with three columns:
Examples of TOP Clause in SQL

► Suppose, you want to show the first three Names and Color of Car from the above table. To do this, you
have to type the following query in SQL:
► SELECT TOP 3 Car_Name, Car_Color FROM Cars;
Examples of TOP Clause in SQL

► Example 2: In this example, we have a table called Student with three columns:
Examples of TOP Clause in SQL

► Suppose, you want to show the details of the first four students in the result from the above table. To do
this, you have to type the following query in SQL:

► SELECT TOP 4 * FROM Student;


Examples of TOP Clause in SQL

► Example 3: In this example, we have a table called Employee with four columns:
Examples of TOP Clause in SQL

► Suppose, you want to show the details of those first four employees whose city is Goa from the above table.
To do this, you have to type the following query in SQL:

► SELECT TOP 4 * FROM Employee WHERE Emp_City = Goa ;


Examples of TOP Clause in SQL

► Example 4: In this example, we have a table called Bikes with three columns:
Examples of TOP Clause in SQL

► Suppose, you want to show the 50 percent of data from the above table. To do this, you have to type the
following query in SQL:

► SELECT TOP 50 PERCENT * FROM Bikes;

► This query shows the following table on the screen:


Syntax of LIMIT Clause in MySQL

► SELECT column_Name1,column_Name2, ....., column_NameN FROM table_name LIMIT


value;

► In the syntax, we have to specify the value after the LIMIT keyword. The value denotes
the number of rows to be shown from the top in the output.
Example of LIMIT Clause in MySQL

► The following SQL example will help you how to use the LIMIT clause in the query. In this example, we have
a table called Cars with three columns:
Example of LIMIT Clause in MySQL

► Suppose, you want to show the first three records of Car using a LIMIT clause in MySQL. To do this,
you have to type the following query in MySQL:

► SELECT * FROM Cars LIMIT 3;


SQL SELECT AS

► SQL 'AS' is used to assign a new name temporarily to a table column or even a table.

► It makes an easy presentation of query results and allows the developer to label results more accurately
without permanently renaming table columns or even the table itself.

► Let's see the syntax of select as:

► SELECT Column_Name1 AS New_Column_Name, Column_Name2 As New_Column_Name FROM Table_Name;

► Here, the Column_Name is the name of a column in the original table, and the New_Column_Name is the
name assigned to a particular column only for that specific query. This means that New_Column_Name is a
temporary name that will be assigned to a query.
SQL SELECT AS

► Assigning a temporary name to the column of a table:


SQL SELECT AS

► Example:
► Suppose you want to rename the 'day_of_order' column and the 'customer' column as 'Date' and 'Client',
respectively.

► SELECT day_of_order AS 'Date', Customer As 'Client', Product, Quantity FROM orders;


SQL SELECT AS

► Let us take another example. Consider we have a students table with the following data.

Student_RollNo Student_Name Student_Gender Student_MobileNumber Student_HomeTown Student_Age Student_Percentage

1 Rohit More Male 9890786123 Lucknow 23 75


2 Kunal Shah Male 7789056784 Chandigarh 20 92
3 Kartik Goenka Male 9908743576 Ahemdabad 22 89

4 Anupama Shah Female 8890907656 Chennai 24 92

5 Snehal Jain Female 8657983476 Surat 21 94


SQL SELECT AS

► Example 1:
► Write a query to get the student name and the average of the percentage of the student under the
temporary column name 'Student' and 'Student_Percentage', respectively.

► SELECT Student_Name AS Student, AVG (Student_Percentage) AS Average_Percentage FROM students;


SQL SELECT AS
► Example 2:
► Write a query to get the student roll number and the student mobile number under the temporary column
name 'Roll No' and 'Mobile Number', respectively.

► SELECT Student_RollNo AS 'Roll No', Student_PhoneNumber AS 'Mobile Number' FROM students;


SQL SELECT AS
► Example 3:
► Write a query to get the student roll number and the student phone number, home town under the
temporary column name 'Roll No' and 'Student_Info', respectively.
► SELECT Student_RollNo AS 'Roll No', CONCAT (Student_PhoneNumber, ', ', Student_HomeTown) AS
Student_Info FROM students;
Assigning a temporary name to a table

► Instead of remembering the table names, we can create an alias of them. We can assign a temporary name to
the columns of a table; similarly, we can create an alias of a table.
► Write a query to create an alias of a table named 'students'.
► SELECT s.Student_RollNo, s.Student_Name, s.Student_Gender, s.Student_PhoneNumber, s.Student_HomeTow
n FROM students AS s WHERE s.Student_RollNo = 3;

► Here, 's' is the alias, i.e., the temporary name assigned to the 'students' table.

Student_RollNo Student_Name Student_Gender Student_MobileNumber Student_HomeTown

3 Kartik Goenka Male 9908743576 Ahemdabad


SQL SELECT IN

► SQL IN is an operator used in a SQL query to help reduce the need to use multiple SQL "OR" conditions.

► It is used in SELECT, INSERT, UPDATE or DELETE statement.

► Advantage of SQL SELECT IN

► It minimizes the use of SQL OR operator.

► Expression IN (value 1, value 2 ... value n);


SQL SELECT IN

► Take an example with character values.


► SELECT * FROM students WHERE students_name IN ( Amit , Raghav, Rajeev)

► Let's take another example with numeric values.


► SELECT * FROM marks WHERE roll_no IN (001, 023, 024);
SQL SELECT from Multiple Tables

► This statement is used to retrieve fields from multiple tables. To do so, we need to use join query to get
data from multiple tables.

► Let's see the example for the select from multiple tables:

► SELECT orders.order_id, suppliers.name


► FROM suppliers
► INNER JOIN orders
► ON suppliers.supplier_id = orders.supplier_id
► ORDER BY order_id;
SQL SELECT from Multiple Tables

► Let us take three tables, two tables of customers named customer1 and customer2 and the third table is
product table.

► Customer1 table
SQL SELECT from Multiple Tables

► Let us take three tables, two tables of customers named customer1 and customer2 and the third table is
product table.

► Customer2 table
SQL SELECT from Multiple Tables

► Let us take three tables, two tables of customers named customer1 and customer2 and the third table is
product table.

► Product table
SQL SELECT from Multiple Tables

► Example syntax to select from multiple tables:

► SELECT p. p_id, p.cus_id, p.p_name, c1.name1, c2.name2


► FROM product AS p
► LEFT JOIN customer1 AS c1
► ON p.cus_id=c1.cus_id
► LEFT JOIN customer2 AS c2
► ON p.cus_id = c2.cus_id
SQL SELECT from Multiple Tables
SQL SELECT DATE

► SQL SELECT DATE is used to retrieve a date from a database. If you want to find a particular date from a
database, you can use this statement.

► For example: let's see the query to get all the records after '2013-12-12'.

► SELECT * FROM table-name WHERE your date-column >= '2013-12-12'

► Let's see the another query to get all the records after '2013-12-12' and before '2013-12-13' date.

► SELECT* FROM table-name where your date-column < '2013-12-13' and your date-column >= '2013-12-12'
SQL SELECT DATE

► If you want to compare the dates within the query, you should use BETWEEN operator to compare the dates.

► SELECT * FROM table_name WHERE yourdate BETWEEN '2012-12-12' and '2013-12-12'


SQL SELECT SUM

► It is also known as SQL SUM() function. It is used in a SQL query to return summed value of an expression.

► Let's see the Syntax for the select sum function:

► SELECT SUM (expression)


► FROM tables
► WHERE conditions;

► expression may be numeric field or formula.


SQL SELECT SUM
► This would produce the following result.

► After using this SQL SELECT SUM example, it will produce the result containing the sum of the salary greater
than 20000.
► Total salary: 116,000
SQL SUM EXAMPLE with single field:
► If you want to know how the combined total salary of all employee whose salary is above 20000 per month.

► SELECT SUM (salary) AS "Total Salary"


► FROM employees
► WHERE salary > 20000;

► In this example, you will find the expression as "Total Salary" when the result set is returned.
SQL SUM EXAMPLE with SQL DISTINCT:
► You can also use SQL DISTINCT clause with SQL SUM function.

► SELECT SUM (DISTINCT salary) AS "Total Salary"


► FROM employees
► WHERE salary > 20000;
SQL SUM EXAMPLE with SQL GROUP BY:
► Sometimes there is a need to use the SQL GROUP BY statement with the SQL SUM function.

► For example, we could also use the SQL SUM function to return the name of department and the total sales
related to department.

► SELECT department, SUM (sales) AS "Total Sales"


► FROM order_details
► GROUP BY department;
SQL SUM EXAMPLE with SQL GROUP BY:
► Let us take a table named order_details
SQL SUM EXAMPLE with SQL GROUP BY:
► After using the SQL GROUP BY statement with SUM, you will find the following result.
SQL SELECT NULL
► First of all we should know that what null value is? Null values are used to represent missing unknown data.
► There can be two conditions:
► Where SQL is NULL
► Where SQL is NOT NULL
► If in a table, a column is optional, it is very easy to insert data in column or update an existing record
without adding a value in this column. This means that field has null value.

► Note: we should not compare null value with 0. They are not equivalent.
SQL SELECT NULL
► Where SQL is NULL:
► How to select records with null values only? (in the marks column)

► There is an example of student table:


SQL SELECT NULL
► Let's see the query to get all the records where marks is NULL:

► SELECT SIR_NAME, NAME, MARKS FROM STUDENTS WHERE MARKS IS NULL

► It will return the following records:


SQL SELECT NULL
► Where SQL is NOT NULL:
► How to select records with no null values(in marks column)? Let's see the query to get all the records where
marks is NOT NULL

► SELECT SIR_NAME, FIRSTNAME, MARKS FROM STUDENTS WHERE MARKS IS NOT NULL

You might also like