3

I have the below content inside a table in SQL

enter image description here

I tried to order by title but I didn't work, is there any SQL statement to use so I can order by the number inside InterSciences Competition?

4
  • do substring of the number part and use in order Commented Jun 12, 2019 at 6:37
  • You need to extract the integer part. Commented Jun 12, 2019 at 6:37
  • how can I do that? Commented Jun 12, 2019 at 6:39
  • What should happen if there's no number inside the parenthesis? Or if the there are two records with the same number but different text? Commented Jun 12, 2019 at 7:44

3 Answers 3

4

You can try like following query.

;WITH cte 
     AS (SELECT title, 
                Cast(Substring(title, Charindex('(', title) + 1, 
                     Charindex(')', title) - 
                     Charindex('(', title) - 1) 
                     AS INT) AS OC 
         FROM   yourtable) 
SELECT * 
FROM   cte 
ORDER  BY oc 

In above query, the number between brackets is extracted and converted to INT for ordering.

Online Demo

Sign up to request clarification or add additional context in comments.

2 Comments

or you can just use that on order by clause. ORDER BY Cast(Substring(title, Charindex('(', title) + 1, Charindex(')', title) - Charindex('(', title) - 1) AS INT)
@hims056 haha, now I see the query you wrote, I did the same thing.
2

Using SUBSTRING() and PATINDEX(), this ordering is possible:

DECLARE @TestTable TABLE (TestVal VARCHAR (20));
INSERT INTO @TestTable (TestVal) VALUES ('Test (1)'), ('Test (10)'), ('Test (2)');

SELECT TestVal 
FROM @TestTable 
ORDER BY CAST(SUBSTRING(TestVal, PATINDEX('%[0-9]%', TestVal), LEN(TestVal) - PATINDEX('%[0-9]%', TestVal)) AS INT),
         LEFT(TestVal, PATINDEX('%[0-9]%', TestVal) - 2)

Output:

TestVal
---------
Test (1)
Test (2)
Test (10)

Demo on db<>fiddle

Comments

1

You can also try this:

declare @t table (title varchar(50))

insert into @t values ('InterSciences Competition (1)')
insert into @t values ('InterSciences Competition (10)')
insert into @t values ('InterSciences Competition (2)')


select * from @t
order by cast(replace(substring(title,CHARINDEX('(',title)+1,CHARINDEX(')',title)),')','') as INT) 

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.