sql
sql
What is Database
► 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
► 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
► 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:
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:
► 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
► 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.
► NOT NULL
► UNIQUE
► PRIMARY KEY
► FOREIGN KEY
► CHECK
1. NOT NULL
► Whenever a table's column is declared as NOT NULL, then the value for that column cannot be
► There must exist a value in the column to which the NOT NULL constraint is applied.
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.
► 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:
► Example:
► Create a student table and apply a UNIQUE constraint on one of the table's column while
creating a table.
► 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
► Example:
► Create a student table and apply a UNIQUE constraint on more than one table's column
while creating a table.
► 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:
► Example:
► Create a student table and apply the PRIMARY KEY constraint while creating a 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:
► 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:
► 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.
► Example:
► 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
► Example:
► Create a student table and apply CHECK constraint to check for the age less than or
equal to 15 while creating a table.
► 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.
► 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.
► 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.
► 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:
► 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.
► 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:
► It can be used in SELECT statement, INSERT statement, UPDATE statement or DELETE statement.
► Query:
► mysql> UPDATE emp SET Location = "Delhi" WHERE Department = "Marketing" OR Last_Name = "Tarle";
► 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:
► 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:
► 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.
► Example 1: The following SELECT query appends the multiple strings into a single string:
► 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:
► 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.
► 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:
► 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:
► 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 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 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 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.
► If you want to access all rows from all fields of the table, use the following SQL SELECT syntax with *
asterisk sign:
► In the syntax, we specify the condition in the WHERE clause using SQL logical or comparison operators.
► we can say that SELECT UNIQUE statement is used to retrieve a unique or distinct element from the table.
► 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.
► 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:
► 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:
► 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:
► 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:
► 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:
► 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:
► 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:
► 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.
► 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
► Example:
► Suppose you want to rename the 'day_of_order' column and the 'customer' column as 'Date' and 'Client',
respectively.
► Let us take another example. Consider we have a students table with the following data.
► 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.
► 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.
► SQL IN is an operator used in a SQL query to help reduce the need to use multiple SQL "OR" conditions.
► 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:
► 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
► 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'.
► 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.
► It is also known as SQL SUM() function. It is used in a SQL query to return summed value of an expression.
► 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.
► 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.
► For example, we could also use the SQL SUM function to return the name of department and the total sales
related to department.
► 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)
► SELECT SIR_NAME, FIRSTNAME, MARKS FROM STUDENTS WHERE MARKS IS NOT NULL