BeginnerLesson 5 of 128 min read

Views: Lists, Filters, Sorting and Search, Compiled Safely to Queries

Understand what a view in a no-code app is: a saved filter, sort and column choice over a table. Compile view definitions to safe parameterised queries, test eight views against an independent Python evaluation, and see why unknown fields are refused.

In this lesson you will

  • Define a view as data
  • Combine filters, sort and search
  • Compile a view to a safe query
  • Verify views against an independent evaluation

About 28 minutes

Different people need different lists of the same shifts

Tomás wants “open shifts this week” on the home screen, volunteers want “shifts at Hall A on weekends”, and the kitchen lead wants “full shifts, soonest first”. It is one table of shifts and many views of it. A view is a saved definition: which table, which columns, which filters, in which order, and how many rows to show. No-code tools let you build views by clicking on filter and sort menus, and the platform turns the definition into a query. Understanding that conversion explains the limits of what views can do and why they are safe: the definition can only mention fields and operators that the platform knows, and values are passed as parameters, never pasted into the query text.

The pieces are few. A filter is a field, an operator and a value, such as day on or after a date, or place equal to Hall A. Several filters are combined with AND, so each narrows the list, and groups with OR need explicit support. A sort is a field and a direction. A search is a filter that looks for text inside a field, usually case-insensitive. A limit and an offset give pages of rows. A compiler walks the definition and builds the query, checking every field name and operator against allow-lists, because names cannot be parameters and an unchecked name is the way into SQL injection, which the Back-end course explained. A view that mentions a field that does not exist is refused, which is also how a platform notices that someone deleted a field that a view depends on.

Part Example Becomes
Filter day >= 2024-03-11 WHERE day >= ?
Several filters place = Hall A, free > 0 WHERE … AND …
Sort day ascending ORDER BY day ASC
Search text contains “kitchen” WHERE LOWER(role) LIKE ?
Limit and offset page 2 of 5 LIMIT 5 OFFSET 5
import sqlite3, json, random, datetime
rng = random.Random(7)
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE shifts (id INTEGER PRIMARY KEY, day TEXT, place TEXT, role TEXT, capacity INTEGER, signed INTEGER)")
rows = []
for i in range(1, 61):
    day = datetime.date(2024, 3, 4) + datetime.timedelta(days=rng.randrange(0, 28))
    cap = rng.choice([2, 3, 4, 6]); rows.append((i, day.isoformat(), rng.choice(["Hall A", "Hall B", "Warehouse"]), rng.choice(["kitchen", "sorting", "driver", "front desk"]), cap, rng.randrange(0, cap + 1)))
db.executemany("INSERT INTO shifts VALUES (?,?,?,?,?,?)", rows)
FIELDS = {"id", "day", "place", "role", "capacity", "signed"}
OPS = {"=": "=", "!=": "!=", ">=": ">=", "<=": "<=", ">": ">", "<": "<", "contains": "LIKE"}
def compile_view(v):
    for f in v.get("columns", ["id"]) + [f["field"] for f in v.get("filters", [])] + [s["field"] for s in v.get("sort", [])]:
        if f not in FIELDS: raise ValueError("unknown field: " + str(f))
    sql, args = "SELECT " + ", ".join(v.get("columns", ["id"])) + " FROM shifts", []
    conds = []
    for f in v.get("filters", []):
        if f["op"] not in OPS: raise ValueError("unknown operator: " + str(f["op"]))
        if f["op"] == "contains": conds.append("LOWER(%s) LIKE ?" % f["field"]); args.append("%" + str(f["value"]).lower() + "%")
        else: conds.append("%s %s ?" % (f["field"], OPS[f["op"]])); args.append(f["value"])
    if v.get("open"): conds.append("signed < capacity")                                    # a computed filter: open places
    if conds: sql += " WHERE " + " AND ".join(conds)
    if v.get("sort"): sql += " ORDER BY " + ", ".join("%s %s" % (s["field"], "DESC" if s.get("desc") else "ASC") for s in v["sort"]) + ", id"
    else: sql += " ORDER BY id"
    if "limit" in v: sql += " LIMIT %d OFFSET %d" % (int(v["limit"]), int(v.get("offset", 0)))
    return sql, args
views = {
  "open this week": {"columns": ["id", "day"], "filters": [{"field": "day", "op": ">=", "value": "2024-03-11"}, {"field": "day", "op": "<=", "value": "2024-03-17"}], "open": True, "sort": [{"field": "day"}]},
  "Hall A shifts": {"columns": ["id"], "filters": [{"field": "place", "op": "=", "value": "Hall A"}]},
  "full shifts, soonest first": {"columns": ["id", "day"], "filters": [{"field": "signed", "op": ">=", "value": 2}], "sort": [{"field": "day"}], "limit": 5},
  "kitchen search": {"columns": ["id"], "filters": [{"field": "role", "op": "contains", "value": "KITCHEN"}]},
  "big shifts, biggest first": {"columns": ["id", "capacity"], "filters": [{"field": "capacity", "op": ">=", "value": 6}], "sort": [{"field": "capacity", "desc": True}, {"field": "day"}], "limit": 4},
  "page 2 of all": {"columns": ["id"], "limit": 10, "offset": 10},
  "empty result": {"columns": ["id"], "filters": [{"field": "place", "op": "=", "value": "Moon"}]},
}
results = {}
for name, v in views.items():
    sql, args = compile_view(v); got = db.execute(sql, args).fetchall(); results[name] = [list(r) for r in got]
    print(name.ljust(28), len(got), "rows | ", sql, args)
bad = {}
for label, v in {"unknown field": {"columns": ["id", "password"]}, "injection in a field name": {"columns": ["id"], "filters": [{"field": "place; DROP TABLE shifts", "op": "=", "value": "x"}]}, "unknown operator": {"columns": ["id"], "filters": [{"field": "place", "op": "LIKE '%' OR 1=1 --", "value": "x"}]}}.items():
    try: compile_view(v)
    except ValueError as e: bad[label] = str(e)
print("refused:", bad)
print("a value that looks like SQL stays a value:", db.execute(*compile_view({"columns": ["id"], "filters": [{"field": "place", "op": "=", "value": "Hall A' OR '1'='1"}]})).fetchall())
print("DATA " + json.dumps({"rows": rows, "views": views, "results": results, "bad": bad}))
open this week               10 rows |  SELECT id, day FROM shifts WHERE day >= ? AND day <= ? AND signed < capacity ORDER BY day ASC, id ['2024-03-11', '2024-03-17']
Hall A shifts                24 rows |  SELECT id FROM shifts WHERE place = ? ORDER BY id ['Hall A']
full shifts, soonest first   5 rows |  SELECT id, day FROM shifts WHERE signed >= ? ORDER BY day ASC, id LIMIT 5 OFFSET 0 [2]
kitchen search               13 rows |  SELECT id FROM shifts WHERE LOWER(role) LIKE ? ORDER BY id ['%kitchen%']
big shifts, biggest first    4 rows |  SELECT id, capacity FROM shifts WHERE capacity >= ? ORDER BY capacity DESC, day ASC, id LIMIT 4 OFFSET 0 [6]
page 2 of all                10 rows |  SELECT id FROM shifts ORDER BY id LIMIT 10 OFFSET 10 []
empty result                 0 rows |  SELECT id FROM shifts WHERE place = ? ORDER BY id ['Moon']
refused: {'unknown field': 'unknown field: password', 'injection in a field name': 'unknown field: place; DROP TABLE shifts', 'unknown operator': "unknown operator: LIKE '%' OR 1=1 --"}
a value that looks like SQL stays a value: []

The program generated 60 shifts for four weeks, with a place, a role, a capacity and the number of people signed up, and defined seven views as data. The compiler turned each into a query with placeholders, as the output block shows, and the database returned: “open this week” 10 rows; “Hall A shifts” 24 rows; “full shifts, soonest first” 5 rows; “kitchen search” 13 rows; “big shifts, biggest first” 4 rows; “page 2 of all” 10 rows; “empty result” 0 rows. The first view combines a date range with a computed condition, places still open, which a platform usually offers as a formula filter, and sorts by day. The search view finds the role “kitchen” with a search for “KITCHEN”, because the compiler lowers the case of both sides, and the paging view takes rows 11 to 20, as an offset of 10 and a limit of 10 does.

Three views were refused on purpose. A column called password does not exist, so the compiler stopped with “unknown field: password” before any query ran. A filter whose field name contains “; DROP TABLE shifts” and an operator that carries SQL text were refused by the allow-lists, and nothing reached the database. A value that looks like SQL, “Hall A’ OR ‘1’=’1”, is allowed, because values are always passed as parameters and treated as plain text, so it simply matches no place and returns an empty list. This is the difference between names, which are checked against a list, and values, which are parameters. A no-code platform does the same inside, and the practical consequence for you is that renaming or deleting a field can break the views that use it, so check them afterwards.

Independent check: for every one of the seven views, the rows were also selected by a Python function that filters, sorts and slices the list of 60 rows directly, with no SQL, using only the definition of the view. The rows returned agree for every view, in the same order, including the descending sort with a tie-break by day and the page that starts at offset 10. The tie-break matters: the compiler adds the id as a last sort key, so that views return rows in a stable order and a page boundary cannot repeat or lose a row between page loads.

Check by hand: the page view asks for 10 rows starting after the first 10, so ids 11 to 20 in order, and there are 60 rows, so 10 are returned. The empty result for the place “Moon” has no rows at all, which is a valid and useful outcome, and a good view tells the user so instead of showing a blank.

Views are not security

A view that hides rows is a convenience, and anyone who can reach the table can ask for other rows. Control access with permissions, as lesson 7 shows, not with filters.

Name views by the question they answer

“Open shifts this week” tells a volunteer what they will find. Keep few views per screen, and delete the ones nobody uses.

About this course

No-code platforms, plans and limits change often, so the lessons describe categories of tools with generic names and you must check each vendor’s current website. The ideas of this course, data tables, forms, views, automations and permissions, are what the tools implement, so the lesson reproduces them in small programs, run in Python 3.13 or Node.js 22 on sample data, with a second independent calculation.

Practice

Define a view for shifts in the next 7 days with free places at Hall B, sorted by day. Add an OR group to the definition and extend the compiler. Predict how many rows your view returns before you run it.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is a view?

  1. A new table
  2. A saved filter, sort and column choice over a table
  3. A permission
  4. A backup

Different lists of the same data.

Why are field names checked against an allow-list?

  1. Names cannot be parameters, and unchecked names allow SQL injection
  2. To make queries faster
  3. Because SQL is case sensitive
  4. To translate names

Values are parameters; names are checked.

Why add the id as a last sort key?

  1. So that order and pages are stable
  2. To save space
  3. To hide ids
  4. To make it slower

No repeats or losses between pages.

What does a computed filter such as signed < capacity do?

  1. Counts the table
  2. Deletes rows
  3. Sorts rows
  4. Compares two fields of the same row

Open places.

Why evaluate the views a second time in Python?

  1. To avoid SQL
  2. It is faster
  3. It is required
  4. To confirm the compiler and the data agree

An independent check.

Summary

  • A view is a definition: table, columns, filters, sort, limit.
  • A compiler builds a safe query: names from an allow-list, values as parameters.
  • Stable sort keys make paging reliable.
  • Views are conveniences, not security.

Next lesson

Lesson 6 covers automations.

Questions

Can a view change data?

Usually a view only shows data, and some platforms let you edit records in it. Permissions still decide what you may change.

What is a view of grouped data?

A summary such as shifts per place. The platform groups the rows and shows counts or sums. Lesson 10 builds such reports.

Why did my view stop working?

Often because a field it uses was renamed or deleted. Check the view's filters and sorts after you change the table.

Progress is saved in this browser.