[Tex/LaTex] Underline in lstlisting environment

listings

I would like to get the same result I get with \underline in a lstlisting environment.

I was almost sure I got it in this way:

\documentclass{article}

\usepackage{listings}
\usepackage{upquote}

\lstdefinestyle{myStyle}{
  language=SQL,
  basicstyle=\small\ttfamily,
  moredelim=[is][\underbar]{_}{_},
  keepspaces=true
}

\begin{document}

\begin{lstlisting}[style=myStyle]
SELECT * FROM usr WHERE _id = 7_
\end{lstlisting}

\end{document}

but when I use the _ delimiter between '' it doesn't work:

\documentclass{article}

\usepackage{listings}
\usepackage{upquote}

\lstdefinestyle{myStyle}{
  language=SQL,
  basicstyle=\small\ttfamily,
  moredelim=[is][\underbar]{_}{_},
  keepspaces=true
}

\begin{document}

\begin{lstlisting}[style=myStyle]
SELECT * FROM usr WHERE id ='_7_'
\end{lstlisting}

\end{document}

result

How can I solve this problem?

Best Answer

There might be easier approaches, but since lstlisting is a verbatim environment, \underline does not work this way (as any other command would fail too). It's necessary to escape to LaTeX with a user defined escapechar, I chose % for this

\documentclass{article}

\usepackage{listings}
\usepackage{upquote}

\lstdefinestyle{myStyle}{
  language=SQL,
  basicstyle=\small\ttfamily,
  moredelim=[is][\underbar]{_}{_},
  keepspaces=true
}

\begin{document}

\begin{lstlisting}[style=myStyle,escapechar=\%]
SELECT * FROM usr WHERE %\underline{id} = \underline{7}%
\end{lstlisting}

\end{document}

enter image description here