Content-type: text/html NUTsqlite Documentation


Section: (1)
Updated: 2014.06.14
Index Return to Main Contents


nut - analyze meals with the USDA Nutrient Database  




NUT allows you to record what you eat and analyze your meals for nutrient composition. Nutrient levels are expressed as a percentage of the DV or Daily Value, the familiar standard of food labeling in the United States. The essential fatty acids, Omega-6 and Omega-3, are not currently mentioned in these standards, and a reference value has been supplied.

NUT uses Tcl/Tk to create an SQLite database that holds its own code, the USDA Nutrient Database for Standard Reference, and your personal data for meals, recipes, and weight logs.

INSTALLATION and LOAD of USDA Database: If your desktop system does not have Tcl/Tk available, download and install the free (community) version of ActiveTcl from

Download the full ascii version of the USDA Nutrient Database, available from or from, and unzip it in some directory.

Run "updateNUT.tcl", an executable included in the NUT distribution, in the same directory where you put the USDA database. This script will load your new NUT database with the NUT code. After this step, run "nut.tcl" to start NUT. Initially, NUT will see the USDA tables and load them as well as any legacy files from previous versions of NUT. After these steps, both "updateNUT.tcl" and the USDA files are not required and can be deleted.

"nut.tcl" can start the program with a different location for the NUT database and a different location for legacy files. These changes are easily made by editing "nut.tcl".

In addition, a value can be changed in "nut.tcl" to make the program usable on screens with a high resolution. NUT will check how many pixels you have and create a font/window combination that is always legible. Change the "appSize" variable in "nut.tcl" to between 0.7 (small) and 1.3 (almost fullscreen) to magnify the default Tk font and window sizes appropriately.


A typical session with NUT begins with a glance at "Analyze Meals" to see the daily averages from the last few meals. Normally, one analyzes more than one day but less than two weeks to get a fairly recent overview of nutritional quality and adherence to plan.

"Record Meals & Recipes" is where meals are planned or else simply recorded if unplanned. A slider can either be moved directly or else clicked on the left or right to move backward or forward to get to the current meal. A simple "Food Search" entry brings up the foods in the database and if one is selected, it is immediately added to the meal. A major feature of NUT is to be able to associate meal foods with automatic portion control for various nutrients so you can more easily plan meals that are both nutritionally complete and in accord with your personal regimen. This function also allows you to save a "meal" as a recipe to be added to the USDA database, or to designate a meal as a Customary Meal for easier data entry later.

"View Foods" shows comprehensive nutrient listings for each food, in serving sizes as described by the USDA nutrient database. Any of these serving sizes can be scaled and easily added to a meal, and NUT remembers your preferred serving sizes.

"Personal Options" allows the nutrient standards to be changed. These personal standards are customized and the rest of the program follows these standards. It is unlikely that the straight "Daily Value", a high-carb, low-fat diet with an absolute minimum of protein, will be optimal for you, so you can try different program settings, experiment to see how you feel when eating different ways, and thus gradually find the style of eating that is your personal optimum. In addition, there is a facility to record weight and bodyfat percentages daily and see a linear extrapolation of the trend so that you do not have to wait weeks to know how a new strategy is working. NUT will also automatically move calories up and down by gradual increments in order to keep lean mass up and fat mass down with the Calorie Auto-Set feature.

Whenever you press a nutrient button you go to a screen that describes "The Story" for that nutrient. This includes various lists of foods sorted to help you find the nutrients you need.


Meal analysis is always a daily rate of intake and not a sum. For instance, if you eat 2000 calories a day and analyze a week of meals, the analysis reports 2000 calories, not 14,000. Likewise, if you eat three meals a day and 2000 calories a day and analyze a single meal of 667 calories, the analysis reports 100% of calories, not 33% of calories. Think of NUT meal analysis as a speedometer, not an odometer.

The range of meals shown on the screen controls many other functions in the program as it not only sets the range for showing food lists, but also the exact Daily Values used in portion control. Therefore, if you want automatic portion control to be as accurate as possible, analyzing just one meal while you are planning meals is best, although it is not required most of the time--just when you are changing strategies, such as from high-carb to low-carb.

The spin button controlling how many consecutive meals to analyze can be selected and cleared with a backspace to speed up making large changes. A very large value will resolve to all the meals in the database, but do remember, if automatic portion control is in effect, there will be a lot of processing to get all of the program functions into sync because portion control always needs to reanalyze all meals until it is sure the requirements are properly met.


For the program analysis to come out right you must record all the meals the program is set for. For instance, if NUT is set for three meals a day, and you eat more than three, combine them into three; if you eat less than three, record some minimal item such as an ounce of water for each missing meal. In this way, even if you take breaks from recording, NUT will report fairly accurate daily averages and just concatenate over the breaks; but otherwise NUT will wrongly weight the meals as a wrong percentage of a day.

When the program first starts, there is a button to "Delete all Meals and Set Meals per Day". Although meals are deleted from view, they are actually archived, so that if you return to the current number of meals per day, the meals will return to the active database. If meal planning is not your forte, or if your meal schedules are highly irregular, set NUT to 1 meal per day and record a daily running total of all foods eaten.

To actually record a meal, first determine if the slider in the upper left corner of the screen shows the correct meal; if not, click on the left or right of the slider to nudge it one meal at a time in the right direction until the correct meal is showing. Then click on the "Food Search" entry area to open up the search screen. Type a part of a food name and all the foods that match will be shown below as you type. Select one with a click and it will be added to the meal.

You can specify quantities in either gram or ounce weights by adjusting the spin button, or by clicking on the food to open up "View Foods" so you can choose a serving size based on cups or some other volume measurement, but you can also let NUT set the quantity with "Auto Portion Control". To achieve portion control based on calories, it is necessary to choose each of a protein, fat, and non-fiber carb food (unless some of these macronutrients are set to "Adjust to my meals"). But in addition, if you have noticed that you rarely achieve the "Daily Value" for some of the vitamins and minerals, they can also be chosen as "Auto Portion Control" nutrients. For instance, you could use Panto. Acid Auto Portion Control on something like mushrooms or avocado to make sure you get some of this vitamin. In this manner, with a combination of portion-controlled foods and non-portion-controlled foods, you can plan a meal that exactly meets your nutrition goals while hopefully being something you really want to eat. When the Auto Portion Control algorithm is running, the "Food Search" entry area turns into an indeterminate progress bar and the food quantities flip around as they find the best possible solution.

The more "Auto Portion Control" selections you make, the more complicated the process of finding the answer becomes, some combinations become impossible, and some combinations might send the algorithm off the deep end, in that it never completes. Perhaps later versions of NUT will have a better way to predict what is going to happen. For the time being, if you need a complicated solution using many portion-controlled foods, be ready to blow away the window running NUT and start over if it doesn't work. And if a Tcl error message dialog appears, just click "OK", because the error is a transient consequence of an unexpected set of foods that cannot be portion controlled to the selected specification. These problems will be rare occurrences as NUT is able to recognize many combinations of foods and portion-control settings that are not compatible.

When you have a good meal planned and think you may want to repeat it, use the Customary Meals feature to save the meal. Later, when you want something similar, add the customary meal to the new meal you are planning. If you add the same meal more than once, you don't double the foods, but you can refresh the Automatic Portion Control easily by adding the meal again. Likewise, you can save the meal multiple times without duplicating the meal foods. Customary Meals can always be adapted to whatever you are going to have, by adding and deleting foods as required, and by changing quantities.

Record a recipe in exactly the same way as a meal, but press the "Save as a Recipe" button to add your recipe as a new food to the USDA database. Then, fill in the blanks with the recipe name, the number of servings, any volume measurement you want to use to measure a serving, such as cups, teaspoons or pieces, etc., and if you know the weight of a serving after preparation, the recipe will be adjusted for water gained or lost in preparation. Furthermore, you will be presented with the complete nutrient screens so you can adjust the nutrient values. This allows you to create a "recipe" that is actually just a processed food or food supplement, where the real ingredients are similar to the processed food or maybe just some water, but you are changing the nutrient information to match the label on a product. On these recipe nutrient screens, the "Daily Value" percentages are the standard 2000 calorie values, not any modifications you may have made from "Personal Options", so that they will match the nutrition labels; however, nutrient values can always be entered in grams. When you "Save" this new recipe, it becomes just like any other food in the database.

A non-obvious use for recipes is to add a new serving size to an existing food to make portion control easier. Take one of my favorites, a roasted chicken wing. The meat weighs 34 grams in an average wing but there is 40% refuse, meaning that the wing weighed on the bone comes to almost 57 grams (34 / 0.6). So, you can make a recipe that is just a duplicate of the food with a slightly different name, but with a serving unit of "grams weighed with refuse" and the number of serving units in one serving is 56.67. Then, at mealtime, if you need strict portion control, you go to "View Foods" and set a number of servings corresponding to the weight of the wings on the bone and add it to the meal, and only the weight of the meat shows up in the meal.

Yet another use for "Save as a Recipe": Use it to quickly delete an entire meal, and then cancel the recipe.


Here's where you can check out the whole nutritional record for a food based on whatever serving size you want to see represented. Notice that many processed foods have very brief summaries of nutrients with many "[No Data]" entries. When added to meals, "[No Data]" is treated as a zero, and since nutrient values for specific foods vary considerably, analyses are always approximate and not nearly as precise as NUT seems to suggest.

Additional information on this screen includes refuse percentages and descriptions that can help in visualizing how much food is required, and serving sizes can be computed by calorie level as well as by weight.


In the simplest case, you are just typing the number of grams of some nutrient that you want to ingest daily, or else clicking an option that will automatically set the value for you. Because the spinbuttons move so slowly, for a big change you usually will select the old value with the mouse, backspace it out, and type the new value you want. All of NUT is hooked together internally, so if your changes impact automatic portion control, there will be lots of activity to get the meal and its analyses all in sync and save everything to the database.

"Adjust to my meals" is the setting if you don't care what the value for a nutrient should be, or if you do care, but you manage the value by different means. For instance, if you are eating low-carb, and you always plan meals to have minimal carbohydrate, "Adjust to my meals" means you don't have to hit a particular carb target and yet everything will mesh properly as if you had set a carb target that was exactly equal to what is in your meals.

Either "Total Fat" or "Non-Fiber Carb" can be set to "Balance of Calories" and sometimes this option will automatically appear if required in order to meet the Calorie requirement.

The options for polyunsaturated fat and the "Omega-6/3 Balance" target select reference values (there are no "Daily Values" for these) based on Dr. William Lands' empirical equation for the percentages of Omega-6 and Omega-3 fatty acids in tissue phospholipids based on diet. What this means is that the actual gram weights of Omega-6 vs. Omega-3 are not a very good indicator of what your body does with the fatty acids because the individual fatty acids have different "strengths" as they compete for conversion to the forms that make up the cell membrane and get chosen at random to provide a signal that is either strong or weak in its effect on inflammation, blood clotting, etc. Further information about this biochemistry is on the NUT site at

(Following is a description of the rightmost column on the screen that concerns the weight log. At some lower screen resolutions, this column can be partially occluded. However, if you move the mouse over the imaginary line between the program settings and the weight log columns, there will appear a double arrow that you can click and drag to the left to bring the weight log column into full view.)

NUT records daily weight and bodyfat percentage measurements and uses linear regression to filter out the random noise and show the actual trend. Are you gaining mostly fat mass or losing mostly lean mass? This feature can tell you if you have a bathroom scale that can read bodyfat percentage. The weight measurement is free of units, so pounds, kilos, or even stone will work. Although NUT reports its findings with high precision, realize that the numbers are not absolutely true, but you are concerned with the trends the numbers represent, so that you can modify your nutrition strategy. For example, if total weight is fairly constant but lean mass is going down and fat mass is going up, would a little more protein or less carbohydrate solve the problem? or would it make it worse?

To use the feature, weigh yourself once a day at some appointed time and enter the weight and bodyfat numbers; then click on "Accept New Measurements". NUT will only accept one set of measurements per day, but there is no harm in missing a day because the feature runs every day whether you add a measurement or not. Think of each new set of measurements as a small correction to the equation to get a truer picture where you are going, and that's how you tell if it is working, because its predictions eventually do seem to be about right. Weight loss gurus often advise against daily weighing because they are afraid you will freak out on days weight goes up. But NUT uses linear regression to remove the noise of daily measurement error and produce a clear signal which way the weight is trending, and the more daily samples, the stronger the signal. This way you can find out more quickly that a particular strategy just isn't working. Also, you can become more aware of weight loss strategies that work by reducing lean mass instead of fat mass.

Calorie "Auto-Set" means that you will eat according to the calorie level that NUT shows and also record your weight and bodyfat percentage daily. NUT can then determine how best to move the calorie level so that gains in lean mass and loss of fat mass are possible. A cycle begins when there are two weight/bodyfat data points recorded. NUT will move calories by a maximum of 20 calories a day. If both lean mass and fat mass are trending down, NUT raises calories and starts a new cycle; if both lean mass and fat mass are trending up, NUT lowers calories and starts a new cycle. When fat mass is trending up and lean mass is trending down, NUT starts a new cycle without changing calories. A cycle which begins with lean mass going up and fat mass going down is allowed to continue as long as the favorable trend prevails. The last set of measurements is always retained for a quick start to the next cycle which means that whenever the weight log is cleared, you see "1 data point so far..."

If you are not using the Calorie Auto-Set feature, you can clear the weight log whenever you like; the usual reason would be that you have started a new strategy and therefore want to see the new trend. For instance, I tend to make five to seven days of measurements, check the numbers, move calories up or down as required, and then clear the weight log when I am trying to find the right calorie level for my latest experiment. The last weight log entry is again retained after clearing the weight log to enable a quicker start to the next cycle of logging.


When you click on a yellow nutrient button, you are taken to a tab that expounds the nutrient's story. The screen features a list of foods sorted from most to least of the nutrient of interest, and a simple graph of intake during the current analysis period that you set in "Analyze Meals".

The food lists can be queried in multiple ways. The basic queries are by weight, by calories, by an approximate serving, and by weight of food in the analyzed daily meals, but the results can be modified to only look at a single food group. If you get a white screen after the "wristwatch" cursor changes back to normal, that means there are no foods that meet the criteria. For instance, if I look at "Foods Ranked per Daily Recorded Meals" and the food group "Breakfast Cereals" but I have eaten no breakfast cereal, I will get a white screen.

If a food from the list looks interesting, click on it so it will open up in "View Foods".


This is an advanced topic that will be expanded as I receive questions about it. The SQLite3 database can be queried independently of the use of NUT and indeed, that is one reason I wrote this version of the software. However, I doubt that knowledge of SQL is widespread, so first I will give an example of a question I asked my database: What date did I have the greatest amount of lean mass and how much was it?

The table we will use is "wlog", and first we are curious about the schema, or what data is in "wlog". For this example, I will use the "sqlite3" commands that come with SQLite, but any third-party software for querying SQLite will work.

I start up the software with the command "sqlite3 nut.sqlite" and get the output:

SQLite version 3.7.13 2012-06-11 02:05:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"

If I need to be reminded what table I am looking for, I ask to see a list of all the tables:

sqlite> .tables
am                 fd_group           recipe             vf               
am_zero            food_des           rm                 vf_zero          
ar                 mealfoods          rm_zero            weight           
archive_mealfoods  meals              sql_statements     weightslope      
dv                 nut_opts           tcl_code           wlog             
dv_defaults        nutr_def           theusual         
fatslope           options            version

(It should be noted that some of the views require Tcl procedures and thus can't be queried apart from NUT.)

Now I ask what data is in the "wlog" table by asking to see the "schema":

sqlite> .schema wlog
CREATE TABLE wlog(weight real, bodyfat real, wldate int, cleardate int, primary key(wldate, cleardate));

This is the exact SQL that created the wlog table. Now I ask "what is the most lean mass I have had?"

sqlite> select max(weight - weight * bodyfat / 100) as leanmass from wlog;

(Don't be shocked if you think this is too low; I am not a bodybuilder or a big guy.) Now I ask, "what was the date I had this much lean mass?"

sqlite> select wldate from wlog where weight - weight * bodyfat / 100 = (select max(weight - weight * bodyfat / 100) from wlog);

Increasing lean mass is great, but as the sole measure of body composition it leads to obesity; decreasing fat mass is great, but as the sole measure of body composition it leads to frailty. What we need is an equation which increases in value as body composition improves. Perhaps the simplest is lean mass minus fat mass, or in other words, what is the "spread" between the lean mass and the fat mass quantities:

sqlite> select wldate, round(weight - weight * bodyfat / 100, 1) as leanmass, round(weight * bodyfat / 100, 1) as fatmass, round(weight - 2 * weight * bodyfat / 100, 1) as bodycomp from wlog group by wldate; 

Now, let's turn to a different task. I've created a bad recipe and I want to delete it from the database. First, I find the record in the food_des table and ask to see "NDB_No", the primary key for foods:

sqlite> select NDB_No, Long_Desc from food_des where Long_Desc like '%ramen jello%';
99008|Ramen jello toast, artisanal, with gelatin from pastured pork

When I know the NDB_No, I can delete the food record from food_des and any associated weight records from weight:

sqlite> delete from food_des where NDB_No = 99008;
sqlite> delete from weight where NDB_No = 99008;

Hopefully you will never need to do this, but it is possible that automatic portion control could write a completely awry meal that NUT is unable to analyze when it tries to come up. The only recourse then is to delete the meal from the database using the meal_date and meal number like this:

sqlite> delete from mealfoods where meal_date = 20150413 and meal = 3;

If the previous strategy then fails again when a meal is reloaded, it probably means the weight table has recorded some impossible weight. For instance, if you have determined there is more spinach in the meal than molecules in the universe, this command will fix it:

sqlite> update weight set Amount = origAmount, whectograms = orighectograms where NDB_No = 11457;

Although you can update some of the NUT data manually as in the previous examples, do note that if you update nutrient values in the food_des table, your updates will not propagate to the existing meals in the meals table unless you reload the USDA nutrient database, this as a consequence of the table joins done at load time to improve performance at runtime.

Now a question which was difficult to answer with the legacy NUT program but fairly easy to answer with SQL. I was buying the most expensive eggs because they had more Omega-3, but decided to use cheaper eggs and just take a little more fish oil. What date did I change over? First, I need the NDB_No of the expensive eggs:

sqlite> select NDB_No, Long_Desc from food_des where Long_Desc like '%egg%' and Long_Desc like '%organic%';
99010|Egg,yolk,raw,fresh,organic,brown,omega3,trader joe's
99011|Egg,whole,cooked,hard-boiled,organic,brn,omega3,trader joe's

I want to see just the raw yolks, and I want to query the "mealfoods" table, which holds the exact foods and quantities for each meal. I know mealfoods has a "meal_date" in addition to the NDB_No, so here's how I see the latest date I ate the expensive egg yolks:

sqlite> select max(meal_date) from mealfoods where NDB_No = 99010;

Here's something you frugalvores might be interested in. I added a table called "cost":

sqlite> .schema cost
CREATE TABLE cost (NDB_No int primary key, cost real, store text);

The actual cost column is dollars per 100 grams of food and after I figure out the NDB_No for the food I set it with an insert command like this:

sqlite> select NDB_No, Long_Desc from food_des where Long_Desc like '%romaine%';
11251|Lettuce, cos or romaine, raw (Lactuca sativa var. logifolia)
sqlite> insert into cost values (11251, 0.25841296, 'Smart & Final');

This says that 100 grams of romaine lettuce costs about $0.25 when bought from Smart & Final. Here's how I find my actual cost per day for the last week:

sqlite> select meal_date, round(sum(mhectograms * cost),2) from mealfoods natural join food_des natural join cost group by meal_date order by meal_date desc limit 7;

A "natural join" means you don't have to specify the columns you are using for a join between tables, and the database has been set up so that natural joins will work most of the time to get useful results.

If I want to see the previous query every day but it is too much of a drag to type it in every time, I can create a view:

sqlite> create view weeklycost as select meal_date, round(sum(mhectograms * cost),2) from mealfoods natural join food_des natural join cost group by meal_date order by meal_date desc limit 7;
sqlite> select * from weeklycost;

Here's how I find which of the foods I buy is the cheapest source of copper (see below for how I know the copper column is named "CU"):

sqlite> select Shrt_Desc, cost / CU as val from cost natural join food_des where val is not null order by val limit 1;
Seeds, sunflower seed kernels, dried (helianthus annuus)|0.332843857072932

In the same vein, although not joinable to the other tables because it allows non-food items, if I need a shopping list:

sqlite> .schema shopping
CREATE TABLE shopping (n integer primary key, item text);
sqlite> insert into shopping values (null, 'radishes');
sqlite> insert into shopping values (null, 'salmon');
sqlite> select * from shopping;

Now a food question relevant to ketogenic diets: How do the lettuces rate for maximum potassium per gram of non-fiber carb?

sqlite> select NDB_No, Shrt_Desc, round(K / CHO_NONFIB) as val from food_des where Long_Desc like 'Lettuce%' order by val desc;
11250|Lettuce,butterhead (incl boston&bibb types),raw|211.0
11251|Lettuce, cos or romaine, raw (lactuca sativa var. logifolia)|208.0
11257|Lettuce, red leaf, raw (lactuca sativa var. crispa)|138.0
11253|Lettuce, green leaf, raw (lactuca sativa var. crispa)|124.0
11252|Lettuce,iceberg (incl crisphead types),raw|80.0

I've been experimenting with coconut oil on my ketogenic diet. Sometimes I feel I've been having too much and I cut back and other times I feel I could use more, so I increase it, but I do not have any idea what amount of coconut oil per meal has seemed satisfactory most of the time. I know the NDB_No is 4047, so what I am going to do is to make a list of how much coconut oil I had per meal for the various days and then count the occurences of each amount of coconut oil, to see what were my most popular amounts of coconut oil per meal. The first column is ounces of coconut oil and the second column is a count of the days when I had that much. I can see that 1.1 ounces per meal (a little over 2 tablespoons) was my most common dosage per meal:

sqlite> select val, count(meal_date) as ct from (select meal_date, round(sum(mhectograms / .2835 / 3.0),1) as val from mealfoods where NDB_No = 4047 group by meal_date order by val) group by val order by ct;

If you're interested in Omega-3 fatty acids, here's a view that does the computation that NUT uses, and then we can answer the question "What (supposedly) was the percentage of Omega-6 in my tissue phospholipids during the summer of 2014?"

sqlite> .schema n6hufacalc
CREATE VIEW n6hufacalc as select meal_id, 100.0 / (1.0 + 0.0441 / (900 * SHORT6 / ENERC_KCAL) * (1.0 + (900 * SHORT3 / ENERC_KCAL) / 0.0555 + (900 * LONG3 / ENERC_KCAL) / 0.005 + (900 * (FASAT + FAMS + FAPU - SHORT6 - LONG6 - SHORT3 - LONG3) / ENERC_KCAL) / 5.0 + (900 * SHORT6 / ENERC_KCAL) / 0.175)) + 100.0 / (1.0 + 0.7 / (900 * LONG6 / ENERC_KCAL) * (1.0 + (900 * LONG3 / ENERC_KCAL) / 3.0)) as n6hufa from meals;
sqlite> select round(avg(n6hufa)) from n6hufacalc where meal_id between 2014060000 and 2014090000;

One of the users wanted a food journal in a particular format. It looked simple but the SQL was surprisingly complicated:

qlite> select id || group_concat(' ' || food) from (select cast(substr(meal_date, 5, 2) as int) || '/' || cast(substr(meal_date, 7) as int) || ' ' || case when meal = 1 then 'breakfast:' when meal = 2 then 'lunch:' else 'dinner:' end as id, token1 || ' ' || case when commapos = 0 then token2 else substr(token2, 1, commapos - 1) end as food from (select meal_date, meal, token1, token2, instr(token2, ',') as commapos from (select meal_date, meal, trim(substr(Long_Desc, 1, instr(Long_Desc, ',')), ',') as token1, trim(substr(Long_Desc, instr(Long_Desc, ',')), ', ') as token2 from mealfoods natural join food_des where meal_date > 20170621))) group by id;
6/22 breakfast: Cheese cheddar, Oil coconut, Spinach raw (Spinacia oleracea), Tomatoes red, Nuts almonds, Beverages coffee, Fish sardine, Snacks pork skins, Cocoa dry powder, Oil flaxseed, Egg yolk, Chicken liver, Mushrooms brown, Artichokes (globe or french), Pork fresh, Beef ground
6/22 lunch: Cheese cheddar, Oil coconut, Brussels sprouts raw (Brassica oleracea (Gemmifera Group)), Spinach raw (Spinacia oleracea), Tomatoes red, Nuts almonds, Beverages coffee, Snacks pork skins, Cocoa dry powder, Oil flaxseed, Egg yolk, Chicken liver, Mushrooms brown, Pork fresh, Chicken broilers or fryers, Beef ground

The next query concerns how non-fiber carb has varied in my diet, but I need to explain a few technicalities first. If you compare the NUT tables to the USDA tables, you can see that NUT doesn't have the USDA's "nut_data" table which contains the nutrient values. This is because the food_des and meals tables have columns that contain the nutrient values, and these columns are named after the corresponding "Tagname" column in the table nutr_def, the nutrient definitions. For instance:

sqlite> select Tagname, NutrDesc from nutr_def where NutrDesc = 'Non-Fiber Carb';
CHO_NONFIB|Non-Fiber Carb

So, "CHO_NONFIB" is the "Non-Fiber Carb" column in both food_des and meals. The meals table contains the nutrient values for each meal; think of it as the sum of the foods in the mealfoods table grouped by each meal. But while mealfoods has a "meal_date" and "meal" column to identify a meal, the meals table has a single "meal_id" column which concatenates both meal_date and meal into a single 10-digit long integer:

sqlite> select max(meal_id) from meals;

This is meal #1 from October 7, 2014. Using integer division using whole numbers only, I can divide to get just the year and month like this:

sqlite> select max(meal_id) / 10000 from meals;

So now here's the query to answer the question "What was my average non-fiber carb intake each month?" Since I eat three meals a day and each meal is a third of a day, I need to also multiply the average by three:

sqlite> select meal_id / 10000, avg(CHO_NONFIB) * 3 from meals group by meal_id / 10000;

To tie it all together, let's join this result to the wlog table to answer the question "How did my lean mass vary with these monthly carb levels?" Because I am joining on a customized date representation, I can't use a natural join, and I have to spell out the whole syntax for joins to specify what is going to be equal to what:

sqlite> select m.meal_id / 10000, avg(m.CHO_NONFIB) * 3, avg(w.weight - w.weight * w.bodyfat / 100) from meals m join wlog w on m.meal_id / 10000 = w.wldate / 100 group by m.meal_id / 10000;
sqlite> .quit



nut.sqlite      All personal data, the USDA Nutrient Database, and Tcl scripts
updateNUT.tcl	Tcl script to create or update the NUT code in the database
nut.tcl		Tcl script to start the NUTsqlite program


Jim Jozwiak (


Copyright (C) 1996-2017 by Jim Jozwiak.




This document was created by man2html, using the manual pages.
Time: 19:56:09 GMT, June 13, 2014