Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order a mysql query alphabetically

Tags:

php

mysql

Let's say that I have the following code:

SELECT * FROM table where company LIKE '%Auto%'

And I receive more results, and I want to have an option to sort the results alphabetically, let's say that the user wants to sort the search results for the ones which start with "C"!

Best Regards,

like image 786
Uffo Avatar asked Jan 05 '10 01:01

Uffo


People also ask

How do I make alphabetical order in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you put data in a database in alphabetical order?

If you want to select records from a table but would like to see them sorted according to a given column, you can simply use the ORDER BY clause at the end of a SELECT statement. It doesn't matter how complicated or long your SQL query is— ORDER BY should always be at the end of the command.

How do I print a list of names in alphabetical order in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


2 Answers

Well, it seems that you are talking about two different things. If you are interested in sorting you would need to use the ORDER BY clause:

SELECT * FROM table ORDER BY name

If you want to filter the results by items that start with the letter 'C' then you would want to add another LIKE clause with that letter:

SELECT * FROM table where company LIKE '%Auto%' AND name LIKE 'C%'

Additionally you'll notice that the name filter only has the % after the query. This is the syntax for "starts with"

like image 137
bendewey Avatar answered Sep 22 '22 16:09

bendewey


Use the ORDER BY clause:

SELECT *
FROM table
where company LIKE '%Auto%'
order by company
like image 40
wallyk Avatar answered Sep 21 '22 16:09

wallyk