What is faster?

Discussion in 'MySQL' started by Gazzerman, Aug 19, 2008.

  1. #1
    EXAMPLE
    ----------
    Table peoplesnames

    id - bigint(100) - auto_increment
    firstname - varchar(20)
    lastname - varchar(20)
    age - int(2)
    otherdetails - varchar(20)

    Indexes
    id - UNIQUE
    age INDEX

    -----------

    My database has 3 million records. I want to find a record where I know the ID number already.

    My question is: Does the database need to search through each record until it finds the ID number that I am looking for?

    SELECT id FROM peoplesnames WHERE id= '1234567';

    Would it be quicker to use the index AGE as well to cut down on the ID numbers to look at?

    SELECT id FROM peoplesnames WHERE age = '21' AND id= '1234567';


    Thanks
     
    Gazzerman, Aug 19, 2008 IP
  2. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #2
    id is already a UNIQUE key. There is no need to use any additional index. Though you can use EXPLAIN to compare both the queries.
     
    mwasif, Aug 20, 2008 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    Agreed. It would be a waste of time to use the age = in the where clause because of the unique id.
     
    jestep, Aug 20, 2008 IP
  4. Gazzerman

    Gazzerman Active Member

    Messages:
    570
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    60
    #4
    Thanks guys, but does the database need to look through each record to find the number even though its unique?

    And is this the same for doing a delete, because I delete about 100,000 lines a day.

    Funny about the explain, I just found out about that 2 days ago.

    Cheers
     
    Gazzerman, Aug 20, 2008 IP
  5. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #5
    You can find out this in EXPLAIN's output (column named 'rows').

    For your convenience, MySQL does not need to look through all the records if the column is UNIQUE.
     
    mwasif, Aug 21, 2008 IP
  6. dugu

    dugu Active Member

    Messages:
    1,381
    Likes Received:
    40
    Best Answers:
    0
    Trophy Points:
    90
    #6
    For an unique field, mysql has the fastest search
     
    dugu, Aug 22, 2008 IP
  7. Gazzerman

    Gazzerman Active Member

    Messages:
    570
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    60
    #7
    Thanks guys
     
    Gazzerman, Aug 24, 2008 IP