Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the field as Distinct having data type as Text. Sql Server

Is their any way to select a field as Distinct whose data type is Text.

If we have a table T1 with a field named Subjects have data type as Text.

Subjects
--------
Room
--------
Room
--------
window
--------
Door
--------
Door
--------

If I try this query

Select Distinct (Subjects)
from T1

It gives me this error:

The text data type can not be selected as DISTINCT because it is not comparable

When I use Group by it give me this error:

The data types 'text', 'ntext' and 'image' can be compared or sorted, 
except when using IS NULL or LIKE operator.

Is there any solution ? Thanks

like image 396
Kamran Avatar asked Dec 10 '13 12:12

Kamran


People also ask

Can I use distinct * in SQL?

The SQL SELECT DISTINCT StatementThe SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Can we use distinct in case statement?

This tutorial explains how to ignore duplicates while specifying conditions / criteria in SQL queries. You must have used DISTINCT keyword to remove duplicates. It is frequently used with COUNT function to calculate number of unique cases.

How do you SELECT distinct data?

The distinct keyword is used with select keyword in conjunction. It is helpful when we avoid duplicate values present in the specific columns/tables. The unique values are fetched when we use the distinct keyword. SELECT DISTINCT returns only distinct (different) values.

Can we use unique instead of distinct in SQL?

The UNIQUE keyword in SQL plays the role of a database constraint; it ensures there are no duplicate values stored in a particular column or a set of columns. On the other hand, the DISTINCT keyword is used in the SELECT statement to fetch distinct rows from a table.


1 Answers

You can use:

SELECT DISTINCT CONVERT(varchar(max), text_column) ...

Or for less memory usage, if you're happy with the first x bytes (say, 900):

SELECT DISTINCT LEFT(text_column, 900) ...

While the cast/convert answers work, and while it's questionable to want to perform a distinct operation on data this large in the first place, the real fix is to stop using the TEXT data type. It has been deprecated since 2005. You should be using VARCHAR(MAX) instead, for a whole variety of reasons.

like image 162
Aaron Bertrand Avatar answered Sep 24 '22 02:09

Aaron Bertrand