Write an SQL query to retrieve the supplier number and supplier names from the supplier table, where the supplier name starts with the letter ‘R’.
The correct answer and explanation is :
To retrieve the supplier number and supplier names from the supplier table where the supplier name starts with the letter ‘R’, you can use the following SQL query:
SELECT supplier_number, supplier_name
FROM supplier
WHERE supplier_name LIKE 'R%';
Explanation:
- SELECT supplier_number, supplier_name:
- The
SELECTstatement specifies the columns to retrieve from the database. Here,supplier_numberandsupplier_nameare selected.
- FROM supplier:
- The
FROMclause indicates the table from which to retrieve the data. In this case, it’s thesuppliertable.
- WHERE supplier_name LIKE ‘R%’:
- The
WHEREclause filters the rows based on specified conditions. - The
LIKEoperator is used to search for a specified pattern in a column. - The pattern
'R%'means the supplier name must start with the letter ‘R’. - The
%symbol is a wildcard character that matches any sequence of characters (including no characters). So,'R%'matches any string that begins with ‘R’.
How the Query Works:
- The
SELECTstatement retrieves data from the specified columns. - The
FROMclause identifies the source table for the data. - The
WHEREclause applies a filter to include only rows where thesupplier_namestarts with ‘R’. - The
LIKE 'R%'condition ensures that only supplier names beginning with ‘R’ are selected.
Example:
Consider a supplier table with the following data:
| supplier_number | supplier_name |
|---|---|
| 1 | Robert |
| 2 | Alice |
| 3 | Rachel |
| 4 | Bob |
| 5 | Rick |
Applying the query:
SELECT supplier_number, supplier_name
FROM supplier
WHERE supplier_name LIKE 'R%';
Would return:
| supplier_number | supplier_name |
|---|---|
| 1 | Robert |
| 3 | Rachel |
| 5 | Rick |
This result includes only the suppliers whose names start with ‘R’.
Additional Notes:
- SQL is case-insensitive by default in many databases. Therefore,
'R%'will match names starting with both ‘R’ and ‘r’. If case sensitivity is required, you may need to use a case-sensitive collation or function, depending on your database system. - Ensure that the column names (
supplier_numberandsupplier_name) and the table name (supplier) match exactly those in your database schema. - If your database uses different naming conventions (e.g., snake_case), adjust the column and table names accordingly.
This query efficiently retrieves the desired supplier information based on the specified condition.