Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Select a substring in Oracle SQL

say I have a table customer with columns Firstname and lastname I would like to be able to write a query that selects all the customers which has exact lastname and the fuzzy firstname

The Substring is returning the values as expected when I run this just on the firstname column

Query

SELECT SUBSTR(firstname,1,4) from customer;

**output:**
ABCD
qwry
cvbn etc

But I am not sure how to get this work to do a match for 2 records, one of the customers having first 4 characters of firstname same as the other customer firstname.

Example:

Customer1:Firstname=ABCDXYZ Lastname=SSS

Customer2:Firstname=ABCD Lastname=SSS

The expected outcome is to be able to see these 2 records in the output

like image 420
user0726 Avatar asked Jan 29 '26 20:01

user0726


1 Answers

The below query will fetch the records who has same last names and same first four characters of first name. It uses self join. Hope the table has a primary key like id.

SELECT distinct c1.firstname, 
                c1.lastname, 
                c2.firstname, 
                c1.lastname
  FROM customer c1, customer c2
 WHERE c1.id <> c2.id 
   AND c1.lastname = c2.lastname
   AND substr(c1.firstname,1,4) = substr(c1.firstname,1,4)
like image 75
Valli Avatar answered Feb 01 '26 12:02

Valli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!