Helix Systems' HR system compiles a list of vice-president-level roles.
Write a query to return the ID and name of every employee whose title begins with VP.
Assumptions:
- The
employeestable has one row per employee with anid, aname, and atitle. - A qualifying employee has a
titlethat starts with the literal charactersVPat the very first position. Titles whereVPappears later in the string do not qualify.
Output:
- One row per qualifying employee, with columns
idandname.
Schema · hr 4 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
name
FROM
employees
WHERE
title ~ '^VP' The shape
The caret in ^VP anchors the regex at position 1 of the string. The pattern matches only when the title begins with the literal characters VP. Without the anchor, the unanchored regex VP would also catch a title like Senior VP or VP-elect, which is not what the report wants.
Clause by clause
SELECT id, namereturns the employee ID and name for the leadership roster.FROM employeesreads the employee table.WHERE title ~ '^VP'keeps rows where the title starts withVP. The^is a position anchor, not a character; it does not consume any of the string. It asserts that the next characters in the pattern must appear at the very beginning.VPthen matches the literal two charactersVandP.
Why this and not LIKE 'VP%'
LIKE 'VP%' returns the same rows and is the more idiomatic spelling for a fixed prefix match. The regex form is shown here because the node is teaching regex anchors, and ^prefix is the regex equivalent of LIKE 'prefix%'. On a large table with a B-tree index, LIKE 'VP%' can use the index; the regex form generally cannot. For a real prefix-only filter, LIKE is usually the right call. For a more complex pattern that also needs to start at the beginning, the ^ anchor is how you say so.
The trap
The ^ must come first in the pattern. Writing 'V^P' is not "starts with V then P"; it matches a literal caret between V and P, which appears nowhere in the data. The anchor is a position assertion, and position-1 only exists at the very start of the pattern. Same rule for $ at the end.
You practiced ~ '^pattern' — anchor a regex at the start of the string so only matches at position 1 qualify.