How to Select Rows in SQL Where a Column Contains Specific Words Baeldung on SQL (2024)

1. Introduction

In this tutorial, we’ll look at querying rows that contain given words or phrases in SQL.

We tested our examples on MS SQL Server 2022, PostgreSQL 14, and MySQL 8 databases. However, most methods we discuss should be available in other versions of these SQL implementations and other SQL dialects.

2. Problem Statement

In many SQL operations, it’s necessary to identify rows where a specific word or phrase exists within a particular column. This capability is crucial for filtering data and retrieving relevant information for the analysis.

Equality checks are not enough here, as we need to identify rows containing a specific word, even if it’s not an exact match.

3. Model

Before writing the SQL queries for this task, let’s set up the data we’ll use.

Let’s define a table for which we’ll write queries:

CREATE TABLE Product ( product_id INTEGER PRIMARY KEY, name VARCHAR(50), description VARCHAR(100));

Next, let’s insert some sample data into it:

INSERT INTO Product VALUES (1, 'RitterSport AlpenMilch', 'Milk Chocolate');INSERT INTO Product VALUES (2, 'Milka Dark Milk', 'Dark Chocolate');INSERT INTO Product VALUES (3, 'Marabou Not Choklad', 'Milk Chocolate With Nuts');INSERT INTO Product VALUES (4, 'Mentos Full Fruit', 'Sugarfree Chewing Gums');INSERT INTO Product VALUES (5, 'Lays', 'Potato Chips');INSERT INTO Product VALUES (6, 'Milka Marabou', 'Milky Darks Chocolate');

We’ll base all our examples on finding the rows that contain the terms Milk or Dark in the description column.

4. Using LIKE

We can use the LIKE operator to perform a wildcard search on the columns:

SELECT * FROM Product WHERE description LIKE '%Milk%' OR description LIKE '%Dark%';

The LIKE operator combined with % on both sides of the search terms allows for flexible searching. This means the target termscan appear anywhere within the description column, not just at the beginning or end. The LIKE operator is part of the SQL standard. It’s available in all the databases we consider in this article.

Here is the result after executing the above query:

How to Select Rows in SQL Where a Column Contains Specific Words Baeldung on SQL (1)

The query successfully retrieved the rows where the description column contains Milk or Dark.

It’s important to note that this query performs a case-sensitive search. If the data might contain variations in capitalization, we can modify the query to achieve case-insensitive searching:

SELECT * FROM Product WHERE LOWER(description) LIKE LOWER('%Milk%') OR LOWER(description) LIKE LOWER('%Dark%');

Here, we use the LOWER() function for both the column and the search term to perform a case-insensitive search.

5. Using Other Pattern Matching Operators

Apart from LIKE, which is a part of the SQL standard, different SQL dialects have different pattern-matching operators.

5.1. PostgreSQL

In PostgreSQL, we can use the ~ operator for pattern matching:

SELECT * FROM Product WHERE description ~ 'Milk' OR description ~ 'Dark'

We can use ~* instead of ~ if we want a case-insensitive search.

Similarly, ILIKE works the same as LIKE but is case-insensitive by default. It’s specific to PostgreSQL and not a part of the SQL standard.

5.2. MySQL

Additionally, we can use pattern matching using the REGEXP operator in MySQL:

SELECT * FROM Product WHERE description REGEXP 'Milk' OR description REGEXP 'Dark' 

Although these operators offer enhanced pattern-matching capabilities, their performance is generally inferior to that of the simple LIKE operator.

5.3. MS SQL

Unlike MySQL and PostgreSQL, MS SQL lacks dedicated pattern-matching operators. However, the LIKE operator in MS SQL offers limited pattern-matching capabilities, supported by regex-like operators such as [] and[^].

6. Using Built-in Functions

An alternative way to achieve this functionality is by using built-in functions specific to individual databases.

6.1. PostgreSQL and MySQL

In PostgreSQL and MySQL databases, we can use POSITION() to search for a word:

SELECT * FROM Product WHERE POSITION('Milk' IN description) > 0 OR POSITION('Dark' IN description) > 0;

The POSITION() function returns the index of the provided substring in the given column and 0 if it doesn’t exist.

Additionally, we can transform the query into a case-insensitive search by using the LOWER() function:

SELECT * FROM Product WHERE POSITION('milk' IN LOWER(description)) > 0 OR POSITION('dark' IN LOWER(description)) > 0;

6.2. MS SQL

In MS SQL, we can utilize the CHARINDEX() function to search for a substring’s position:

SELECT * FROM ProductWHERE CHARINDEX('Milk', description) > 0 OR CHARINDEX('Dark', description) > 0;

Like POSITION(), CHARINDEX() returns the 1-based index of the search substring or 0 if it isn’t in the string.

7. Comparison

Let’s check the availability of the discussed options across various databases:

Operator / FunctionPostgreSQLMySQLMS SQLCase Sensitive?Description
LIKEYesYesYesYesSimple wildcard search
LIKE with RegexNoNoYesNoSupports additional regex wildcards
ILIKEYesNoNoYesCase-insensitive LIKE
~YesNoNoYesCase-sensitive regular expression
~*YesNoNoNoRegular expression matching
REGEXPNoYesNoNoRegular expression matching
POSITIONYesYesNoYesSubstring position
CHARINDEXNoNoYesNoSubstring position

Although the LIKE operator offers search flexibility searching, the specific functions are more efficient for huge datasets as they are optimized for performance. However, built-in functions make it challenging to use generic queries across databases due to variations in syntax and functionality.

Typically, PostgreSQL is case-sensitive unless specifically configured otherwise, whereas MySQL and MS SQL Server generally support case insensitivity by default.

8. Conclusion

In this tutorial, we explored different options to filter rows that contain specific words or phrases. Combined with wildcards, the LIKE operator offers a powerful and flexible approach to pattern matching and is available in all SQL implementations. Pattern-matching operators available in each database enable advanced search operations. Furthermore, we can use database-specific functions like POSITION() and CHARINDEX() to check for the position of the target term in a string.

The scripts used in the article are available over on GitHub.

How to Select Rows in SQL Where a Column Contains Specific Words Baeldung on SQL (2024)

FAQs

How to SELECT rows containing specific text in SQL? ›

To select the row value containing string in MySQL, use the following syntax. SELECT *FROM yourTableName where yourColumnName like '%yourPattern%'; To understand the above syntax, let us first create a table.

How to SELECT rows based on condition in SQL? ›

You can specify a condition when you select rows. You specify the opposite of any condition by typing NOT before the entire condition. To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols.

How do you SELECT specific rows from a column in SQL? ›

Yes, you can select specific rows and columns in SQL using the SELECT statement. The SELECT statement is used to retrieve data from one or more tables in a database. To select specific columns, you simply list the names of the columns you want to retrieve after the SELECT keyword.

How do you SELECT specific values from a column in SQL? ›

SELECT statements

The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value'; In the above SQL statement: The SELECT clause specifies one or more columns to be retrieved; to specify multiple columns, use a comma and a space between column names.

How to SELECT specific words in SQL? ›

Approach 1: Using LIKE Operator with Wildcards

The LIKE operator is used to match pattern within a field. The '%' wildcard represents any sequence of characters, which help us to search for a specific word in the field.

How do I extract a specific text from a column in SQL? ›

SUBSTRING() is a function that enables us to extract subparts of strings, which are known as substrings. The strings we want to extract from can be specified in the function itself, or they can be a part of a table's columns. Using this function, we can extract as many substrings as we want from a single string.

How do I SELECT rows with specific values? ›

Select Rows That Contain Specific Values
  1. Select Rows > Row Selection > Select Where. ...
  2. From the column list, highlight the name of the column whose rows you want to select.
  3. Use the drop-down menu to select a condition from the list (equals, does not equal, and so on). ...
  4. Type the search value.
  5. Click OK.
May 14, 2024

How do I SELECT rows based on multiple conditions? ›

To filter rows based on multiple conditions, we can create a boolean mask with the & and | operators, and use it to select the desired rows. This code creates a boolean mask with two conditions, and uses it to select all rows where both conditions are true.

How do I SELECT a specific range of rows in SQL? ›

The BETWEEN operator in SQL is a logical operator used for selecting values within a particular range. This operator is typically used with the WHERE clause to filter out records based on specific criteria. The range specified by the BETWEEN operator includes the endpoints.

How do I SELECT a substring from a column in SQL? ›

MySQL SUBSTRING() Function

The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The position of the first character in the string is 1. Note: The position of the last character in the string is -1. Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.

How to use rownum in SQL query? ›

However, in some database systems like Oracle, Rownum is a pseudocolumn that can be used to limit the number of rows returned in a query. Rownum 1 is often used to retrieve only the first row from a result set. For example, "SELECT * FROM table WHERE ROWNUM = 1" would return the first row of the table.

How can I get distinct values for a particular column in SQL? ›

The DISTINCT keyword is used in SQL to eliminate duplicate values from the result set of a SELECT statement. When used, it only returns unique, distinct values. For example, if a table contains multiple rows with the same value in a certain column, the DISTINCT keyword will only return a single row with that value.

How to find specific data in SQL database? ›

Search object in all online SQL databases

On the home page of the object explorer, enter the object name and search. In the result below, you see that a specified object exists in multiple databases. You can browse to the specified object in the database using the object explorer.

How do I reference a specific column in SQL? ›

You use column-ref to reference a column (database field), optionally qualified by a table and/or schema name. The column reference comprises the data type of the database field that the column represents (see Data Types).

How do you get a specific substring from a string in SQL? ›

MySQL SUBSTR() Function

The SUBSTR() function extracts a substring from a string (starting at any position). Note: The position of the first character in the string is 1. Note: The position of the last character in the string is -1. Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.

What is like %% in SQL? ›

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign % represents zero, one, or multiple characters.

How do I find a specific text string in SQL Server? ›

CHARINDEX() and PATINDEX() are the functions with which you can search for a substring in a string inside SQL Server. PATINDEX() is more powerful because it lets you use regular expressions.

Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 5591

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.