Sobes.tech
Middle

How to select only unique records from a table in SQL?

sobes.tech AI

Answer from AI

To select only unique records from a table in SQL, you can use the DISTINCT keyword.

Example:

SELECT DISTINCT column1, column2
FROM table_name;

This will return all unique combinations of values in the specified columns.

If you need to select unique rows based on one column, and other columns may differ, the task is more complex and may require the use of window functions or subqueries.

For example, to select unique records based on column1, you can use:

SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY id) as rn
  FROM table_name
) sub
WHERE rn = 1;

This selects the first record for each unique value of column1.

How to select only unique records from a table in… - sobes.tech