Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DISTINCT clause in SQLite

Tags:

sqlite

Recently i found that SQLite don't support DISTINCT ON() clause that seems postgresql-specific. For exeample, if i have table t with columns a and b. And i want to select all items with distinct b. Is the following query the only one and correct way to do so in SQLite?

select * from t where b in (select distinct b from t)

Sample data:

a | b
__|__
1   5
2   5
3   6
4   6

What i expect in return:

a | b
__|__
1   5
3   6
like image 962
grigoryvp Avatar asked Jun 14 '10 15:06

grigoryvp


People also ask

What is the use of distinct clause in SQLite?

SQLite DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only the unique records.

What is the syntax of SQLite distinct clause?

SQLite DISTINCT Clause It is used when you have multiple duplicate records in the table. Syntax: SELECT DISTINCT column1, column2,..... columnN.

Why do we use distinct clause?

SQL DISTINCT clause is used to remove the duplicates columns from the result set.

How can I get unique values from a column in SQLite?

If we define DISTINCT for one column in SQLite select statement then the DISTINCT clause will return unique values only for that column. In case if we use DISTINCT for multiple columns in SQLite SELECT statement then DISTINCT will use a combination of those columns to evaluate the duplicate values.


2 Answers

sqlite> SELECT * FROM t GROUP BY b;
2|5
4|6
(for each b: one (unpredictable) value of a)

sqlite> SELECT * FROM (SELECT * FROM t ORDER BY a DESC) GROUP BY b;
1|5
3|6
(for each b: the row with min a)

sqlite> SELECT * FROM (SELECT * FROM t ORDER BY a ASC) GROUP BY b;
2|5
4|6
(for each b: the row with max a)
like image 191
Solimo Avatar answered Nov 11 '22 21:11

Solimo


Use:

  SELECT MIN(t.a) AS A,
         t.b
    FROM TABLE t
GROUP BY t.b
like image 20
OMG Ponies Avatar answered Nov 11 '22 20:11

OMG Ponies