Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL startswith (using `LIKE`) on an expression

Tags:

What's an appropriate way to do startswith(expression) in SQL?

I can do it with LIKE ((expression) || '%'), but it doesn't look very nice to me.

Full query is in form:

SELECT …, (SELECT COUNT(*)             FROM post AS child             WHERE child.path LIKE (post.path || '%')            AND child.depth >= post.depth) FROM post WHERE … 

I suppose it is preferable to use LIKE because of DB indexing for this case.

like image 776
HoverHell Avatar asked Feb 28 '11 17:02

HoverHell


Video Answer


2 Answers

Just use LIKE 'input%'. I.E:

WHERE child.path LIKE post.path + '%' 

(I assume this is for SQL Server, though this syntax probably works elsewhere)

like image 69
Scott Anderson Avatar answered Oct 02 '22 01:10

Scott Anderson


In standard SQL, you can also say:

where position(post.path in child.path) = 1 

I don't know if your RDBMS supports that. PostgreSQL does.

like image 35
Tom Anderson Avatar answered Oct 02 '22 01:10

Tom Anderson