How to implement template file that would reside in database? I was wondering if it would be possible to have a template "file" that would be stored only in DB and would not exist physically?

Twig tempaltes are parsed from files only once and they are processed and stored in DB anyway so would it be possible to have such DB entry from the get-go?
You can register a loader, see Drupal\Core\Template\Loader for the implementations that drupal core uses and their parent classes/interfaces.

See also how they're registered in core.services.yml, for example:

twig.loader.filesystem:
    class: Drupal\Core\Template\Loader\FilesystemLoader
    arguments: ['@app.root', '@module_handler', '@theme_handler']
    tags:
      - { name: twig.loader, priority: 100 }


So, it's certainly possible to do it, if it's a good idea is another question ;)