SQL Subqueries in FileMaker

I’ve had some small pre-FileMaker experience with SQL and had it in my head that subqueries work in the FROM clause.  They do in MySQL etc, so I was frustrated when I couldn’t get that to work in FileMaker’s SQL as it’s really needed in some cases.

In a current project we have a case where there is a relationship from Contacts to Loans and we wanted to see the total Loan amount from the Contact context.  However, Contacts can be associated with a Loan using multiple roles, and we only want to have the Loan amount counted once for the Contact, otherwise the total will seem inflated.  To further complicate this, the Portal is filtered, and we want to see the filtering reflected in the total.  This, I thought was a job for SQL…

I first thought some kind of DISTINCT statement would allow me to just summarize the amount once per loan, but you can only apply DISTINCT to the field you want Summed.  For example,

SELECT SUM ( DISTINCT “Loan Amount” )

But this won’t work, because the Loan Amount may not be unique across Loans!

I can do this:

SELECT DISTINCT “LoanID”, SUM ( “LoanAmount” )

but that gives me the first Loan Number and Amount, not a total I can use.  If I add GROUP BY I get a little closer:

SELECT DISTINCT “LoanID”, SUM ( “LoanAmount” ) FROM Loans GROUP BY “LoanID”

but that gives me a list like this:

  • 120225 100,000
  • 120226 200,000

They’re distinct amounts, but I still need to parse out the second column and sum the amounts.  I think “No problem, this is a sub query and I know how to do that.”  And try to get this to work:

SELECT SUM ( “Amount” ) FROM ( SELECT DISTINCT “LoanID” As Number, “Loan Amount” As Amount FROM LOANS )

but couldn’t get that to work, and indeed it looks like that syntax is not supported in FM SQL.  I came up with a clever tail custom function to total the columns from my GROUP BY query that worked…and began the subtle fear of knowing that someday that 49,999 recursion limit would be hit

After leaving it for a bit I looked at the ODBC guide again and noted that indeed subqueries are supported, but only in the WHERE clause.  After letting that sink in I realized that I could easily get the result I wanted from a single query:

SELECT SUM ( “LoanAmount” ) FROM Loans WHERE “LoanID” IN ( SELECT DISTINCT “LoanID” FROM Loans )

and voila!  Probably 101 for real SQL folks, but I was pleased and have found references and docs on subqueries in FMSQL scarce.  Powerful stuff and no recursion limit!

Featured Posts

Follow Along

Stay up to date with the latest news & examples from SeedCode

10 Comments

  • So glad I revisited this post. I was digging into some sub queries today and it made my head hurt for a few. This totally got me on track! Thank you Jason for your post and all the people who commented. Cheers!

  • Hey Jason,
    Awesome post! Subqueries were definitely something I didn’t know where possible until recently and I’m glad you could bring some light into how awesome they are!

    Here’s an example of where I used a subquery to get a weighted average in one step.

    Let(
    [
    theyear = 2013 ;
    data = ExecuteSQL( "

    SELECT VolumePlan * PricePlan,
    (SELECT Sum(VolumePlan) from PlanData where "Year" = ? )

    from PlanData
    Where
    "Year" = ?
    and VolumePlan 0 and VolumePlan IS NOT NULL and PricePlan IS NOT NULL"

    ;"/" ; "+"

    ;
    theyear ;
    theyear
    ) ;

    math = Evaluate( data )
    ] ;

    math

    )

    The ExecuteSQL is returning something that looks like 5/15+4/15+5/15+1/25 and then the Evaluate function is actually doing the math. The subquery needs the same logic as the main query, so the “?” parameters are duplicated. Saves having to run two queries!

    • Jason Young

      Very cool, so you can nest sub-queries as columns. I certainly didn’t know that, so thanks so much for sharing! Also, very clever building an actual expression as your result! “Hacking” those delimiters is something I need to play around with for sure!

  • Bob

    I don’t know jack squat about FM SQL, but am wondering if there is a missing close quote in the final parenthetical.

    • Jason Young

      Hi Bob,

      Right, good eye! Actually the starting quote on the sub-query was wrong. I corrected.

      Thanks!

  • Nice stuff, Jason!

    One other nice thing about this technique: In FQL benchmark tests, we found that queries using a subquery in the WHERE clause like this typically run faster than equivalent queries constructed using an INNER JOIN — often *much* faster.

    An added bonus: To me at least, your subquery technique also reads better than an equivalent JOIN query, since it pushes complexity to the WHERE clause, and streamlines the main FROM and SELECT clauses. All good…

    • Jason Young

      Hi Brian,
      Thanks! although referring to this as “my” technique does make me smile.
      I’ve read on various non FM SQL posts that the way WHEREs are handled is more optimized than in the other clauses and that’s why you have a sizable group insisting that Implicit Joins (relationship done in the WHERE clause) are faster than doing the more familiar (to me at least) explicit Joins that are done in the FROM clause. Your benchmarks seem to back this up. Benchmark testing on this stuff both compared to traditional FileMaker and within FQL itself will hopefully become more available. I’ve got it on my list to run some, but need that 8th day in the week!

  • Jason,
    thanks for posting this. There have been many times where I could have used subqueries, and I thought they were not possible. Generally I would resort to separate queries. I wonder if you could have also used a summary field in a filtered portal. In this case, the summary field would be in the loans table, and be a total of the loan amount. Then place the summary field in a hidden portal in the contact context and using the same filtering as the main loans portal.

    • Jason Young

      Hi Darren,
      Thanks and glad you liked that post. Right, I’ve used that technique and it’s a great one. That was my first choice here, but I couldn’t get it to work. I’m not sure why that works in some cases and not others, but the relationship is two “jumps” away and that may have something to do with it. Although I am in my infatuation stage with ExecuteSQL, I’ll go with a FileMaker technique if it’s faster!

Leave a Reply

Your email address will not be published. Required fields are marked *

Check out some of our other posts ...

New Week Views in DayBack for FileMaker

You can now expand DayBack’s week views to show two or three weeks at a time. We’ve been using this internally in beta mode for a few weeks, and it’s very helpful to see what’s coming up next week while navigating this week’s work. Find tips on how to work with these new views on the DayBack blog.

To-Do Lists in FileMaker – New in DayBack Calendar

Now create and manage FileMaker to-do lists directly from the Unscheduled Items sidebar in DayBack Calendar. Our latest extension brings to-do behavior to any FileMaker table. Like unscheduled items, this behavior is based on a new checkbox field in your table, so some or all of your records in the table can be treated as to-dos. Mark your to-do’s done as you complete them, or drag them into the calendar to schedule time to work on them. See it in action here: Customize Your To-Do Lists This extension was designed to be pretty a scaffold onto which you could build your own, more specific to-do behaviors by customizing the action itself or the FileMaker scripts tha manipulate events. Here are some ideas to get you started. Add To-Do Lists to Your FileMaker Calendar If you haven’t already enabled the unscheduled sidebar along DayBack’s right edge, you can learn how to turn that on here: unscheduled items in DayBack. Then, download the custom action and learn how to configure it here: To-Do Lists in DayBack Calendar.

Improved Resource Selection

We’ve made some big changes to how you filter and assign resources when editing events in DayBack. These changes will make it much easier to work with large numbers of resources, especially for folks assigning multiple resources to the same event. Watch a video of the new behaviors and learn more here: Adding Multiple Resources to an Item. If you haven’t looked at your resource field mapping in a while, here is how you set that up: Mapping the Resource Field in FileMaker. Please get in touch if you have any questions about this; we’re here to help.

Suggesting Appointment Slots

Show Available Slots that Match Multiple Criteria Schedulers often look for gaps in their schedules to find the open resources for each opportunity. But sometimes, gaps don’t tell the whole story. You may have invisible criteria like skill-matching, cleaning requirements, or multiple resources to schedule at once. Or you may be on the phone with an opportunity and must suggest available times as quickly as possible. In these cases, DayBack can suggest the best slots that match all of your requirements. Scheduling Criteria Are Often Invisible In the movie above, schedulers can see openings for the two technicians, but they can’t easily see if the required rooms and equipment are free at the same time. While DayBack can show different types of resources simultaneously, as the number of criteria increases, it can be hard for schedulers to see everything at once and still make good decisions. Our customers often have rules that constrain when an otherwise open slot can be scheduled. Here are some of the invisible criteria we’ve built out for customers: Because DayBack is highly scriptable, it can scrub open slots against a variety of criteria to render just the slots that fit all your requirements. When multiple slots match, DayBack can even rank them so you can present the most ideal slots to your clients first. You Have to *See* Slots in Context to Make the Best Decisions Many scheduling apps present possible appointments as a list of dates and times. Without showing more information about each slot, schedulers can book days too tightly, always suggest the same providers first, or create huge gaps in some provider’s schedules. Ranking slots can help, but we’ve found that highlighting ideal slots alongside existing appointments gives schedulers the information they need to make the best decisions. We’ve seen schedulers quickly offer to split appointments or to slightly change services when they see available slots in the context of other appointments, trainings, vacations, and breaks. Getting Started We customize the recommendation of slots for each deployment as part of DayBack’s implementation packages. Please get in touch if you think DayBack could make a big impact on your team.

COMPANY

FOLLOW ALONG

Stay up to date with the latest news & examples from SeedCode

© 2024 SeedCode, Inc.