A nice SQL question!
It seems like you want to use a LIKE pattern with a range of values, and also match the length of the code column. Here's how you can do it:
Method 1: Using multiple OR conditions
(code LIKE '21%' OR code LIKE '22%' OR code LIKE '23%' OR code LIKE '24%'
OR code LIKE '25%' OR code LIKE '26%' OR code LIKE '29%')
AND LENGTH(code) = 4;
Method 2: Using REGEXP (Regular Expressions)
If your database management system (DBMS) supports regular expressions (e.g., MySQL, PostgreSQL), you can use:
code REGEXP '^(21|22|23|24|25|26|29)' AND LENGTH(code) = 4;
Here's how it works:
^ matches the start of the string.
(21|22|23|24|25|26|29) is a group of alternatives (the | character means "or"). It matches any of the specified values.
- The
REGEXP operator checks if the code column matches this pattern.
AND LENGTH(code) = 4 ensures the length of code is still 4 characters.
Method 3: Using BETWEEN and LIKE (if the range is contiguous)
If your desired values were contiguous (e.g., 21 to 26, without the jump to 29), you could use:
code LIKE '2_' AND code BETWEEN '2100' AND '2699' AND LENGTH(code) = 4;
Here:
2_ matches any string starting with 2 followed by any single character (_ is a single-character wildcard).
BETWEEN '2100' AND '2699' filters the range (inclusive).
LENGTH(code) = 4 still checks the length.
However, since your desired values are not contiguous (21 to 26, then 29), this method won't work exactly as needed.
Method 4: Extracting the prefix and checking (DBMS-dependent)
In some DBMS (e.g., PostgreSQL, SQL Server), you can extract the first 2 characters and check:
-- PostgreSQL example
SUBSTR(code, 1, 2) IN ('21', '22', '23', '24', '25', '26', '29') AND LENGTH(code) = 4;
or
-- SQL Server example
code LIKE '__%' AND LEFT(code, 2) IN ('21', '22', '23', '24', '25', '26', '29') AND LEN(code) = 4;
Choose the method that best fits your DBMS and personal preference!
Example use case (MySQL):
CREATE TABLE mytable (code VARCHAR(10));
INSERT INTO mytable (code) VALUES
('2100'), ('2201'), ('2302'), ('2403'), ('2504'),
('2605'), ('2906'), ('2707'), ('2008'), ('1234';
SELECT * FROM mytable
WHERE code REGEXP '^(21|22|23|24|25|26|29)' AND LENGTH(code) = 4;
Result:
+------+
| code |
+------+
| 2100 |
| 2201 |
| 2302 |
| 2403 |
| 2504 |
| 2605 |
| 2906 |
+------+
Only the rows with code values starting with 21, 22, 23, 24, 25, 26, or 29, and having a length of 4 are returned. Happy querying!