1.introduction SQL Part-1
1.introduction SQL Part-1
Introduction to SQL
• Structured Query Language – SQL is the most common language used to communicate with the
database.
Users Database
Create
Insert / Delete
Update
Select
3 SQL | © SmartCliff | Internal | Version 1.0
MySQL
Introduction to SQL
• Deals with description of database objects like create and modify the structure of the object.
• All DDL commands are auto-committed, which means they store all database changes permanently.
• Keywords :
• DML Command are not auto - committed , it means changes by DML command are not permanent it can be roll
back.
• Keywords :
• Keywords:
▪ REVOKE - Withdraws the user’s access privileges given by using the GRANT command.
• Transaction :
• A transaction is the logical work unit that performs a single activity or multiple activities in a database.
• Transactions may consist of a single read, write, delete, or update operations or a combination of these.
• TCL
• Keywords :
• Rollback : Restores the database to the original state since last commit.
• Savepoint : Used to temporarily save transaction so that you can rollback to that point whenever necessary.
DataTypes
• Each column in a database table is required to have a name and a data type.
• Numeric Datatype
• String Datatype
Datatypes - Numeric
Storage Minimum Value Minimum Value Maximum Value Maximum Value
Type
(Bytes) Signed Unsigned Signed Unsigned
Datatypes – String
Types Description Categories Range
Contains non-binary strings. Length is
fixed as you declare while creating a
Trailing spaces are The length can be any value from 0
CHAR table. When stored, they are
removed. to 255.
rightpadded with spaces to the
specified length.
A value from 0 to 255 before MySQL
Contains non-binary strings. Columns
VARCHAR As stored. 5.0.3, and 0 to 65,535 in 5.0.3 and
are variable-length strings.
later versions.
BINARY Contains binary strings. - 0 to 255
A value from 0 to 255 before MySQL
VARBINARY Contains binary strings. - 5.0.3, and 0 to 65,535 in 5.0.3 and
later versions.
Datatypes – String
Types Description Categories Range
Create Command
Syntax :
CREATE DATABASE databasename;
Example:
CREATE DATABASE menagerie;
DROP Command
Syntax :
DROP DATABASE databasename;
Example:
DROP DATABASE menagerie;
Create Command
• The Create command is used for creating a table. Table is the base object in a database
Syntax:
Example:
CREATE TABLE table_name (
CREATE TABLE pet (
column1 datatype,
name VARCHAR(20),
column2 datatype,…
owner VARCHAR(20),
column3 datatype,
species VARCHAR(20),
………
);
);
Lexical Issues
• Must be unique.
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE pet;
• TRUNCATE is used to delete all the rows in the table but maintains the structure of the table.
Syntax:
TRUNCATE TABLE table_name;
• The alter table command is used to modify the structure of the table.
• Modifying the structure includes adding columns, constraints, changing data types and sizes,
Syntax:
ALTER TABLE table_name ADD column_name datatype;
Example:
ALTER TABLE pet ADD sex CHAR(1);
Syntax:
ALTER TABLE table_name DROP COLUMN column_name;
Example:
ALTER TABLE pet DROP COLUMN death ;
• Used the MODIFY option in the ALTER TABLE command to change the definition of the column. The
Syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Example:
ALTER TABLE pet
MODIFY COLUMN sex varchar(10);
• The RENAME COLUMN statement is used to change the name of the column
Syntax:
Example:
Syntax:
RENAME table old_name to new_name;
Example:
RENAME table pet to pet_animal;
MySQL Constraints
Types of Constraints
Types of Constraints
Example - NOT NULL Agent_Details
Data
Field Name Size NULL
Type
agent_code char 6 No
agent_name varchar 25 No
working_area varchar 25 No
Example:
CREATE TABLE Agent_Details (
Types of Constraints
Unique Constraint:
Types of Constraints
Example - Unique Order_Details
ord_date date No
cust_code char 6 No
agent_code char 6 No
Example:
CREATE TABLE Order_details ( order_num DECIMAL(6) NOT NULL UNIQUE,
order_amount DECIMAL(12,2) ,
order_date DATE NOT NULL,
customer_code CHAR(6) NOT NULL,
agent_code CHAR(6) NOT NULL);
33 SQL | © SmartCliff | Internal | Version 1.0
Constraints
Types of Constraints
Types of Constraints
Person_Details
Example - PrimaryKey
Field Name Data Type Size NULL Constraint
Example:
CREATE TABLE person_details ( person_id INT PRIMARY KEY,
person_name VARCHAR(32) NOT NULL,
person_gender CHAR(1) , person_dob DATE ,
person_email VARCHAR(32) NOT NULL UNIQUE );
Types of Constraints
Default Constraint:
Types of Constraints
Check Constraint:
• Can also be used to limit the value of the range that can be placed in a column.
Types of Constraints
Check Constraint:
Person_Details
Example:
Field Name Data Type Size NULL Constraint
CREATE TABLE person_details (
person_id int No primary
person_id INT PRIMARY KEY,
person_name varchar 32 No
person_name varchar(32) NOT NULL,
person_gender char 1 Yes
person_gender CHAR(1) ,
person_age int Yes check
(person_age person_age INT check (person_age >=18) ,
>=18) person_email VARCHAR(32) NOT NULL
person_email varchar 32 No unique UNIQUE,
person_city varchar 32 No default person_city VARCHAR(32) DEFAULT
‘TAMILNADU’ );
Types of Constraints
Customer_orders Example:
Data CREATE TABLE customer_orders (
Field Name Size NULL Constraint
Type
order_id INT PRIMARY KEY,
order_id int No Primary
order_date DATETIME NOT NULL,
order_date datetime No
order_amount INT NOT NULL,customer_id INT
order_amount int No
FOREIGN KEY(customer_id ) REFERENCES
customer_id int No Foreign
customers (customer_id) );
40 SQL | © SmartCliff | Internal | Version 1.0
Constraints
Constraint Levels
Column Level:
Example:
CREATE TABLE customer_orders (
order_id INT PRIMARY KEY,
order_date DATETIME NOT NULL,
order_amount INT NOT NULL,
customer_id INT );
Constraint Levels
Table Level:
Example:
CREATE TABLE customer_orders (
order_id INT ,
order_date DATETIME NOT NULL,
order_amount INT NOT NULL,
customer_id INT,
CONSTRAINT oid_pk PRIMARY KEY(order_id),
FOREIGN KEY(customer_id ) REFERENCES customers (customer_id) );
Constraint Levels
• In MySQL, when you have a table with a foreign key reference to another table, and you want to
delete a row or column from the referenced table, you need to carefully manage how this
deletion affects the referencing table. Here’s how you can handle such scenarios:
When you delete a row in the table that is being referenced by a foreign key in another table, MySQL
needs to know what to do with the referencing rows. You can specify the behavior using foreign key
constraints:
Constraint Levels
Options for Handling Deletions
CASCADE:
o What it does: Automatically deletes rows in the referencing table that match the foreign key
value being deleted.
o Use case: Use this if you want to automatically remove all related records when the parent
record is deleted.
Example:
ALTER TABLE referencing_table
ADD CONSTRAINT fk_constraint_name
FOREIGN KEY (column_in_referencing_table)
REFERENCES
referenced_table(column_in_referenced_table
)
ON DELETE CASCADE;
45 SQL | © SmartCliff | Internal | Version 1.0
Constraints
Constraint Levels
SET NULL:
o What it does: Sets the foreign key column in the referencing table to NULL when the
referenced row is deleted.
o Use case: Use this if you want to retain the referencing row but indicate that the foreign key
reference no longer exists.
Example:
ALTER TABLE referencing_table
ADD CONSTRAINT fk_constraint_name
FOREIGN KEY (column_in_referencing_table)
REFERENCES
referenced_table(column_in_referenced_table
)
ON DELETE SET NULL;
Constraint Levels
RESTRICT:
o What it does: Prevents the deletion of a row in the referenced table if there are any rows in the
referencing table that reference it.
o Use case: Use this if you want to enforce referential integrity strictly and disallow deletion if
dependent rows exist.
Example:
ALTER TABLE referencing_table
ADD CONSTRAINT fk_constraint_name
FOREIGN KEY (column_in_referencing_table)
REFERENCES
referenced_table(column_in_referenced_table
)
ON DELETE RESTRICT;
Constraint Levels
NO ACTION:
o What it does: Similar to RESTRICT, but differs in its behavior in terms of when the restriction
check is performed. Essentially, it behaves like RESTRICT if not explicitly set.
o Use case: Use this for strict enforcement of referential integrity at the end of the transaction.
Example:
ADD CONSTRAINT fk_constraint_name
FOREIGN KEY (column_in_referencing_table)
REFERENCES
referenced_table(column_in_referenced_table
)
ON DELETE NO ACTION;
Constraint Levels
2. Deleting Columns in the Referenced Table : If you want to delete a column that is part of a foreign
key constraint, you must first drop the foreign key constraint that uses that column. After dropping the
Constraint Levels
2. Drop the Column:
ALTER TABLE referenced_table
DROP COLUMN column_to_be_deleted;
Constraint Levels
• For insertions, MySQL ensures referential integrity by enforcing foreign key constraints, which
means you cannot insert a value into the referencing table unless it matches a value in the
referenced table.
• Managing insertions involves ensuring that the foreign key values exist in the referenced table,
using transactions to maintain atomic operations, and handling complex scenarios through
application logic. While there is no direct ON INSERT action, the foreign key constraints themselves
Constraint Levels
On Update Cascade:
Example:
ALTER TABLE referencing_table
ADD CONSTRAINT fk_constraint_name
FOREIGN KEY (column_in_referencing_table)
REFERENCES
referenced_table(column_in_referenced_table)
ON UPDATE CASCADE;
AUTO_INCREMENT Field
• Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table.
• By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
Example:
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int,PRIMARY KEY (Personid));
Syntax:
ALTER TABLE table_name ADD [CONSTRAINT constraint_name]
constraint_type(column_name);
Example
CREATE TABLE CustomerOrders(
order_ID INT ,
Example:
orderDate DATETIME,
ALTER TABLE CustomerOrders add CONSTRAINT amt_chk
Amount BIGINT,
CHECK (Amount >0);
CustomerID INT,
PRIMARY KEY(order_ID),
FOREIGN KEY (CustomerID) REFERENCES
Customers(Customer_ID));
Syntax:
VALUES(value1,value2,value3……);
Example:
Note:
Column name list is optional of values.
Character and date values must be enclosed within single quotation.
Date must be in ‘YYYY-MON-DD’ format.
• Either all the records or a subset may be chosen using WHERE Clause.
Syntax:
UPDATE table SET column1=value1, column2=value2 WHERE condition;
Example:
UPDATE customer SET customer_city = ‘Gluton’ WHERE customer_id = ‘cus_001’;
Syntax:
DELETE FROM table_name [WHERE column=condition];
Example:
DELETE FROM customers WHERE customer_id = ‘cus_001’;
TRUNCATE Query
• Removes all rows from a table, leaving it empty but with its structure intact.
Syntax:
TRUNCATE TABLE table_name ;
Example:
TRUCATE TABLE customers ;
Introduction
• DCL commands are used for access control and permission management for users in our
database.
• With these commands, we can easily allow or deny some actions for users on the tables or
records (row-level security).
Commands Description
GRANT This command gives users access privileges to the database.
REVOKE This command withdraws the user’s access privileges given by using the
GRANT command.
DENY bans certain permissions from users.
Introduction
PRIVILEGES
PRIVILEGE DESCRIPTION
SELECT Ability to perform SELECT statements on the table.
INSERT Ability to perform INSERT statements on the table.
UPDATE Ability to perform UPDATE statements on the table.
DELETE Ability to perform DELETE statements on the table.
REFERENCES Ability to create a constraint that refers to the table.
ALTER Ability to perform ALTER TABLE statements to change the table definition.
ALL does not grant all permissions for the table. Rather, it grants the ANSI-92 permissions
ALL
which are SELECT, INSERT, UPDATE, DELETE, and REFERENCES.
GRANT Command
• Syntax:
GRANT [privilege]
ON [object]
TO [user]
[WITH GRANT OPTION]
• Here's the rundown on each of the parameters that we have used in the above command:
Privilege - can be either the keyword ALL (to grant a wide variety of permissions) or a specific
database permission or set of permissions.
GRANT Command
Object - can be any database object. The valid privilege options vary based on the type of
database object you include in this clause. Typically, the object will be either a database,
User - can be any database user. You can also substitute a role for the user in this clause if
If you include the optional WITH GRANT OPTION clause at the end of the GRANT command,
you not only grant the specified user the permissions defined in the SQL statement but also
give the user permission to further grant those same permissions to other database users.
// Grant permission to the user to retrieve the data from the employee
GRANT SELECT
ON HR.employees
TO Joe
• In Example #1, Joe can retrieve information from the employees' table.
• He will not be able to grant permission to other users to retrieve information from that table because
the DCL script did not include the WITH GRANT OPTION clause.
// Grant permission to the user to retrieve the data from the employee
GRANT UPDATE
ON HR.employees
TO Joe WITH GRANT OPTION
• The WITH GRANT OPTION clause indicates that JOE can grant to other users any of the
// Grant permission to insert the data in the employee with public keyword
GRANT INSERT
ON HR.employees
TO PUBLIC WITH GRANT OPTION
• In example #3, grant the INSERT privilege on the HR.employees table to all users in the local
database, and allow each of those users to grant the INSERT privilege to other users.
REVOKE Command
• The REVOKE command removes database access from a user previously granted such access.
• Syntax:
REVOKE [GRANT OPTION FOR] [permission]
ON [object]
FROM [user]
[CASCADE]
• Here's the rundown on each of the parameters that we have used in the above command:
Permission — specifies the database permissions to remove from the identified user.
The command revokes both grants and DENY assertions previously made for the identified
permission.
REVOKE Command
Object — can be any database object. The valid privilege options vary based on the type of
database object you include in this clause. Typically, the object will be either a database, function,
stored procedure, table, or view.
User — can be any database user. You can also substitute a role for the user in this clause if you
wish to make use of role-based database security.
The GRANT OPTION FOR clause removes the specified user's ability to grant the specified
permission to other users. If you include the GRANT OPTION FOR clause in a REVOKE
statement, the primary permission is not revoked. This clause revokes only the granting ability.
The CASCADE option also revokes the specified permission from any users to whom the specified
user granted the permission.
• In example #2, We used ALL to revoke all the permissions like SELECT, INSERT, UPDATE, DELETE,
and REFERENCES on the table for a user named Joe.
• In example #3, We are revoking the INSERT privileges given to all the users (public role).
71 SQL | © SmartCliff | Internal | Version 1.0
Data Control Language
DENY Command
• The DENY command explicitly prevents a user from receiving a particular permission.
• This feature is helpful when a user is a member of a role or group that is granted permission,
and you want to prevent that individual user from inheriting the permission.
• The parameters for the DENY command are identical to those used for the GRANT command.
Syntax:
DENY [Permission] on [Object] TO [User]
Introduction
• Data Query Language(DQL) is used for fetching data from a relational database.
• Select is one of the most important SQL commands used in the DQL.
• One can fetch either the entire table or some data according to specified rules.
SELECT Command
SYNTAX:
SELECT column1,column2,….. From table_name;
• The above syntax implies that the resultset holds the data from column 1, column 2, and so on from
the original table.
• The above Example, We are retrieving the data of the column FirstName and Age from the Employee
table and after executing the above query, the resultset will be as below
SELECT Command
• We can also retrieve all data from the table with the below syntax:
SYNTAX:
SELECT * From table_name;
• The below Example, We are retrieving the all data from the Employee table using * instead of
specifying the column name.
Example #2: Retrieve all column data from the table
SELECT * From Employee;
• After executing the above example ,the result set will be as follows
SELECT Command
• We can also retrieve the data from the table with alias name as follows:
SYNTAX:
SELECT Column1 As C1, Column2 As C2 from table_name;
• Here C1,C2 are the alias name that will be displayed in the result set instead of the column name.
• The below Example, We are retrieving the all data from the Employee table using * instead of
specifying the column name.
Quiz
2) Which SQL statement is used to extract data
from a database?
a) GET
b) EXTRACT
c) OPEN
d) SELECT
Answer : Option d)
78 SQL | © SmartCliff | Internal | Version 1.0
SQL Statements
Quiz
3) Which of the following is used to add a new
row in the table of SQLdatabase ?
a) ADD
b) CREATE
c) MAKE
d) INSERT
Answer : Option d)
79 SQL | © SmartCliff | Internal | Version 1.0
SQL Statements
Quiz
4) In the given query which of the keyword
must be inserted?
a) Table
b) Values
c) Relation
d) Field
Answer : Option b)
80 SQL | © SmartCliff | Internal | Version 1.0
SQL Statements
Quiz
5) Which of the following is not a DDL
command?
a) DROP
b) UPDATE
c) ALTER
d) CREATE
Answer : Option b)
81 SQL | © SmartCliff | Internal | Version 1.0
SQL Function
Please download pictures in
suitable size here and insert them
by clicking the symbol above.
SQL Functions
• Used to compute values.
• Features:
SQL Functions
Types
• Act on each row that is returned by the query and gives one result per row.
– Character Functions
– Number Functions
– Date Functions
– Conversion Functions
– General Functions.
Character Functions
Types
Types
Syntax:
CONCAT(‘string1’,’string2’)
Example:
SELECT concat(Name,concat ('(',concat (countrycode,')'))) NAME_CCODE FROM
city;
SUBSTR:
• Returns ‘n’ no. of characters from the given string and starting from the ‘m’ th position
Syntax: Example:
SUBSTR(‘string’,m,n) SELECT SUBSTR(COUNTRYCODE,1,2) FROM CITY;
LENGTH:
Syntax: Example:
LENGTH(‘string’) SELECT LENGTH(countrycode) FROM city;
INSTR:
• Searches for a character in the given string and returns its position
Syntax:
INSTR(‘string’,’substring’,s)
Example:
SELECT INSTR(COUNTRYCODE,'F') FROM CITY;
LPAD / RPAD:
• Returns the string value left/right padded with the given pad value
Syntax:
LPAD(‘string’,n,’pad_value’)
Example:
SELECT LPAD(POPULATION,7,0) FROM CITY;
Types:
Syntax:
UPPER(‘String’ | column_name)
Number Functions
• Types
• ROUND: round off the given number (n) to the nearest integer(d) places and it is optional.
Syntax:
ROUND(n,[d])
Number Functions
Types
Syntax:
TRUNC(x,y)
Syntax:
MOD(number,divisor)
Date Functions
Aggregate Functions
• Types of group functions(Aggregate Functions)
– count
– min
– max
– avg
– sum
Aggregate Functions
Example: Employee Table
Example:
SELECT COUNT(*) AS total_employees FROM employees;
Aggregate Functions
Example: Employee Table
Example:
SELECT MIN(salary) AS minimum_salary FROM employees;
Aggregate Functions
Example: Employee Table
Example:
SELECT MAX(salary) AS maximum_salary FROM employees;
Aggregate Functions
Example: Employee Table
Example:
SELECT AVG(salary) AS average_salary FROM employees;
Aggregate Functions
Example: Employee Table
Example:
SELECT SUM(salary) AS total_salary FROM employees;
Need of Clauses
• MySQL clauses are used to provide some additional functionalities such as filtering the records,
sorting the records, fetching the records, and grouping the records .
Clauses Description
Where Filtering the records in a table
Order By sorting the records in ascending or descending order
Limit Restrict the number of rows
Group By Grouping a set of rows
Having Filtering the data like where clause
• The below table shows the order in which the clauses are used.
Where Clause
• The WHERE clause filters certain records that meet the conditions mentioned in the query.
Where Clause
• The MySQL WHERE clause is not a mandatory clause of SQL DML statements, but if you want to
limit the number of rows to be affected by your DML query or the number of rows to return from
your select statement, then you need to use the Where Clause in MySQL.
• In Example#1, return all the row from the employee table under a condition that the employee must
belong to ‘Mumbai’.
Example#1: Where with Select Query
SELECT * FROM Employee WHERE CITY = ‘MUMBAI’;
• In Example #2, the SELECT statement uses the AND condition to return all the employees from the
Employee table whose GenderID is 1 and the Salary is greater than or equal to 27000.
• In Example #3, the SELECT statement uses the OR condition to return the data that satisfy either of
any one condition.
• In this case, the SELECT statement will return all ID, Name, EmailID, and CITY column values from
the Employee table where the GenderID is 1 or the Salary is greater than 29000.
• In Example #4, the SELECT statement uses the AND & OR condition.
• The below example uses the WHERE clause to define multiple conditions, but it combines the AND
condition and the OR condition.
• In Example #5, We used Where Clause with Update Statement (DML Statement).
• In The below example we use the Where clause to update all the Employee Salary to 37000 where
the DepartmentID is 3.
• Once you execute the below query you will get the following output and notice the salary is updated to
37000 as expected.
SELECT * FROM Employee WHERE DepartmentId = 3;
Order By Clause
• The Order By Clause in MySQL is used for sorting the data either in ascending or descending
• That means if you want to sort the output or result of a query either in ascending or descending order
Syntax:
SELECT expressions FROM tables [WHERE conditions] ORDER BY expression [ASC | DESC];
Order By Clause
2.Tables: The tables from which we want to retrieve the records. There should be at least one table
specified in the FROM clause.
3.WHERE Conditions: It is optional. The conditions must be met for the records to be selected by the
query.
4.ASC: It is optional. If you want to sort the result set in ascending order of the expression, then you
need to use ASC.
5.DESC: It is optional. If you want to sort the result set in descending order by expression, then you
need to the DESC keyword.
Order By Clause
Note:
• By default, the Order By Clause in MySQL will sort the data in ascending order.
• If you want to arrange the data in descending order, then you must have to use the DESC
keyword.
• The Order By Clause can be applied to any data type column in the table.
• This clause will arrange the data temporarily but not in the permanent store.
• We are going to use the following Employee table to understand the Order By clause in MySQL
• In Example #1, We used order by Clause without specifying ASC or DEC and by default it will set ad
ASC.
• In The below example, all records are sorted by the Name field in ascending order
• In Example #2, We used ORDER BY Clause to sort the result set in descending order.
• The below MySQL ORDER BY example will return all records sorted by the Name field in the
descending order whose Gender is Male.
Example #2: ORDER BY Clause with Where and sort out in DEC
SELECT * FROM Employee WHERE Gender = ‘Male’ ORDER BY Name DESC;
• Notice, the result set has the Male employees and then sort the employees by name in
descending order.
NOTE:
If we are using where clause and order by clause in a single query, then first where clause gets executed and then
order by clause gets executed.
• In Example #3, We used the ORDER BY Clause to sort with the relative position in the result set.
• The above MySQL ORDER BY statement would return all the records sorted by the Name field in
the descending order whose Salary is greater than 26000.
• Since the Name field is in position 1 in the select clause and would be equivalent to the following
ORDERBYclause example.
• The following resultset will be returned when we execute the above query
• In Example #4, We used the ORDER BY Clause to sort with both ASC and DEC attributes in a
single SELECT statement.
• In the following query, the Order By Clause will return all records sorted by the Gender field in
descending order, with a secondary sort by Name field in ascending order whose salary is
greater than 25000.
NOTE: When we have multiple columns in order by clause, the data first gets arranged based on the first column
and if any duplicate values are there in the first column then it will take the support of the second column for the
arrangement or else the second column will not be used.
121 SQL | © SmartCliff | Internal | Version 1.0
SQL Clauses
• The following resultset will be returned when we execute the above query
Limit Clause
• The LIMIT clause in MySQL is used to restrict the number of rows returned by a query. It is often
combined with ORDER BY to fetch a specific subset of rows.
Syntax:
SELECT column1, column2, ...
FROM table_name
[WHERE condition]
[ORDER BY column_name ASC|DESC]
LIMIT [offset,] row_count;
Limit Clause
Example:
1. Fetch the first 3 employees from the Employee table
3. Fetch employees starting from the 4th row (Pagination: skip 3 rows, fetch the next 3):
Limit Clause
5. Fetch the first 2 employees from the Payroll department, ordered by their name
Group By Clause
• The Group by Clause in MySQL is used to divide similar types of records or data as a group and
then return.
• If we use group by clause in the query then we should use groupings/aggregate functions such as
• When we implement group by clause first the data of the table will be divided into the separate
group as per the column and later aggregate function will execute on each group’s data to get
the result.
Group By Clause
• That means first Group By clause is used to divide similar types of data as a group and then an
aggregate function is applied to each group to get the required results.
Syntax:
SELECT expression1, expression2, expression_n, aggregate_function (expression)
FROM tables [WHERE conditions GROUP BY expression1, expression2, expression_n;
1.expression1, expression2, expression_n: The expressions that are not encapsulated within an
aggregate function must be included in the GROUP BY clause.
2.aggregate_function: The aggregate function is nothing but such as SUM, COUNT, MIN, MAX,
or AVG functions that we should use while we are using the Group by Clause in MySQL.
Group By Clause
3. Tables: Tables are nothing but the name of the table or tables from which we want to retrieve the
data.
4. WHERE conditions: It is optional. If you want to retrieve the data based on some conditions, then
you need to specify such conditions using the Where Clause in MySQL.
• We are going to use the following Employee table to understand the Group By clause in MySQL
• In The following example we grouped the employees by department, and then we applied the count
function to each group.
Example #1: Group By with Count
SELECT Department, COUNT(*) AS TotalEmployee FROM Employee GROUP BY Department
• When we execute the above query, we will have the following output
• In The following example we find the highest salary in each department in the organization.
• When we execute the above query, we will have the following output
• In The following example we get the number of employees working in each Gender per
department.
• When we execute the above query, we will have the following output
NOTE:
• When we use multiple columns in a group by clause first data in the table is divided based on the first column of
the group by clause and then each group is subdivided based on the second column of the group by clause and
then the group function is applied on each inner group to get the result.
• When the aggregate function is applied to a group it returns only a single value but each group can return a
value.
• Use the Group By clause only on a column that contains duplicate values, never apply it on unique columns.
• In The following example we get the number of employees working in each Gender per
department.
• When we execute the above query, we will have the following output
Having Clause
• The Having Clause in MySQL is used for restricting or you can say filtering the data just like the
• So, the Having Clause in MySQL is an additional filter that is applied to the result set.
• Logically, the having clause filters the rows from the intermediate result set that is built by using
• That means it is used in combination with a GROUP BY clause to restrict the number of groups to be
returned by satisfying the condition which is specified using the having clause.
Having Clause
Syntax:
SELECT expression1, expression2, expression_n,
aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, expression_n
HAVING having_condition;
1. aggregate_function: It can be any of the aggregate functions such as SUM, COUNT, MIN, MAX, or
AVG.
Having Clause
2. expression1, expression2, expression_n: The expressions which are not encapsulated within an
3. Where Conditions: It is optional. If you want to retrieve selected records based on some conditions
then you need to specify the conditions using the Where clause in MySQL.
4. HAVING having_condition: The Having Clause Condition is used to add a further condition that can
be applied only to the aggregated results to restrict the number of groups to be returned.
• We are going to use the following Employee table to understand the Having clause in MySQL
• The Where clause in MySQL is used to filter the rows before aggregation, whereas the Having
clause in MySQL is used to filter the groups that mean after aggregations.
• The below example uses the SUM function to return the name of the department and the total Salary
• The Having Clause will filter the results so that only departments with a total Salary greater than
• The below example uses the COUNT function to return the city and the number of employees
• The Having Clause will filter the results so that only cities with more than 4 employees will be
returned.
Quiz
a) SELECT
b) ORDER BY
c) WHERE
Answer : Option c)
Quiz
a) SELECT
b) GROUP BY
c) WHERE
Answer : Option b)
Quiz
a) SELECT
b) ORDER BY
c) WHERE
Answer : Option b)
Quiz
a) ASC
b) DESC
Answer : Option a)
Quiz
Answer : Option a)