
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select Records with Active Status in MySQL Using ENUM
MySQL's ENUM data type is used to define a specific set of values in a column making it easier to manage and maintain data consistency.
GROUP BY and WHERE() function
In MySQL WHERE clause is used to filter the rows based on a condition before grouping them. The GROUP BY clause groups rows with identical values in specified columns, and can be used with functions like SUM, COUNT, and AVG. Together they enable focused data analysis by filtering and grouping efficiently.
Syntax
Following is the syntax to filter the data on certain conditions and to eliminate duplicate records.
SELECT column1, column2, ... FROM table_name WHERE condition GROUP BY column_name;
Example
In the below example we use GROUPBY() and WHERE() functions to filter and select the records with Active status.
Creating TableTo understand the above syntax let us first create a table. where, we set the Status column using ENUM restricted to ('Active', 'Inactive') ?
CREATE TABLE DemoTable ( StudentId int, Status enum('Active','Inactive') );Inserting Records
Let's populate the table with sample data. To do this we need to use INSERT command ?
INSERT INTO DemoTable (StudentId, Status) VALUES (99, 'Active'), (99, 'Inactive'), (100, 'Inactive'), (99, 'Active'), (100, 'Inactive'), (101, 'Active'), (101, 'Active');View the data
Display all records from the table using SELECT statement ?
SELECT * FROM DemoTable;
Following is the output of the above query ?
StudentId | Status |
---|---|
99 | Active |
99 | Inactive |
100 | Inactive |
99 | Active |
100 | Inactive |
101 | Active |
101 | Active |
This displays all records in the table along with duplicates.
Selecting data with 'Active' statusTo filter records with the Active status, we use a WHERE clause. Additionally, the GROUP BY clause ensures distinct records for each StudentId.
SELECT StudentId,Status FROM DemoTable2037 where Status='Active' GROUP BY StudentId;
Following is the output of the above query ?
StudentId | Status |
---|---|
99 | Active |
101 | Active |
From the above output, we can say that the query selects records with the Active status and groups them by StudentId, eliminating duplicate rows.
Conclusion
ENUM column restricts inputs to predefined values, ensuring data consistency.
The WHERE clause filter rows based on specific ENUM values.
Using GROUP BY ensures unique records in the result set.