The Wayback Machine - https://web.archive.org/web/20240920083118/https://www.geeksforgeeks.org/sql-select-where-field-contains-words/
Open In App

SQL SELECT WHERE Field Contains Words

Last Updated : 12 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The SQL SELECT WHERE field Contains Words” in SQL is used to find data with specific words in it. It helps us to find patterns in text fields. One more way to do this is by using full-text search, which searches entire blocks of text to find what we need.

In simple words, we can say SQL gives us ways to find data based on words or phrases in fields which makes it easier to get the required information.

SQL SELECT WHERE Clause

Using the SELECT WHERE clause, we can filter a query based on certain conditions. For example, if we want to filter records by word matches, we use the LIKE operator and wildcard characters.

Syntax:

SELECT column1, column2, …

FROM table_name

WHERE condition;

Explanation: This query is used for searching data where the condition is true in a mentioned column of a table.

‘LIKE’ operator

The ‘LIKE’ operator is commonly used for matching patterns in SQL queries. We can use ‘%’ as a wildcard to represent any sequence of characters.

Syntax:

SELECT column1, column2, …FROM table_nameWHERE column_name LIKE ‘%word%’;

The ‘%word%’ will match any value that contains the word ‘word’ and the ‘%’ before and after makes sure that the mentioned word can occur at any position(beginning, middle or end).

Example of SQL SELECT WHERE Field Contains Words

To search for a record that contains a specific word in a specific field, we will use SELECT statement in SQL with WHERE clause to filter the results based on a specific word.

Consider a table named products with columns product_id and product_name. We want to select products where the product name contains the word “chair“.

Query:

CREATE TABLE products (
product_id INT,
product_name VARCHAR(100)
);


INSERT INTO products (product_id, product_name) VALUES
(1, 'Office Chair'),
(2, 'Dining Chair'),
(3, 'Desk Lamp'),
(4, 'Armchair');
SELECT * FROM PRODUCTS;

Output:

sql_table_for_products

The table created using create command in sql

We search for the word ‘chair using 2 approaches, discussed below:

  • Using LIKE Operator with wildcards
  • Using Full taxt search (MATCH .. .AGAINST)

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.

Syntax:

SELECT * FROM your_table_name WHERE your_column_name LIKE ‘%your_word%’;

Example

Using LIKE Operator to with SELECT WHERE to find the words present in a specific colum.

Step 1: Basic SQL SELECT statement without any conditions.

SELECT * FROM products;

Output:

sql_table_for_products

product table

Step 2: SQL SELECT statement using the LIKE operator to filter rows where the product name contains the word “chair”.

SELECT * FROM products WHERE product_name LIKE '%chair%';

Output:

sql-output

sql select where field contains words

Explanation:

The query retrieves all records from the “products” table where the “product_name” contains the word “chair.” The output includes all rows with product names that have “chair” as a substring, providing a filtered result set.

Approach 2: Using Full-Text Search

Full-text is an advanced way to search text in table. First we will create a full-text index on column(s) we want to search then we will use MATCH AGAINST keyword to search the data.

A full-text index is a special type of index that help us for efficient searching of text-based data. By creating a full-text index on a column, we enable the database to perform fast text searches on that column.

The MATCH(your_column_name) clause indicates that we are performing a full-text search on the specified column. The AGAINST (‘your_word’) clause specifies the search term or terms to match against. In this case, it’s your_word.

When we use MATCH AGAINST for full-text search, the search term can be a single word, multiple words, or even a phrase.

Syntax:

//Create a Full-Text Index:CREATE FULLTEXT INDEX idx_your_index_name ON your_table_name(your_column_name);//Use MATCH AGAINST Syntax in SELECT statement to search for specific words:SELECT * FROM your_table_name WHERE MATCH(your_column_name) AGAINST (‘your_word’);

Example

Step 1: Create a Full-Text Index.

CREATE FULLTEXT INDEX idx_product_name ON products(product_name);

Step 2: Use MATCH AGAINST Syntax in SELECT statement to search for specific words.

SELECT * FROM products WHERE MATCH(product_name) AGAINST ('chair');

Output:

sql-output

sql select where match against

Explanation:

The query uses full-text search to retrieve records from the “products” table where the “it ” matches the word “chair.” The output includes rows with product names containing variations or forms of the specified word, providing a comprehensive search result.

Conclusion

In conclusion, using the SELECT WHERE clause to filter records by word matches is a powerful way to get accurate information. Whether you use the LIKE operator or you use full-text searching, knowing how to use these techniques will help you get the information you need faster, making your database queries more efficient.



Similar Reads

How to Select Words With Certain Values at the End of Word in SQL?
To select words with certain values at the end of the word In SQL, we can use pattern matching. A pattern matching allows users to search for certain patterns in the data. It is done using the LIKE operator in SQL. The query uses wildcard characters to match a pattern, Wildcard characters are case-sensitive. Some wildcard characters and their meani
2 min read
How to Update MongoDB Field Using Value of Another Field
In the NoSQL database, MongoDB is the most robust and flexible option for managing big data. One common problem that occurs when working with MongoDB is to Update the MongoDB field using the value of another field and change data within our database. In this article, we will learn about How to Update the MongoDB field using the value of another fie
3 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
How to Select a Single Field for all Documents in a MongoDB Collections
In MongoDB, retrieving specific data from a collection is a common operation that developers often perform. Whether we are building a web application or running analytical queries, selecting a single field from all documents in a MongoDB collection can provide valuable insights and simplify data processing. In this guide, we'll explore how to fetch
3 min read
How to Check if an Array Field Contains a Unique Value or Another Array in MongoDB?
MongoDB is a widely used NoSQL database that enables developers to query complex data structures flexibly. In MongoDB, arrays are commonly used to store lists of values, providing flexibility in data modeling. To ensure data integrity and get valuable insights, it's important to understand how to check for unique values and arrays within array fiel
4 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL Query to Delete Last N Characters From Field
SQL stands for Structured Query Language. It is used to communicate with the database. There are some standard SQL commands like 'select', 'delete', 'alter' etc. To delete the last N characters from the field we will use the string function. String function: It is used to perform an operation on an input string and return an output string. There ar
3 min read
Update Date Field in SQL Server
The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. With this article, we will learn how to Update the Date Field in SQL Server. In this article, we will be making use of the Microsoft SQL Server as o
2 min read
SQL Query to Convert Date Field to UTC
In SQL, dates are complicated for newbies, since while working with the database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, DateTime (time is also involved with date) is used. In this article, we will discuss how to convert Date Field to UTC in SQL. For this art
2 min read
How to Remove Prefix From Field in SQL Server?
In SQL, certain words are reserved. These are called Keywords or Reserved Words. These words cannot be used as identifiers i.e. as column names in SQL. But, there is an exception to this rule too. In this article, we will discuss how to use Reserved Words as column names in SQL and how to remove prefixes from a field. For this article, we will be u
2 min read
Select statement in MS SQL Server
In this article, the most basic statement used in SQL is being discussed. Basic statement: select There are large amounts of data available everywhere. The data is stored in a sequential order in form of a table. Each table consists of a row which represents a unique record and column represents a field. Schemas are used to arrange the tables in a
2 min read
Select top in MS SQL Server
Prerequisite - Select in MS SQL Server Suppose that a user wants to extract the top students from the whole institution but has to use some complex queries to extract the data. To avoid complexity, the user can use 'Select Top'. 'Select Top' extracts the limited number of rows. This results in accurate data along with less time consumption. Syntax
2 min read
SELECT data from Multiple Tables in SQL
The statement is used to retrieve the fields from multiple tables and with the help of JOIN operations we easily fetch the records from multiple tables, Generally JOINS are used when there are common records between two tables. In this article, we will look into various types of JOIN that are used in SQL. SQL JoinsSQL joins combine two or more tabl
3 min read
SQL | Query to select NAME from table using different options
Let us consider the following table named "Geeks" : G_ID FIRSTNAME LASTNAME DEPARTMENT 1 Mohan Arora DBA 2 Nisha Verma Admin 3 Vishal Gupta DBA 4 Amita Singh Writer 5 Vishal Diwan Admin 6 Vinod Diwan Review 7 Sheetal Kumar Review 8 Geeta Chauhan Admin 9 Mona Mishra Writer SQL query to write “FIRSTNAME” from Geeks table using the alias name as NAME.
2 min read
SQL Query to select Data from Tables Using Join and Where
The aim of this article is to make a simple program to Join two tables using Join and Where clause using MySQL. Below is the method to do the same using MySQL. The prerequisites of this article are MySQL and Apache Server on your computer are installed. What is a Query in SQL? A SQL query is a request passed for data/information from a table in a d
3 min read
SQL - SELECT DATE
In Microsoft SQL Server, SELECT DATE is used to get the data from the table related to the date, the default format of date is 'YYYY-MM-DD'. Syntax: SELECT * FROM table_name WHERE condition1, condition2,..; Now we will execute queries on SELECT DATE on database student in detail step-by-step: Step 1: Creating a database university: CREATE DATABASE
1 min read
SQL Query to Select all Records From Employee Table Where Name is Not Specified
Here, we are going to see how to find the names of the persons other than a person with a particular name SQL. In this article, we will be making use of the MSSQL Server as our database. For example, if the employee name is Pradeep you need to show the table of employees excluding that employee with the name Pradeep. So let us execute this query in
2 min read
SQL - SELECT RANDOM
RANDOM( ) in SQL is generally used to return a random row from a table present in the database. It has many applications in real life. For example : There are a lot of employees in an organization. Suppose, if the event manager wants to mail any ten random employees then he/she can use the RANDOM( ) in SQL to get the Email Id of the ten random empl
2 min read
SQL - SELECT NULL
The word NULL is used to describe a missing value in SQL. In a table, a NULL value is a value in a field that appears to be empty. A field with a NULL value is the same as one that has no value. It's important to grasp the difference between a NULL value and a zero value or a field of spaces. There are two possibilities: Where SQL is NULLSyntax: SE
2 min read
How to Select All Records from One Table That Do Not Exist in Another Table in SQL?
We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries. In this let us see How to select All Records from One Table That Do Not Exist in Another Table step-by-step. Creating a Database Use the below command to create a database named Geeks
2 min read
How to Exclude Records With Certain Values in SQL Select?
In this article, we will understand how to exclude some records having certain values from a table. For the purpose of demonstration, we will be creating a Participant table in a database called “GeeksForGeeksDatabase“. Step 1: Creating the DatabaseUse the below SQL statement to create a database called GeeksForGeeksDatabase. Query: CREATE DATABASE
3 min read
How to Select Group of Rows that Match All Items on a List in SQL Server?
In this article, we will see, how to select a group of rows that match all the items on a list in SQL Server. We can perform the above function by two methods. Those are: By using IN operatorBY performing JOIN using STRING_SPLIT methodIN operator: It allows you to specify a list of values in a WHERE clause. STRING_SPLIT(): this function can be used
2 min read
How to Select a Range of Letters in SQL?
In this article, we will see how to Select a Range of Letters in SQL using the LIKE clause. The LIKE clause is used for pattern matching in SQL using wildcard operators such as %, ^, etc. It has square brackets[] as one of the wildcard operators that is used to specify the range of characters for pattern matching. Let see these above mention functi
2 min read
How to Use SELECT In Order BY Specific Ids in SQL?
The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for ascending). In this article, we will be doing order by on a database with some specified values of the column only. So let's start by creating a Database first. Step 1: Create a database
1 min read
How to Select Individual Columns in SQL?
In SQL, sometimes we require to select individual columns from a table. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. Select is the most commonly used statement in SQL. The SELECT Statement in SQL is used to retrieve or fetc
2 min read
How to Use SELECT With Aggregate Functions in SQL?
In SQL, mainly five aggregate functions are provided. These help us to process the table data in the desired way. All these are illustrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE Gee
2 min read
How to Select Data Between Two Dates and Times in SQL Server?
In SQL, some transactions need to be extracted based on their completion times and dates. Here, the DATETIME2 data type in SQL to perform such operations. For this article, we will be using the Microsoft SQL Server as our database. Note: Here, we will use the two dates and times given in the query and separate them using the BETWEEN keyword. This i
2 min read
How to Select the First Row of Each GROUP BY in SQL?
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. To select the first row of each group in SQL, you can use the ' GROUP BY ' clause with the ' MIN ' or ' MAX ' aggregate function. SyntaxSELECT * FROM yourTable WHERE columnName = (SELECT MIN(columnName) FROM yourTable GROUP BY groupColumnNam
3 min read
Article Tags :