Selecting All Except Certain Columns

9.9.10 Selecting All Except Certain Columns

Som et im es you want t o ret rieve alm ost all t he colum ns from a t able. Suppose you have an image t able t hat cont ains a BLOB colum n nam ed data used for st oring im ages t hat m ight be very large, and ot her colum ns t hat charact erize t he BLOB colum n, such as it s I D, a descript ion, and so fort h. I t s easy t o writ e a SELECT query t hat ret rieves all t he colum ns, but if all you need is t he descript ive inform at ion about t he im ages and not t he im ages t hem selves, it s inefficient t o drag t he BLOB values over t he connect ion along wit h t he ot her colum ns. I nst ead, you want t o select everyt hing in t he record except t he data colum n. Unfort unat ely, t here is no way t o say direct ly in SQL, select all colum ns except t his one. You m ust explicit ly nam e all t he colum ns except data . On t he ot her hand, it s easy t o const ruct t hat kind of query by using t able st ruct ure inform at ion. Ext ract t he list of colum n nam es, delet e t he one t o be excluded, t hen const ruct a SELECT query from t hose colum ns t hat rem ain. The following exam ple shows how t o do t his in PHP, using t he get_column_names_with_show funct ion developed earlier in t he chapt er t o obt ain t he colum n nam es from a t able: names = get_column_names_with_show conn_id, tbl_name; query = ; construct list of columns to select: all but data reset names; while list index, name = each names { if name == data continue; if query = put commas between column names query .= ,; query .= name; } query = SELECT query FROM tbl_name; The equivalent Perl code for const ruct ing t he query is a bit short er and correspondingly m ore crypt ic : my names = get_column_names_with_show dbh, tbl_name; my query = SELECT . join ,, grep data, names . FROM tbl_name; Whichever language you use, t he result is a query t hat you can use t o select all colum ns but data . I t will be m ore efficient t han SELECT because it w ont pull t he BLOB values over t he net work. Of course, t his process does involve an ext ra round t rip t o t he server t o execut e t he st at em ent t hat ret rieves t he colum n nam es, so you should consider t he cont ext in which you plan t o use t he SELECT query. I f youre j ust going t o ret rieve a single record, it m ight be m ore efficient sim ply t o select t he ent ire row t han t o incur t he overhead of t he ext ra round t rip. But if youre select ing m any rows, t he reduct ion in net work t raffic achieved by skipping t he BLOB colum ns will be wort h t he overhead of t he addit ional query for get t ing t able st ruct ure.

9.10 Listing Tables and Databases