Reusing sql query values for another query in single request I have an sql table for some chats with a table messages, containing  id int pk, chat_id int, created_at timestamp.  

Given a message id, is it possible to select it, along with 5 messages after it in same chat, in single query?

Or can I somehow combine the two following subqueries (having starting_message_id as an input)?

SELECT * FROM messages WHERE chat_id IN (
    SELECT chat_id from messages where id='starting_message_id'
) AND created_at &gt; (
    SELECT created_at from messages where id='starting_message_id'
) ORDER BY created_at ASC LIMIT 5;


I feel that only two requests are sufficient: 


selecting chat_id and created_at columns by chat id
selecting some messages having all data known


What would the correct optimised syntax be?
I believe you want something like:

SELECT msg.* 
FROM messages msg
JOIN (SELECT chat_id, created_at
  FROM messages
  where id='starting_message_id') nested
ON (msg.chat_id=nested.chat_id and msg.created_at&gt;=nested.created_at)
ORDER BY msg.created_at
LIMIT 6;