Tuesday, 28 July 2026

SPARQL IF Function: Adding Conditional Logic to Queries

  

So far, we've learned how to retrieve data from RDF graphs, calculate aggregates using functions such as COUNT(), MIN(), MAX(), and AVG(), and sort results using ORDER BY.

 

But what if we want our query to make decisions?

 

For example:

·      Classify employees as Senior or Junior based on age.

·      Determine whether an employee is a High Earner.

·      Categorize employees by years of service.

·      Generate human-readable labels directly from query results.

 

This is where the SPARQL IF() function becomes useful. The IF() function works much like an if-else statement in programming languages.

 

Syntax

IF(condition, valueIfTrue, valueIfFalse)

   

If the condition evaluates to true, the first value is returned. Otherwise, the second value is returned.

 

Example 1: Classify Employees as Senior or Junior

Suppose the company considers employees aged 40 or above to be Senior employees.

 

PREFIX : <http://example.org/company/> 

SELECT ?empName ?age
       (IF(?age >= 40, "Senior", "Junior") AS ?empLevel)
WHERE { 
  ?emp a :Employee ;
       :name ?empName ;
       :age ?age  
  
}

   

Output

   

empName

age

empLevel

David Miller 

34

Junior

Emma Wilson

30

Junior

James Taylor 

32

Junior

John Smith 

55

Senior

Michael Brown

48

Senior

Sarah Johnson

42

Senior

Sophia Davis 

29

Junior

 

1. Understanding the IF Expression

The important part is:

IF(?age >= 40, "Senior", "Junior")

   

This can be read as:

 

If age is greater than or equal to 40
    return "Senior"
Else
    return "Junior"

Example 2: Categorize Employees by Salary

Suppose HR wants to identify highly compensated employees.

 

Employees earning 120,000 or more are considered High Earners.

 

PREFIX : <http://example.org/company/> 

SELECT ?empName
       (IF(?salary >= 120000, "High Earner", "Standard Earner") AS ?empLevel)
WHERE { 
  ?emp a :Employee ;
       :name ?empName ;
       :salary ?salary  
}
ORDER BY DESC(?salary)

Output

empName

empLevel

John Smith 

High Earner

Michael Brown

High Earner

Sarah Johnson

High Earner

Emma Wilson

Standard Earner

James Taylor 

Standard Earner

Sophia Davis 

Standard Earner

 

Example 3: Determine Whether an Employee Has a Manager

Notice that John Smith is the Director and does not report to anyone. We can use BOUND() together with IF().  

 

PREFIX : <http://example.org/company/> 

SELECT ?name (IF(BOUND(?manager), "Yes", "No") AS ?hasManager) 
WHERE { 
  ?employee :name ?name . 
  
  OPTIONAL { 
    ?employee :reportsTo ?manager . 
  } 
} 
ORDER BY ?name

Output

name

hasManager

David Miller 

Yes

Emma Wilson

Yes

James Taylor 

Yes

John Smith 

No

Michael Brown

Yes

Sarah Johnson

Yes

Sophia Davis 

Yes

 

This is a common pattern when working with optional relationships.

 

Example 4: Identify Long-Service Employees

Suppose employees who joined before 2020 are considered long-service employees.

 

PREFIX : <http://example.org/company/> 

SELECT ?name ?joinedOn
       (IF (?joinedOn < "2020-01-01"^^xsd:date, "Long Service", "Recent Hire") AS ?serviceCategory)
WHERE { 
  ?employee :name ?name ;
            :joinedOn ?joinedOn
  
  
}
ORDER BY ?joinedOn

   

Output

name

joinedOn 

serviceCategory

John Smith 

2010-03-15 

Long Service

Michael Brown

2014-01-22 

Long Service

Sarah Johnson

2016-07-10 

Long Service

David Miller 

2020-11-15 

Recent Hire

Emma Wilson

2021-06-01 

Recent Hire

Sophia Davis 

2022-02-10 

Recent Hire

James Taylor 

2023-01-05 

Recent Hire

 

 

Example 5: Using IF with BIND

Many developers prefer placing conditional logic inside a BIND.

 

Example 4 can be written using BIND like below.

 

PREFIX : <http://example.org/company/> 

SELECT ?name ?joinedOn ?serviceCategory
       
WHERE { 
  ?employee :name ?name ;
            :joinedOn ?joinedOn.
  
  BIND (
    IF (?joinedOn < "2020-01-01"^^xsd:date, "Long Service", "Recent Hire") AS ?serviceCategory
  )
  
}
ORDER BY ?joinedOn

   

2. Nested IF Statements

SPARQL allows IF statements to be nested. Suppose we want three age categories:

 

Age 50+ Executive

Age 40–49 Senior

Below 40 Junior

 

The general syntax for a nested IF() expression in SPARQL is:

 

IF(
    condition1,
    result1,
    IF(
        condition2,
        result2,
        IF(
            condition3,
            result3,
            defaultResult
        )
    )
)

   

This works exactly like an if else if else if else chain in programming languages.

 

Equivalent pseudocode:

 

if condition1
    return result1
else if condition2
    return result2
else if condition3
    return result3
else
    return defaultResult

Example: Employee Age Classification

 

PREFIX : <http://example.org/company/>

SELECT ?name ?age
       (
         IF(?age >= 50,
            "Executive",
            IF(?age >= 40,
               "Senior",
               IF(?age >= 30,
                  "Mid-Level",
                  "Junior"
               )
            )
         )
         AS ?level
       )
WHERE {
    ?employee :name ?name ;
              :age ?age .
}

   

Output

name

age

level

Sophia Davis 

29

Junior

Emma Wilson

30

Mid-Level

James Taylor 

32

Mid-Level

David Miller 

34

Mid-Level

Sarah Johnson

42

Senior

Michael Brown

48

Senior

John Smith 

55

Executive

 

Many developers find nested IF() expressions easier to read when used inside a BIND.

 

PREFIX : <http://example.org/company/>

SELECT ?name ?age ?level
WHERE {
    ?employee :name ?name ;
              :age ?age .

    BIND(
        IF(?age >= 50,
           "Executive",
           IF(?age >= 40,
              "Senior",
              IF(?age >= 30,
                 "Mid-Level",
                 "Junior"
              )
           )
        )
        AS ?level
    )
}

ORDER BY ?age

   

3. Formatting Recommendation

For simple conditions:

 

IF(?age >= 40, "Senior", "Junior")

   

For nested conditions, always format vertically:

 

IF(condition1,
   result1,
   IF(condition2,
      result2,
      IF(condition3,
         result3,
         defaultResult)))

   

This makes complex decision trees much easier to understand and maintain.

 

In summary, the IF() function allows conditional logic to be incorporated directly into SPARQL queries.

 

General syntax:

 

IF(condition, valueIfTrue, valueIfFalse)

   

Common use cases include:

 

·      Employee classifications

·      Salary bands

·      Service categories

·      Optional relationship handling

·      Data quality checks

·      Human-readable labels

 

When combined with BIND(), FILTER(), OPTIONAL, ORDER BY, and aggregation functions, IF() becomes a powerful tool for transforming raw RDF data into business-friendly reports and analytics.

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment