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 |