Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching SQL on first 5 characters

I'm thinking about a SQL query that returns me all entries from a column whose first 5 characters match. Any ideas? I'm thinking about entries where ANY first 5 characters match, not specific ones. E.g.

HelloA
HelloB
ThereC
ThereD
Something

would return the first four entries:

HelloA
HelloB
ThereC
ThereD

EDIT: I am using SQL92 so cannot use the left command!

like image 212
MJP Avatar asked Nov 06 '13 19:11

MJP


People also ask

How can you fetch first 5 characters of the string in SQL?

The LEFT() function extracts a number of characters from a string (starting from left).

How do you match patterns characters in SQL?

SQL pattern matching enables you to use _ to match any single character and % to match an arbitrary number of characters (including zero characters). In MySQL, SQL patterns are case-insensitive by default.

How do I select the first 3 characters in SQL?

SELECT LEN(column_name) FROM table_name; And you can use SUBSTRING or SUBSTR() function go get first three characters of a column.


2 Answers

Sounds easy enough...

In SQL Server this would be something along the lines of

where Left(ColumnName,5) = '12345'
like image 89
Tim Avatar answered Nov 07 '22 00:11

Tim


Try this :

SELECT *
FROM YourTable
WHERE LEFT(stringColumn, 5) IN (
    SELECT LEFT(stringColumn, 5)
    FROM YOURTABLE
    GROUP BY LEFT(stringColumn, 5)
    HAVING COUNT(*) > 1
    )

SQLFIDDLE DEMO

This selects the first 5 characters, groups by them and returns only the ones that happen more than once.

Or with Substring:

SELECT * FROM YourTable 
WHERE substring(stringColumn,1,5) IN (
  SELECT substring(stringColumn,1,5)
  FROM YOURTABLE
GROUP BY substring(stringColumn,1,5)
HAVING COUNT(*) > 1)
;

SQLFIDDLE DEMO

like image 25
Filipe Silva Avatar answered Nov 07 '22 00:11

Filipe Silva