1
$\begingroup$

How should I sort my SELECT ?

EXAMPLE LIST

1, 2, 2A, 4, 10, 10A

SQL

$query = "SELECT * FROM table WHERE column1 = '$var' ORDER BY length(column2), column2";

If I ORDER BY length() like my example, 2A will end up in the bottom.
If I remove length(), 10 comes after 1.

How do I sort so it appears as above?

$\endgroup$
1

3 Answers 3

0
$\begingroup$

Like this:

$query = "SELECT * FROM table WHERE column1 = '$var' ORDER BY CAST(column2 as UNSIGNED), column2";
$\endgroup$
Sign up to request clarification or add additional context in comments.

2 Comments

Works like a charm. Thank you!
I'm glad I could help.
0
$\begingroup$

order by hex is best way to do this:

$query = "SELECT *, cast(hex(column2 as unsigned) as l FROM table WHERE column1 = '$var' ORDER BY l";

$\endgroup$

Comments

0
$\begingroup$

With a custom function such as alphas found here, you can order it by first the number portion of the value followed by the string portion of the value.

If you define and populate a table as such:

CREATE TABLE test (t VARCHAR(255));
INSERT INTO test VALUES
  ('10A'),
  ('2'),
  ('2A'),
  ('4'),
  ('10'),
  ('1');

Then create a custom function called alphas which extracts the string portion (no numbers):

DELIMITER |
DROP FUNCTION IF EXISTS alphas; 
CREATE FUNCTION alphas( str CHAR(32) ) RETURNS CHAR(16) 
BEGIN 
  DECLARE i, len SMALLINT DEFAULT 1; 
  DECLARE ret CHAR(32) DEFAULT ''; 
  DECLARE c CHAR(1); 
  SET len = CHAR_LENGTH( str ); 
  REPEAT 
    BEGIN 
      SET c = MID( str, i, 1 ); 
      IF c REGEXP '[[:alpha:]]' THEN 
        SET ret=CONCAT(ret,c); 
      END IF; 
      SET i = i + 1; 
    END; 
  UNTIL i > len END REPEAT; 
  RETURN ret; 
END | 
DELIMITER ;

Then you can do a ordered query like this:

SELECT t FROM test ORDER BY CAST(t AS UNSIGNED), alphas(t);

The CAST function converts strings like 10A to an unsigned number of 10.

$\endgroup$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.