Find only last four characters in the column?

Discussion in 'Databases' started by greatlogix, Jun 22, 2009.

  1. #1
    order table have column order_id with value "002-0123060-8773017" in it. Is it possible that I supply last 4 digits/characters to query "3017" to get selected the row containing the above number? I want to get all orders where order# ends with "3017"
     
    greatlogix, Jun 22, 2009 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    First I would put an index on the last 4 characters of the field.

    Then you can use something like this to return the rows.

    SELECT * FROM order_table WHERE RIGHT(order_id,4) = '3017';
     
    jestep, Jun 22, 2009 IP
  3. greatlogix

    greatlogix Active Member

    Messages:
    664
    Likes Received:
    13
    Best Answers:
    1
    Trophy Points:
    85
    #3
    Thanks jestep for your reply.
    MY database knowledge is not so good. How to add index on the last 4 characters of the field? Can you share syntax?

    Thanks. Rep added.
     
    greatlogix, Jun 22, 2009 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    Disregard that. You can only specify a length on the beginning of the index and not the end.
     
    jestep, Jun 22, 2009 IP
  5. chisara

    chisara Peon

    Messages:
    141
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #5
    That is not correct jestep, indexes are not part of the SQL specification, as such they are not mandatory.
    But the advantages of indexes are numerous and for this reason vendors implement their own indexing functionality.
    I know PostgreSQL supports indexing on expressions and I would expect that MS-SQL, Oracle and DB2 do this as well.
    Rough version in PostgreSQL would be
    CREATE INDEX yourindex_idx ON yourtable (substr(yourstring,length(yourstring)-4,4);

    Of your DB does not get this form of indexing you can add a column called lastfourcharacters in the table and fill this with an oninsert and onupdate trigger. Then put a normal index on that column.
     
    chisara, Jun 23, 2009 IP