What Does starts_with() Function Do in PostgreSQL

There is a function provided by PostgreSQL that determines whether or not a string begins with the specified word or string. This function is known as the starts_with() function. The starts_with() function takes a string and checks whether that string starts with another specified string passed as an argument in the function.

In this blog, we will examine how the starts_with() function works.

What Does the starts_with() Function Do in PostgreSQL?

The starts_with() function checks whether the specified string starts with a string specified or not. The function takes both these strings as arguments to check and returns the boolean value depicting as result. The basic syntax of the given function is given below:

starts_with(Main_String, Prefix)

In the above syntax,

  • The first argument is the main string in which we want to check whether the prefix of this string is the same as the specifies or not.
  • The second argument is the prefix or the string that needs to be matched with the argument.

The starts_with() function returns a value having a data type of Boolean. If the main string starts with the same word specified as a prefix(the second argument), the function returns “true” and in the other case when they do not match, it will return “false”.

Let’s implement the function through examples.

Example

The below example illustrates the working of the starts_with() function:

SELECT starts_with('commandprompt.com', 'command');

In the above query:

  • The string to check the first word from is “commandprompt.com”.
  • And the prefix/string that we want to check is “command”.
  • The function has checked whether “commandprompt.com” starts with “command”, the function has returned a boolean value of true.

The output is given as:

img

If we write the query as:

SELECT starts_with('commandprompt.com', '.com');

The output will be:

img

The output is false because the string “commandprompt.com” does not start with “.com”.

This is the basic functioning of the starts_with() function and this is all about this function.

Conclusion

The starts_with() function is a simple function that gives a boolean value in return. The function checks for the prefix of the specified main string. If that prefix matches with the prefix(the second parameter) specified, the function returns a true otherwise false.