The basic form of an SQL query, specifically when retrieving data, is composed of a combination of clauses. The most elementary form of an SQL query for data retrieval can be represented as
SyntaxSELECT [DISTINCT] column1, column2, ...
FROM tablename
WHERE condition;
Let's break it down:
Here are the primary components of SQL queries:
To provide a more holistic view, here are a few more SQL examples, keeping them as basic as possible:
SELECT * FROM tablename;
SELECT column1, column2 FROM tablename;
SELECT column1, column2 FROM tablename WHERE column1 = 'value';
SELECT column1, column2 FROM tablename ORDER BY column1 ASC;
SQL provides support for pattern matching through the LIKE operator, along with the use of the wild-card symbols.
Regular expressions: is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching.
Examples:
Finds Names that start or ends with "a“
Finds names that start with "a" and are at least 3 characters in length.
LIKE: The LIKE operator is used in a 'WHERE' clause to search for a specified pattern in a column
wild-card: There are two primary wildcards used in conjunction with the `LIKE` operator
percent sign (%) Represents zero, one, or multiple characters
underscore sign(_) Represents a single character
Here's a breakdown of how you can use these wildcards with the `LIKE` operator:
SELECT column_name
FROM table_name
WHERE column_name LIKE 'pattern%';
For example, to find all customers whose names start with "Ma":
SELECT FirstName
FROM Customers
WHERE FirstName LIKE 'Ma%';
SELECT column_name
FROM table_name
WHERE column_name LIKE '%pattern';
For instance, to find all products that end with "ing":
SELECT ProductName
FROM Products
WHERE ProductName LIKE '%ing';
SELECT column_name
FROM table_name
WHERE column_name LIKE '%pattern%';
Example, to find all books that have the word "life" anywhere in the title:
SELECT BookTitle
FROM Books
WHERE BookTitle LIKE '%life%';
SELECT column_name
FROM table_name
WHERE column_name LIKE 'p_ttern';
For instance, if you're looking for a five-letter word where you know the first letter is "h" and the third letter is "l", you could use:
SELECT Word
FROM Words
WHERE Word LIKE 'h_l__';
You can use both wildcards in the same pattern. For example, to find any value that starts with "A", followed by two characters, and then "o":
SELECT column_name
FROM table_name
WHERE column_name LIKE 'A__o%';
Keep in mind that the actual symbols used for wildcards might vary depending on the database system. For example, in SQL Server, the wildcard for a single character is `[?]` instead of `_`. Always refer to the specific documentation of the database you're working with.