Write a query to fetch unique department names from the departments table.
Objective
Write a query to fetch unique department names from a table named departments
.
Step 1: Create departments
Table
We’ll first create the table to hold department data:
CREATE TABLE departments (
id INT PRIMARY KEY,
department_name VARCHAR(100)
);
Step 2: Insert Dummy Data (with duplicates)
Let’s insert some sample data into the table. We’ll intentionally include duplicate department names:
INSERT INTO departments (id, department_name) VALUES
(1, 'HR'),
(2, 'Engineering'),
(3, 'Sales'),
(4, 'HR'),
(5, 'Engineering'),
(6, 'Marketing'),
(7, 'Finance');
Step 3: SQL Query to Fetch Unique Department Names
Now we want to fetch distinct (unique) department names. Here's the query:
SELECT DISTINCT department_name FROM departments;
Output
department_name |
---|
HR |
Engineering |
Sales |
Marketing |
Finance |
The DISTINCT
keyword ensures that only unique values are returned — no duplicates.
Summary
Step | Description |
---|---|
1. | Created departments table |
2. | Inserted dummy data (with duplicates) |
3. | Used SELECT DISTINCT to get unique names |
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.