Home > Articles > Data

Client Dataset Basics

This chapter is from the book

This chapter is from the book

Filters and Ranges

Filters and ranges provide a means of limiting the amount of data that is visible in the dataset, similar to a WHERE clause in a SQL statement. The main difference between filters, ranges, and the WHERE clause is that when you apply a filter or a range, it does not physically change which data is contained in the dataset. It only limits the amount of data that you can see at any given time.


Ranges are useful when the data that you want to limit yourself to is stored in a consecutive sequence of records. For example, say a dataset contains the data shown in Table 3.4.

Table 3.4 Sample Data for Ranges and Filters






Bill Peterson




Frank Smith




Sarah Johnson




John Doe




Paula Wallace



The data in this much-abbreviated table is indexed by birthday. Ranges can only be used when there is an active index on the dataset.

Assume that you want to see all employees who were born between 1960 and 1970. Because the data is indexed by birthday, you could apply a range to the dataset, like this:

ClientDataSet1.SetRange(['1/1/1960'], ['12/31/1970']);

Ranges are inclusive, meaning that the endpoints of the range are included within the range. In the preceding example, employees who were born on either January 1, 1960 or December 31, 1970 are included in the range.

To remove the range, simply call CancelRange, like this:



Unlike ranges, filters do not require an index to be set before applying them. Client dataset filters are powerful, offering many SQL-like capabilities, and a few options that are not even supported by SQL. Tables 3.5–3.10 list the various functions and operators available for use in a filter.

Table 3.5 Filter Comparison Operators





Equality test

Name = 'John Smith'


Inequality test

ID <> 100


Less than

Birthday < '1/1/1980'


Greater than

Birthday > '12/31/1960'


Less than or equal to

Salary <= 80000


Greater than or equal to

Salary >= 40000


Empty string field (not used to test for NULL values)

Name = BLANK


Test for NULL value

Birthday IS NULL


Test for non-NULL value

Birthday IS NOT NULL

Table 3.6 Filter Logical Operators




(Name = 'John Smith') and (Birthday = '5/16/1964')


(Name = 'John Smith') or (Name = 'Julie Mason')


Not (Name = 'John Smith')

Table 3.7 Filter Arithmetic Operators





Addition. Can be used with numbers, strings, or dates/times.

Birthday + 30 < '1/1/1960' Name + 'X' = 'SmithX' Salary + 10000 = 100000

Subtraction. Can be used with numbers or dates/times.

Birthday - 30 > '1/1/1960' Salary - 10000 > 40000


Multiplication. Can be used with numbers only.

Salary * 0.10 > 5000


Division. Can be used with numbers only.

Salary / 10 > 5000

Table 3.8 Filter String Functions






Upper(Name) = 'JOHN SMITH'



Lower(Name) = 'john smith'


Return a portion of a string

SubString(Name,6) = 'Smith' SubString(Name,1,4) = 'John'


Trim leading and trailing characters from a string

Trim(Name) Trim(Name, '.')


Trim leading characters from a string

TrimLeft(Name) TrimLeft(Name, '.')


Trim trailing characters from a string

TrimRight(Name) TrimRight(Name, '.')

Table 3.9 Filter Date/Time Functions





Returns the year portion of a date value.

Year(Birthday) = 1970


Returns the month portion of a date value.

Month(Birthday) = 1


Returns the day portion of a date value.

Day(Birthday) = 15


Returns the hour portion of a time value in 24-hour format.

Hour(Appointment) = 18


Returns the minute portion of a time value.

Minute(Appointment) = 30


Returns the second portion of a time value.

Second(Appointment) = 0


Returns the current date and time.

Appointment < GetDate


Returns the date portion of a date/time value.



Returns the time portion of a date/time value.


Table 3.10 Other Filter Functions and Operators





Partial string comparison.

Name LIKE '%Smith%'


Tests for multiple values.

-Year(Birthday) IN (1960, 1970, 1980)


Partial string comparison.

Name = 'John*'

To filter a dataset, set its Filter property to the string used for filtering, and then set the Filtered property to True. For example, the following code snippet filters out all employees whose names begin with the letter M.

ClientDataSet1.Filter := 'Name LIKE ' + QuotedStr('M%');
ClientDataSet1.Filtered := True;

To later display only those employees whose names begin with the letter P, simply change the filter, like this:

ClientDataSet1.Filter := 'Name LIKE ' + QuotedStr('P%');

To remove the filter, set the Filtered property to False. You don't have to set the Filter property to an empty string to remove the filter (which means that you can toggle the most recent filter on and off by switching the value of Filtered from True to False).

You can apply more advanced filter criteria by handling the dataset's OnFilterRecord event (instead of setting the Filter property). For example, say that you want to filter out all employees whose last names sound like Smith. This would include Smith, Smythe, and possibly others. Assuming that you have a Soundex function available, you could write a filter method like the following:

procedure TForm1.ClientDataSet1FilterRecord(DataSet: TDataSet;
 var Accept: Boolean);
 Accept := Soundex(DataSet.FieldByName('LastName').AsString) =

If you set the Accept parameter to True, the record is included in the filter. If you set Accept to False, the record is hidden.

After you set up an OnFilterRecord event handler, you can simply set TClientDataSet.Filtered to True. You don't need to set the Filter property at all.

The following example demonstrates different filter and range techniques.

Listing 3.4 contains the source code for the main form.

Listing 3.4 RangeFilter—MainForm.pas

unit MainForm;


 SysUtils, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls,
 DB, DBClient, QExtCtrls, QGrids, QDBGrids;

 TfrmMain = class(TForm)
 DataSource1: TDataSource;
 pnlClient: TPanel;
 pnlBottom: TPanel;
 btnFilter: TButton;
 btnRange: TButton;
 DBGrid1: TDBGrid;
 ClientDataSet1: TClientDataSet;
 btnClearRange: TButton;
 btnClearFilter: TButton;
 procedure FormCreate(Sender: TObject);
 procedure btnFilterClick(Sender: TObject);
 procedure btnRangeClick(Sender: TObject);
 procedure btnClearRangeClick(Sender: TObject);
 procedure btnClearFilterClick(Sender: TObject);
 { Private declarations }
 { Public declarations }

 frmMain: TfrmMain;


uses FilterForm, RangeForm;

{$R *.xfm}

procedure TfrmMain.FormCreate(Sender: TObject);

 ClientDataSet1.AddIndex('bySalary', 'Salary', []);
 ClientDataSet1.IndexName := 'bySalary';

procedure TfrmMain.btnFilterClick(Sender: TObject);
 frmFilter: TfrmFilter;
 frmFilter := TfrmFilter.Create(nil);
 if frmFilter.ShowModal = mrOk then begin
  ClientDataSet1.Filter := frmFilter.Filter;
  ClientDataSet1.Filtered := True;

procedure TfrmMain.btnClearFilterClick(Sender: TObject);
 ClientDataSet1.Filtered := False;

procedure TfrmMain.btnRangeClick(Sender: TObject);
 frmRange: TfrmRange;
 frmRange := TfrmRange.Create(nil);
 if frmRange.ShowModal = mrOk then
  ClientDataSet1.SetRange([frmRange.LowValue], [frmRange.HighValue]);

procedure TfrmMain.btnClearRangeClick(Sender: TObject);


As you can see, the main form loads the employee dataset from a disk, creates an index on the Salary field, and makes the index active. It then enables the user to apply a range, a filter, or both to the dataset.

Listing 3.5 contains the source code for the filter form. The filter form is a simple form that enables the user to select the field on which to filter, and to enter a value on which to filter.

Listing 3.5 RangeFilter—FilterForm.pas

unit FilterForm;


 SysUtils, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls,

 TfrmFilter = class(TForm)
 pnlClient: TPanel;
 pnlBottom: TPanel;
 Label1: TLabel;
 cbField: TComboBox;
 Label2: TLabel;
 cbRelationship: TComboBox;
 Label3: TLabel;
 ecValue: TEdit;
 btnOk: TButton;
 btnCancel: TButton;
 function GetFilter: string;
 { Private declarations }
 { Public declarations }
 property Filter: string read GetFilter;


{$R *.xfm}

{ TfrmFilter }

function TfrmFilter.GetFilter: string;
 Result := Format('%s %s ''%s''',
 [cbField.Text, cbRelationship.Text, ecValue.Text]);


The only interesting code in this form is the GetFilter function, which simply bundles the values of the three input controls into a filter string and returns it to the main application.

Listing 3.6 contains the source code for the range form. The range form prompts the user for a lower and an upper salary limit.

Listing 3.6 RangeFilter—RangeForm.pas

unit RangeForm;


 SysUtils, Classes, QGraphics, QControls, QForms, QDialogs, QExtCtrls,

 TfrmRange = class(TForm)
 pnlClient: TPanel;
 pnlBottom: TPanel;
 Label1: TLabel;
 Label2: TLabel;
 ecLower: TEdit;
 ecUpper: TEdit;
 btnOk: TButton;
 btnCancel: TButton;
 procedure btnOkClick(Sender: TObject);
 function GetHighValue: Double;
 function GetLowValue: Double;
 { Private declarations }
 { Public declarations }
 property LowValue: Double read GetLowValue;
 property HighValue: Double read GetHighValue;


{$R *.xfm}

{ TfrmRange }

function TfrmRange.GetHighValue: Double;
 Result := StrToFloat(ecUpper.Text);

function TfrmRange.GetLowValue: Double;
 Result := StrToFloat(ecLower.Text);

procedure TfrmRange.btnOkClick(Sender: TObject);
 LowValue: Double;
 HighValue: Double;
 LowValue := StrToFloat(ecLower.Text);
 HighValue := StrToFloat(ecUpper.Text);

 if LowValue > HighValue then begin
  ModalResult := mrNone;
  ShowMessage('The upper salary must be >= the lower salary');
 ModalResult := mrNone;
 ShowMessage('Both values must be a valid number');


Figure 3.8 shows the RangeFilter application in operation.

Figure 3.8 RangeFilter applies both ranges and filters to a dataset.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020