Skip to content
Educora
AdvancedGrade 1024 min39 / 59

Database queries, searching and sorting

Simple and compound conditions (=, <>, <, >, <=, >=, AND, OR, NOT), the masks * and ?, evaluating a query step by step with sets, counting records and finding where a record moves after sorting — in DİM notation.

Check yourself
In this lesson you will learn
  • Write simple conditions with comparison signs and find the records that meet each one
  • Evaluate a compound query with AND, OR, NOT and brackets step by step using sets
  • Apply the masks * and ? to text fields
  • Find a record’s new position after a query and a sort

In an online shop you tick “price under 50 manat” and “rating above 4” — and out of thousands of products only a few are left. That is a query: the DBMS checks every record against the condition and shows only the ones that fit.

Every entrance exam paper has one query task: find how many records satisfy a query, which record numbers are selected, or how a record moves after sorting. The structure of tables is explained in the lesson “Databases: models, DBMS and related tables”.

Queries and simple conditions

Definition
Query

A DBMS object: a command that selects (searches for) the records meeting a condition, sorts them if needed and shows the result as a new table. A query does not change the data; it only selects.

Definition
Simple condition

Written as “field — comparison sign — value”: Math > 18, Status = “delayed”. Text values are written in quotes and compared letter by letter.

SignMeaningExample
=equal toClass = 10
<>not equal toPlatform <> 2
<less thanAge < 16
>greater thanScore > 90
<=less than or equal toPrice <= 50
>=greater than or equal toHistory >= 70
№NameMathPhysicsInformatics
1Aysel181225
2Murad252114
3Leyla121922
4Elvin202517
5Nigar91620
6Rashad231124
7Gunay152219
Table “Olympiad”: pupils’ scores in three subjects. Examples 1–3 of this lesson use this table.
Example 1. Simple conditions — sets of records

Which record numbers of the “Olympiad” table meet the condition?
1) Math > 18 2) Physics <= 16 3) Informatics <> 22 4) Math >= 18

Show solution
We check each record from top to bottom and write the numbers as a set.
1) 25, 20, 23 → {2, 4, 6}. 18 > 18 is false, so 1 is not included.
2) 12, 16, 11 → {1, 5, 6}. 16 <= 16 is true.
3) Everything except 22 → {1, 2, 4, 5, 6, 7}.
4) The boundary counts: 18, 25, 20, 23 → {1, 2, 4, 6}.

Compound conditions: AND, OR, NOT

Simple conditions are combined with logical operations — the AND, OR and NOT from the lesson “Boolean logic and logic gates”. DİM tasks write them in English: AND, OR, NOT. Once we know the set of records for each simple condition, a compound condition becomes operations on sets. M(A) is the set of numbers of the records that meet condition A.

M(A AND B) = M(A) ∩ M(B)
where:
  • M(A)numbers of the records meeting condition A
  • ∩intersection: in both sets

AND — both conditions must hold: the common numbers stay.

M(A OR B) = M(A) ∪ M(B)
where:
  • ∪union: in at least one set

OR — at least one condition must hold: the numbers are combined, without repeats.

M(NOT A) = U \ M(A)
where:
  • Uall records of the table
  • \difference: remove M(A) from U

NOT — the records that do not meet the condition stay.

Examples on the “Olympiad” table: (Math > 18) AND (Informatics >= 20) → {2, 4, 6} ∩ {1, 3, 5, 6} = {6}; (Math > 18) OR (Physics > 20) → {2, 4, 6} ∪ {2, 4, 7} = {2, 4, 6, 7}; NOT (Physics > 15) → {1, 6}. Order of operations: brackets first (from the inside out), then NOT, then AND, and OR last. DİM queries usually have brackets: start from the innermost one, and where there are none, follow the order NOT → AND → OR. The same logic works in internet search — see “Searching the internet: search engines and queries”.

  1. 1
    Split into simple conditions

    For each simple condition in the query write down its set of records.

  2. 2
    Apply NOT

    For a condition under NOT take the remaining records — or flip the sign.

  3. 3
    Open brackets from the inside

    AND → intersection, OR → union; write every intermediate result down.

  4. 4
    Read off the answer

    The final set gives the selected record numbers; the number of its elements is the number of records.

Example 2. DİM-style task: which records?

If the query
(((Math < 20) AND NOT (Physics > 18)) OR ((Informatics > 21) AND (Physics > 15)))
is applied to the “Olympiad” table, which record numbers are selected?
A) 1, 5 B) 1, 3, 5 C) 3, 5, 6 D) 1, 3, 5, 6 E) 3

Show solution
1) Math < 20 → {1, 3, 5, 7}; NOT (Physics > 18) = Physics <= 18 → {1, 5, 6}. AND → {1, 5}.
2) Informatics > 21 → {1, 3, 6}; Physics > 15 → {2, 3, 4, 5, 7}. AND → {3}.
3) OR: {1, 5} ∪ {3} = {1, 3, 5}.
Correct answer: B) 1, 3, 5.
NOT (A AND B) = (NOT A) OR (NOT B) · NOT (A OR B) = (NOT A) AND (NOT B)
where:
  • A, Bany conditions

De Morgan’s laws: when NOT goes inside the brackets, AND and OR swap.

Example 3. NOT outside: how many records?

How many records of the “Olympiad” table satisfy NOT (NOT (Math > 15) AND (Informatics < 20)) OR NOT (Physics > 20)?

Show solution
Way 1 (with sets): NOT (Math > 15) → {3, 5, 7}; Informatics < 20 → {2, 4, 7}; AND → {7}; the outer NOT → {1, 2, 3, 4, 5, 6}. NOT (Physics > 20) → {1, 3, 5, 6}. OR → {1, 2, 3, 4, 5, 6}.
Way 2 (De Morgan): NOT (NOT A AND B) = A OR NOT B, i.e. (Math > 15) OR (Informatics >= 20) → {1, 2, 4, 6} ∪ {1, 3, 5, 6} = {1, 2, 3, 4, 5, 6} — the same result.
Answer: 6 records.
Replace NOT with a comparison sign
  1. 1.NOT (Score > 45) ⇔ Score 45
  2. 2.NOT (Age >= 16) ⇔ Age 16
  3. 3.NOT (City = “Baku”) ⇔ City “Baku”
  4. 4.NOT (Price <= 20) ⇔ Price 20

Masks: * and ?

In a text field we sometimes look not for an exact value but for a mask — a pattern. A mask has two special signs: * — any number of any characters (zero included), ? — exactly one arbitrary character. In DİM notation a mask is written in quotes after an equals sign: Destination = “*n”.

MaskMeaningMatchesDoes not match
*nends with nRiverton, MapletonSandford, Oakdale
M*starts with MMilltown, MapletonRiverton
*ll*contains llMilltown, HillsideLakeside
?a*second character is aOakdale, LakesideMilltown
1??3 characters starting with 1101, 1501150, 205
№RouteDestinationPlatformStatus
1101Riverton2on time
2205Oakdale1delayed
3310Milltown3on time
4118Mapleton2delayed
5222Lakeside1on time
6407Sandford3delayed
7150Hillside2on time
8333Brighton1on time
Table “Bus station”: intercity routes (the town names are made up).
Example 4. A query with a mask

If the query ((Status = “delayed” OR Platform = 1) AND Destination = “*n*”) is applied to the “Bus station” table, how many records are selected? How would the answer change with the mask “*n”?

Show solution
1) Status = “delayed” → {2, 4, 6}; Platform = 1 → {2, 5, 8}; OR → {2, 4, 5, 6, 8}.
2) “*n*” — names containing n: Riverton, Milltown, Mapleton, Sandford, Brighton → {1, 3, 4, 6, 8}.
3) AND → {4, 6, 8} — 3 records.
4) “*n” — only names ending with n: {1, 3, 4, 8} (Sandford drops out). Then {2, 4, 5, 6, 8} ∩ {1, 3, 4, 8} = {4, 8} — 2 records.

Sorting

Definition
Sorting

Arranging records in order by the values of one or more fields. Ascending order: numbers from small to large, text in alphabetical order (A → Z), dates from earlier to later. Descending order is the reverse. Sorting does not change the records or their number, only their order.

When sorting by two fields, records are first arranged by the first field; records with equal values in the first field are then ordered by the second field. For example, Baku, Ganja, Lankaran, Shaki is an ascending list of cities. DİM’s hardest query task combines a filter and a sort:

  1. 1
    Apply the query

    Write the selected records into a new table in their original order.

  2. 2
    Note the old position

    Write down which row of this new table holds the record you need: k.

  3. 3
    Sort

    Sort the result table by the given field in ascending or descending order.

  4. 4
    Compare with the new position

    Let the new position be m: k − m > 0 means “k − m rows up”, k − m < 0 means down, k = m means unchanged.

№NameMathPhysicsChemistry
1Kamran728164
2Sabina886990
3Orkhan657771
4Fidan908558
5Tural706283
6Gunay597476
Table “Mock exam”: for Example 5.
Example 5. Filter + sort

After the query ((Math >= 70 OR Chemistry > 75) AND Physics > 65) is applied to the “Mock exam” table, the result is sorted by Chemistry in ascending order. How does Fidan’s record move?
A) 2 rows down B) 1 row up C) it does not move D) 2 rows up E) 1 row down

Show solution
1) Kamran: 72 >= 70, 81 > 65 → yes. Sabina: 88, 69 → yes. Orkhan: 65 and 71 — the bracket is false → no. Fidan: 90, 85 → yes. Tural: 70 >= 70, but Physics 62 → no. Gunay: Chemistry 76 > 75, Physics 74 → yes.
2) Result table: Kamran, Sabina, Fidan, Gunay — Fidan is in row 3 (k = 3).
3) Ascending by Chemistry: Fidan 58, Kamran 64, Gunay 76, Sabina 90 — Fidan is in row 1 (m = 1).
4) k − m = 2 > 0.
Correct answer: D) 2 rows up.
Example 6. Sorting by two fields

Records (name — class — score): Aysel — 9 — 85, Murad — 10 — 90, Leyla — 9 — 92, Elvin — 11 — 78, Nigar — 10 — 88, Rashad — 9 — 70. The table is sorted first by Class ascending, then by Score descending. In which position will Nigar be?

Show solution
1) Class 9 (score descending): Leyla 92, Aysel 85, Rashad 70 → positions 1–3.
2) Class 10: Murad 90, Nigar 88 → positions 4–5.
3) Class 11: Elvin 78 → position 6.
Answer: Nigar is 5th.
Python
rows = [('Kamran', 72, 81, 64), ('Sabina', 88, 69, 90), ('Orkhan', 65, 77, 71),
        ('Fidan', 90, 85, 58), ('Tural', 70, 62, 83), ('Gunay', 59, 74, 76)]

# query: ((Math >= 70 OR Chemistry > 75) AND Physics > 65)
result = [r for r in rows if (r[1] >= 70 or r[3] > 75) and r[2] > 65]
print('After the query:', [r[0] for r in result])

# sort by Chemistry, ascending (reverse=True would give descending)
sorted_rows = sorted(result, key=lambda r: r[3])
print('After sorting: ', [r[0] for r in sorted_rows])

k = [r[0] for r in result].index('Fidan') + 1
m = [r[0] for r in sorted_rows].index('Fidan') + 1
print('Fidan:', k, '->', m, '| rows up:', k - m)
▸ Expected output
After the query: ['Kamran', 'Sabina', 'Fidan', 'Gunay']
After sorting:  ['Fidan', 'Kamran', 'Gunay', 'Sabina']
Fidan: 3 -> 1 | rows up: 2
Example 5 in Python: AND, OR, NOT are written and, or, not in Python, and <> is written !=. Change the condition and press Run.
Interactive
Loading simulation…
Check each record against the query. Look carefully at Gunay: 90 > 90 is false.
DİM notationSQL
(A > 5) AND NOT (B = 2)WHERE a > 5 AND NOT b = 2
Platforma <> 2platform <> 2
İstiqamət = «*n»destination LIKE '%n'
Kod = «1??»code LIKE '1__'
Chemistry ascending / descendingORDER BY chemistry ASC / DESC
The same queries in SQL: masks use % instead of * and _ instead of ?. More in the SQL course lessons “WHERE: filtering rows”, “LIKE, IN, BETWEEN and IS NULL” and “ORDER BY and LIMIT: sorting and limiting”.

Key points

  • Simple condition: field — sign — value; > and < exclude the boundary, >= and <= include it, <> means “not equal”.
  • AND → intersection, OR → union, NOT → the remaining records; order: brackets, NOT, AND, OR.
  • Replace NOT with the opposite sign (NOT (x > a) ⇔ x <= a) and use De Morgan’s laws.
  • Mask: * — any number of characters (even zero), ? — exactly one; “*n” ends with n, “*n*” contains n.
  • Filter + sort: a record’s position is counted in the query’s result table and then compared with its position after sorting.

Check yourself

12 questions. Every correct answer earns XP.

1 / 12
What does the sign <> mean in a query?