Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL - Sort by first letter

Tags:

mysql

i have this sql query (below) and it works great but i need to modify it to select only records with $a first character. I've tried a few variations of the LIKE A% with no luck. The crux of my situation seems to be the name alias. If i use WHERE name LIKE 'A%' before the ORDER i get an error. That seems like the logical place for it to be. Any suggestions?

SELECT  
  IF(company_name <> '', company_name, PC_last_name) AS name, 
  customer_id AS id, 
  company_name AS cn, 
  PC_first_name AS pcf, 
  PC_last_name AS pcl, 
  primary_phone 
FROM sales_customer 
ORDER BY name
like image 789
Lawrence Gadette Avatar asked Feb 16 '26 13:02

Lawrence Gadette


2 Answers

Try this, it get's the first letter from the name.

SELECT IF(company_name <> '', company_name, PC_last_name) AS name, customer_id AS id, company_name AS cn, PC_first_name AS pcf, PC_last_name AS pcl, primary_phone
FROM sales_customer
ORDER BY SUBSTRING(name, 1, 1) ASC
like image 80
blaff Avatar answered Feb 18 '26 03:02

blaff


I think you can't use the alias for this comparison on WHERE. Try this:

SELECT  
  IF(company_name <> '', company_name, PC_last_name) AS name, 
  customer_id AS id, 
  company_name AS cn, 
  PC_first_name AS pcf, 
  PC_last_name AS pcl, 
  primary_phone 
FROM sales_customer 
WHERE IF(company_name <> '', company_name, PC_last_name) LIKE 'A%'
ORDER BY name
like image 31
bfavaretto Avatar answered Feb 18 '26 04:02

bfavaretto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!