Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the DISTINCT first character of a field (MySQL)

Tags:

I would like to produce a character list of all of the first letters of column in my database. The SQL below illistrats what I would like to return.

 SELECT DISTINCT first_character(name) FROM mydatabase 

Is there a way to do this in MySQL?

EDIT What is the advantage of using SUBSTRING over LEFT and vice versa?

EDIT Currently there are about 1700 records in the table and growing.

like image 245
chadgh Avatar asked May 07 '09 21:05

chadgh


People also ask

Does distinct return the first row?

Bare usage of DISTINCT will return the first occurrence. However, it can work either way by sorting the initial results first before conducting the distinction step.

How do I SELECT distinct data in MySQL?

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.

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.


2 Answers

Sorry to do this, but I figured out exactly what I needed to do just now.

 SELECT DISTINCT LEFT(name, 1) FROM mydatabase 

This returned a list of the first, distinct, single characters that each row in the column started with. I added changed it to the following to get it the list in alpha-numeric order:

 SELECT DISTINCT LEFT(name, 1) as letter FROM mydatabase ORDER BY letter 

Works like a charm.

like image 98
chadgh Avatar answered Nov 07 '22 19:11

chadgh


Sounds simple:

select distinct substring(field,1,1) as char from mytable 
like image 20
Andomar Avatar answered Nov 07 '22 20:11

Andomar