Search only first 3 characters of a column

Discussion in 'Databases' started by greatlogix, Mar 18, 2011.

  1. #1
    I need to find rows using 3 digit area code in phone numbers
    phone numbers are stored in this format (300-121-0101) in "phone" column.

    phone
    300-121-0101
    300-151-0122
    333-141-4422

    I need a query to input "300" and get first 2 rows.

    Can somebody help me?
     
    greatlogix, Mar 18, 2011 IP
  2. jhkoenig

    jhkoenig Peon

    Messages:
    56
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    select * from xxxxx where substring(phone,1,3) = yyy
    where xxxxx is your table name and yyy is your area code.

    My site, WannaBuddy.com depends on such database trickery.
    Good luck!
     
    jhkoenig, Mar 18, 2011 IP
  3. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    you can also use:

    select * from tableName where phone like "300%";
     
    gandalf117, Mar 18, 2011 IP
  4. ACME Squares

    ACME Squares Peon

    Messages:
    98
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    The LIKE operator (gandalf117's solution) will be faster than substring, so use LIKE.
     
    ACME Squares, Mar 22, 2011 IP
  5. randheer

    randheer Greenhorn

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #5
    check this out

    Check this example you can provide the @var as 300 for your input

    declare @table table (phno varchar(100))
    insert into @table values (300457589)
    insert into @table values (300457589)
    insert into @table values (305457589)

    declare @var varchar(100)
    set @var=300

    select * from @table where phno like @var + '%'

    don't use substring function it will make operation slow. As using function on column will impact not using index of that column on execution plan.
     
    randheer, Apr 5, 2011 IP
  6. backlinkmaker

    backlinkmaker Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    select * from tableName where phone like "300%";
     
    backlinkmaker, Apr 5, 2011 IP