Skip to content
  • DISTINCT & Aliases · SQL

DISTINCT & Aliases

LearnViaNotes @learnvianotes· 2 min read

DISTINCT removes duplicate result rows; aliases give columns and tables short, readable names.

DISTINCT

SQL
SELECT DISTINCT category FROM products ORDER BY category;

SELECT DISTINCT city FROM customers ORDER BY city;       -- NULL counts as one value here
Output
category
-----------
Electronics
Furniture
Stationery

city
---------
NULL
Bengaluru
Delhi
Mumbai

DISTINCT applies to the whole row, not to one column:

SQL
SELECT DISTINCT customer_id, status FROM orders ORDER BY customer_id, status;
Output
customer_id | status
------------+----------
1           | delivered
1           | shipped
2           | delivered
3           | pending
3           | shipped
4           | cancelled
SQL
SELECT COUNT(DISTINCT customer_id) AS customers_who_ordered,
       COUNT(DISTINCT status)      AS statuses
FROM orders;
Output
customers_who_ordered | statuses
----------------------+---------
4                     | 4
PostgreSQL (DISTINCT ON)
-- PostgreSQL only: first row per group (by the ORDER BY)
SELECT DISTINCT ON (dept_id) dept_id, name, salary
FROM employees
ORDER BY dept_id, salary DESC;

Column aliases

SQL
SELECT name AS employee,
       salary * 12 AS "annual pay",       -- double quotes: spaces or reserved words
       hire_date joined                    -- AS is optional
FROM employees
WHERE emp_id <= 2
ORDER BY emp_id;
Output
employee | annual pay | joined
---------+------------+-----------
Asha     | 1800000    | 2015-03-01
Ravi     | 1440000    | 2017-06-15

Table aliases

SQL
SELECT e.name, d.name AS department
FROM employees AS e
JOIN departments d ON d.dept_id = e.dept_id
WHERE e.salary > 100000
ORDER BY e.emp_id;
Output
name  | department
------+------------
Asha  | Engineering
Ravi  | Engineering
Priya | Sales

What is the difference between DISTINCT and GROUP BY?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report