Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
How to Alter Multiple Columns at Once in SQL Server?
Next article icon

How to SELECT DISTINCT on Multiple Columns in SQL Server?

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with SQL Server, there are scenarios where we might need to retrieve unique combinations of values from multiple columns. This is where the SELECT DISTINCT statement comes in handy. It allows us to eliminate duplicate rows from the result set.

However, using SELECT DISTINCT it on multiple columns requires a slightly different approach compared to using it on a single column. In this article, we'll explore how to use SELECT DISTINCT on multiple columns in SQL Server by understanding various examples and so on.

What is the DISTINCT Keyword?

The DISTINCT keyword is used in SQL queries to filter out duplicate rows in the result set. When the Distinct operator is used with a single column, it makes sure that columns only contain unique values, however, in scenarios where uniqueness is defined by combinations of multiple columns, a more complex method is needed.

The syntax for Selecting Distinct Rows on Multiple Columns:

To select distinct rows based on multiple columns in SQL Server, we need to specify all the columns whose combinations should be unique.

The syntax for such a query is defined below:

SELECT DISTINCT column1, column2, ...
FROM table_name;

Let's set up an environment

Let's create an example table called products and insert some data into it including duplicate values. Below are the examples of using SELECT DISTINCT on multiple columns in SQL Server with the provided products table:

Create Table:

CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
category VARCHAR(50),
unit_price DECIMAL(10, 2),
stock_quantity INT
);

Insert Data:

INSERT INTO products VALUES
(1, 'Laptop', 'Electronics', 1200.00, 50),
(2, 'Smartphone', 'Electronics', 800.00, 100),
(3, 'Coffee Maker', 'Appliances', 50.00, 30),
(4, 'Backpack', 'Fashion', 40.00, 80),
(5, 'Desk Chair', 'Furniture', 150.00, 20),
(6, 'Laptop', 'Electronics', 1200.00, 50),
(7, 'Coffee Maker', 'Appliances', 50.00, 30);

Output:

productsITable
Products Table

Examples of How to SELECT DISTINCT on multiple columns in SQL Server

Example 1: Select the Unique Combinations of product_name and category.

SELECT DISTINCT product_name, category
FROM products;

Output:

product_name-and-category
Unique Combinations of product_name and category

Explanation:

  • SELECT DISTINCT: It tells the database to give only the unique values from the specified columns in the result set and not the repeated ones. Redundancy rows are cleaned up to make sure that each row in the output is unique.
  • product_name, category: The query requests distinct combinations of values from these columns.
  • FROM products: Specifies the table from which the data will be retrieved.

Example 2: Select the Unique Combinations of category and unit_price.

SELECT DISTINCT category, unit_price
FROM products;

Output:

category-and-unit_price
Unique Combinations of category and unit_price


Explanation:

  • SELECT DISTINCT: It tells the database to give only the unique values from the specified columns in the result set and not the repeated ones. Redundancy rows are cleaned up to make sure that each row in the output is unique.
  • category, unit_price: The query requests distinct combinations of values from these columns.
  • FROM products: Specifies the table from which the data will be retrieved. This query will return distinct combinations of category and unit_price from the products table.

Example 3: Select the Unique Combinations of category, unit_price, and stock_quantity.

SELECT DISTINCT category, unit_price, stock_quantity
FROM products;

Output:

category-unit_price-and-stock_
Unique Combinations of category, unit_price, and stock_quantity

Explanation:

  • SELECT DISTINCT: It tells the database to give only the unique values from the specified columns in the result set and not the repeated ones. Redundancy rows are cleaned up to make sure that each row in the output is unique.
  • category, unit_price, stock_quantity: The query requests distinct combinations of values from these columns.
  • FROM products: Specifies the table from which the data will be retrieved.

Conclusion

Overall, Using SELECT DISTINCT on multiple columns in SQL Server allows you to retrieve unique combinations of values from those columns. It's a powerful tool for eliminating duplicate rows from your result set and ensuring that you only get the data you need. By understanding how to use SELECT DISTINCT on multiple columns, you can enhance the efficiency and accuracy of your SQL queries in SQL Server.


Next Article
How to Alter Multiple Columns at Once in SQL Server?

M

minalpandey6899
Improve
Article Tags :
  • SQL Server
  • Databases
  • SQL Server Query

Similar Reads

  • How to SELECT DISTINCT on Multiple Columns in SQL?
    In the world of databases, data duplication can lead to confusion and inefficiency. SQL provides a powerful tool, SELECT DISTINCT, to retrieve unique values from columns. However, when dealing with multiple columns, the approach becomes more detailed. In this article, we will explain how to use SELE
    4 min read
  • How to SELECT DISTINCT on Multiple Columns in SQLite?
    SQLite is a lightweight and server-less relational database management system (R.D.B.M.S). It is a self-contained database and requires very minimal configuration. It is a server-less architecture that is good for mobile applications and simple desktop applications. In this article, we are going to
    4 min read
  • How to Alter Multiple Columns at Once in SQL Server?
    In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database an
    3 min read
  • How to Find the Maximum of Multiple Columns in SQL Server?
    When working with SQL Server databases, there are times when we need to find the maximum value among multiple columns. This task can be accomplished using various techniques within SQL queries. By using functions like CASE and GREATEST, SQL Server provides efficient ways to determine the maximum val
    4 min read
  • Selecting Multiple Columns Based On Condition in SQL
    SQL (Structured Query Language) is used to manage and query databases. One common requirement when querying data is selecting multiple columns based on specific conditions. Understanding how to use SQL for this purpose can enhance your ability to retrieve relevant data efficiently. In this article,
    4 min read
  • How to find distinct values of multiple columns in PySpark ?
    In this article, we will discuss how to find distinct values of multiple columns in PySpark dataframe. Let's create a sample dataframe for demonstration: [GFGTABS] Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creati
    2 min read
  • How to Concatenate Text From Multiple Rows in SQL Server
    When we fetch data from a table, there may be requirements to concatenate the text value of a table column in multiple rows into a single row. There are many ways we can concatenate multiple rows into single row SQL Server. We can use different ways based on need and convenience. In this article, we
    6 min read
  • How to Find the Maximum of Multiple Columns in PostgreSQL?
    PostgreSQL is one of the most advanced general-purpose object-relational database management systems and is open-source. Being an open-source software, its source code is available under PostgreSQL license, a liberal open-source license. Anyone with the right skills is free to use, modify, and distr
    4 min read
  • How to Find the Maximum of Multiple Columns in SQL
    Finding the maximum value of multiple columns is one of the most common analytical tasks essential for making decisions and analyzing data. Using the MAX() function of SQL, users can find the maximum value in a single column. But to find the maximum value in multiple columns, users need to use other
    2 min read
  • How to Get Multiple Counts With Single Query in SQL Server
    In SQL Server, obtaining multiple counts with a single query is a common requirement, especially when we are analyzing data across different conditions. Whether we are tallying the number of active and inactive users or counting orders based on their status by using a single query can speed our data
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences