DISTINCT removes duplicate result rows; aliases give columns and tables short, readable names.
DISTINCT
SELECT DISTINCT category FROM products ORDER BY category;
SELECT DISTINCT city FROM customers ORDER BY city; -- NULL counts as one value herecategory
-----------
Electronics
Furniture
Stationery
city
---------
NULL
Bengaluru
Delhi
MumbaiDISTINCT applies to the whole row, not to one column:
SELECT DISTINCT customer_id, status FROM orders ORDER BY customer_id, status;customer_id | status
------------+----------
1 | delivered
1 | shipped
2 | delivered
3 | pending
3 | shipped
4 | cancelledSELECT COUNT(DISTINCT customer_id) AS customers_who_ordered,
COUNT(DISTINCT status) AS statuses
FROM orders;customers_who_ordered | statuses
----------------------+---------
4 | 4-- 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
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;employee | annual pay | joined
---------+------------+-----------
Asha | 1800000 | 2015-03-01
Ravi | 1440000 | 2017-06-15Table aliases
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;name | department
------+------------
Asha | Engineering
Ravi | Engineering
Priya | SalesWhat is the difference between DISTINCT and GROUP BY?