I have the table in the following format in PostgreSQL:
Name Age Gender Occupation
John 32 Male Software Engineer
Sarah 26 Female Graphic Designer
David 41 Male Sales Manager
Emily 29 Female Marketing Coordinator
Michael 37 Male Project Manager
I would like to get all unique values from each column for the query result when also using limit. Is this achievable in postgresql?
So for example my query would be like this:
SELECT * FROM my_table
WHERE Gender = 'Male'
LIMIT 2;
I expect to get all unique values per column regardless of my limit:
Name: John, David, Michael
Age: 32, 41, 37
Occupation: Software Engineer, Sales Manager, Project Manager
Gender: Male
How can I do that using SQL?
3
Answers
You can use subqueries, to completely disregard outer where clause:
EDIT: To disregard only
LIMIT
you could use CTE.You can use the following query to get the unique values for each column with the Limit,
This query selects the distinct values for each column using subqueries with the
DISTINCT
keyword and assigns them to separate column aliases (column_1, column_2, column_3, etc.). TheLIMIT
keyword is used to specify the number of unique values to select for each column.Note
that this query assumes that all columns in the table have the same data type. If columns have different data types.Additionally, this query may not be efficient for tables with a large number of columns or a large number of distinct values.
Here it is using
string_agg
. You may use another aggregation function if more relevant.See demo.
Unrelated but it is not a good idea to keep age in a table because it keeps changing. Better have the date of birth and calculate the age using age function.