Problem Solution Discussion Avoiding Output Column Order Problems When Writing Programs

| 2001-05-11 10:15:08 | barb | saturn | 58274 | | 2001-05-12 12:48:13 | tricia | mars | 194925 | | 2001-05-12 15:02:49 | phil | mars | 1048 | | 2001-05-13 13:59:18 | barb | saturn | 271 | ...

3.3 Avoiding Output Column Order Problems When Writing Programs

3.3.1 Problem

Youre issuing a SELECT query from wit hin a program , and t he colum ns dont com e back in t he order you expect .

3.3.2 Solution

When you use t o select colum ns, all bet s are off; you cant assum e anyt hing about t he order in which t heyll be ret urned. Eit her nam e t he colum ns explicit ly in t he order you want , or ret rieve t hem int o a dat a st ruct ure t hat m akes t heir order irrelevant .

3.3.3 Discussion

The exam ples in t he previous sect ion illust rat e t he differences bet ween using versus a list of nam es t o specify out put colum ns when issuing SELECT st at em ent s from wit hin t he m ysql program . The difference bet ween approaches also m ay be significant when issuing queries t hrough an API from wit hin your own program s, depending on how you fet ch result set rows. I f you select out put colum ns using , t he server ret urns t hem using t he order in which t hey are list ed in t he t able definit ion—an order t hat m ay change if t he t able st ruct ure is m odified. I f you fet ch rows int o an array, t his non-det erm inacy of out put colum n order m akes it im possible t o know which colum n each array elem ent corresponds t o. By nam ing out put colum ns explicit ly, you can fet ch rows int o an array wit h confidence t hat t he colum ns will appear in t he array in t he sam e order t hat you nam ed t hem in t he query. On t he ot her hand, your API m ay allow you t o fet ch rows int o a st ruct ure cont aining elem ent s t hat are accessed by nam e. For exam ple, in Perl you can use a hash; in PHP you can use an associat ive array or an obj ect . I f you do t his, you can issue a SELECT query and t hen access st ruct ure m em bers by referring t o t he colum n nam es in any order you want . I n t his case, t here is effect ively no difference bet ween select ing colum ns wit h or by nam ing t hem explicit ly: I f you can access values by nam e wit hin your program , t heir order wit hin result set rows is irrelevant . This fact m akes it t em pt ing t o t ake t he easy way out by using SELECT for all your queries, even if youre not act ually going t o use every colum n. Nevert heless, it s m ore efficient t o nam e specifically only t he colum ns you want so t hat t he server doesnt send you inform at ion youre j ust going t o ignore. An exam ple t hat explains in m ore det ail why you m ay want t o avoid ret rieving cert ain colum ns is given in Recipe 9.9 , in Recipe 9.9.10 .

3.4 Giving Names to Output Columns