Search code examples
pythonsqlsqlitesubstringsql-max

How to join two queries to make a subquery


I have a first query that give me a set of values and a second query that give me the maximum of this set of value. I want to merge these two queries. I tried like this below:

First query:

SELECT SUBSTR(column, INSTR(column, ' ')+1,3)  
from table  
WHERE column LIKE '#13 %'

Second query:

SELECT MAX(column)

The merge:

SELECT MAX(column) 
FROM table WHERE column = (
  SELECT  SUBSTR(column, INSTR(column, ' ')+1,3)  
  from table  
  WHERE column LIKE '#13 %'
)

Can you please help how can I merge two queries?

First query result:

30
1
2
3
12
13
14
15
16
17
18
19

I want to have the maximum value of this set of values with my second query: 30.


Solution

  • The result of SUBSTR(column, INSTR(column, ' ') + 1, 3) is a string, so you must cast it to a number and this can be done simply by adding 0.
    Then use MAX() aggregate function:

    SELECT MAX(SUBSTR(column, INSTR(column, ' ') + 1, 3) + 0)  
    FROM tablename  
    WHERE column LIKE '#13 %';
    

    Since you have the condition column LIKE '#13 %' in the WHERE clause, then you know that the 1st space in the column is at position 4, so you could simplify to:

    SELECT MAX(SUBSTR(column, 5, 3) + 0)  
    FROM tablename  
    WHERE column LIKE '#13 %';