Unit-6: Relational Languages
Table of Contents
Tuple Relational Calculus (TRC)
Tuple Relational Calculus (TRC) is a non-procedural query language for relational databases. Unlike Relational Algebra, which specifies how to retrieve data, TRC specifies what data to retrieve without detailing the steps. It uses tuple variables that range over tuples (rows) of relations.
Key Concepts of TRC
- Tuple Variables: Variables that represent a tuple (row) in a relation. For example,
Tcould represent a tuple from theStudentrelation. - Domain Variables: Variables that represent components (attributes) of a tuple. For example,
T.Namerefers to the 'Name' attribute of tupleT. - Atomic Formulas: Basic conditions that can be true or false. These include:
R(T): TupleTbelongs to relationR.T.A op U.B: AttributeAof tupleTis compared with attributeBof tupleUusing an operator (=,<,>,<=,>=,!=).T.A op constant: AttributeAof tupleTis compared with a constant.
- Logical Connectives: Used to combine atomic formulas:
AND(∧),OR(∨),NOT(¬). - Quantifiers:
- Existential Quantifier (∃): "There exists" or "for some".
(∃T) (P(T))means there exists at least one tupleTfor which conditionP(T)is true. - Universal Quantifier (∀): "For all".
(∀T) (P(T))means for all tuplesT, conditionP(T)is true.
- Existential Quantifier (∃): "There exists" or "for some".
General Form of a TRC Query
{ T | P(T) }
This reads as: "The set of all tuplesTsuch that predicateP(T)is true."
TRC Examples
- Find all students' names:
LetStudent(ID, Name, Major)be a relation.{ T.Name | Student(T) } - Find the names of students majoring in 'Computer Science':
{ T.Name | Student(T) AND T.Major = 'Computer Science' } - Find the names of students who have enrolled in at least one course:
LetEnrolls(StudentID, CourseID)be a relation.{ S.Name | Student(S) AND (∃E) (Enrolls(E) AND S.ID = E.StudentID) }
Exam Notes
- TRC is considered tuple-oriented because variables represent entire tuples.
- It is theoretically equivalent in expressive power to Relational Algebra and Domain Relational Calculus.
Domain Relational Calculus (DRC)
Domain Relational Calculus (DRC) is another non-procedural query language, similar to TRC, but its variables range over the domains of attributes rather than entire tuples. It specifies a predicate that the desired attribute values must satisfy.
Key Concepts of DRC
- Domain Variables: Variables that represent individual values from the domain of an attribute. For example,
ID,Name,Majorcould be domain variables. - Atomic Formulas: Similar to TRC, but involving domain variables directly:
R(v1, v2, ..., vn): The valuesv1, v2, ..., vnform a tuple in relationR.v1 op v2orv op constant: Comparisons between domain variables or a variable and a constant.
- Logical Connectives and Quantifiers: Same as in TRC (
AND,OR,NOT,∃,∀).
General Form of a DRC Query
{ v1, v2, ..., vn | P(v1, v2, ..., vn) }
This reads as: "The set of all tuples of values(v1, v2, ..., vn)such that predicateP(v1, v2, ..., vn)is true."
DRC Examples
- Find all students' names:
LetStudent(ID, Name, Major)be a relation.{ N | (∃I, M) (Student(I, N, M)) } - Find the names of students majoring in 'Computer Science':
{ N | (∃I) (Student(I, N, 'Computer Science')) } - Find the names of students who have enrolled in at least one course:
LetEnrolls(StudentID, CourseID)be a relation.{ SN | (∃SI, SM, ECI, ESID) (Student(SI, SN, SM) AND Enrolls(ESID, ECI) AND SI = ESID) }
Comparison: TRC vs. DRC
| Feature | Tuple Relational Calculus (TRC) | Domain Relational Calculus (DRC) |
|---|---|---|
| Variable Type | Tuple variables (range over tuples) | Domain variables (range over attribute values) |
| Query Focus | Specifies conditions on tuples | Specifies conditions on attribute values |
| Syntax Example | { T.Name | Student(T) AND T.Major = 'CS' } | { N | (∃I) (Student(I, N, 'CS')) } |
| Complexity | Can be more intuitive for tuple-level operations | Can be more direct for attribute-level operations |
Query by Example (QBE)
Query by Example (QBE) is a visual, two-dimensional query language developed by IBM. It allows users to formulate queries by providing an example of the desired result, primarily by filling in skeleton tables displayed on a screen. It's user-friendly and often used in graphical database interfaces.
Key Concepts of QBE
- Skeleton Tables: Users interact with blank table structures (schemas) for relations.
- Example Elements: Variables represented by an underscore followed by a name (e.g.,
_NAME,_ID). These are used to link conditions across tables or to specify which columns to print. - Constant Elements: Actual values used for selection criteria (e.g.,
'Computer Science'). - Condition Box: A separate area where complex conditions involving multiple attributes or aggregate functions can be specified.
- Operators: Keywords used to specify actions. Common operators include:
P.(Print): Indicates the attributes to be displayed in the result.I.(Insert): For inserting new tuples.D.(Delete): For deleting existing tuples.U.(Update): For modifying existing tuples.AND,OR, comparison operators (<,>,=, etc.).
QBE Examples
Assume relations: STUDENT(ID, Name, Major, Age) and COURSE(C_ID, C_Name, Credits) and ENROLLS(S_ID, C_ID, Grade).
- Find the names and majors of all students:
STUDENT ID Name Major Age P. P. - Find the names of students majoring in 'Computer Science':
STUDENT ID Name Major Age P. 'Computer Science' - Find the IDs and names of students who have enrolled in the 'Database' course:
STUDENT ID Name Major Age P. _SID P. _SNAME COURSE C_ID C_Name Credits _CID 'Database' ENROLLS S_ID C_ID Grade _SID _CID Here,
_SIDand_CIDare example elements linking the three tables.
Exam Notes
- QBE is well-suited for interactive query interfaces due to its visual nature.
- It simplifies complex queries by allowing users to fill out tables rather than writing textual code.
Datalog
Datalog is a declarative logic programming language often used as a query language for deductive databases. It's a subset of Prolog and is particularly useful for expressing recursive queries.
Key Concepts of Datalog
- Facts: Atomic statements that are considered true, representing the extensional database (EDB). They are similar to tuples in a relational database.
- Example:
student('101', 'Alice', 'CS').
- Example:
- Rules: Horn clauses that define new relations (intensional database - IDB) based on existing facts and other rules. Rules have a head (conclusion) and a body (conditions).
- Syntax:
Head :- Body.(Read as: Head is true if Body is true). - Example:
enrolled_in_cs(Name) :- student(ID, Name, 'CS').(A student is enrolled in CS if their major is CS).
- Syntax:
- Queries: Statements that ask whether a certain fact is true or to retrieve all facts that satisfy a certain pattern.
- Syntax:
?- Query. - Example:
?- enrolled_in_cs('Alice').(Is Alice enrolled in CS?) - Example:
?- enrolled_in_cs(X).(Who is enrolled in CS? - retrieves all matching X).
- Syntax:
- Recursion: Datalog's powerful feature allows rules to refer to themselves, directly or indirectly, enabling the definition of recursive relationships (e.g., finding all descendants).
- Example (simple transitive closure):
path(X, Y) :- direct_path(X, Y).path(X, Y) :- direct_path(X, Z), path(Z, Y).
This defines a path between X and Y if there's a direct path, or if there's a direct path from X to Z and a path from Z to Y.
- Example (simple transitive closure):
Components of a Datalog Program
- Extensional Database (EDB): The set of facts explicitly stored in the database.
- Intensional Database (IDB): The set of relations defined by rules. These are derived facts.
Datalog Example
Consider two relations: Parent(Child, ParentName) and Female(PersonName).
Facts (EDB):Parent('Bob', 'Alice').Parent('Carol', 'Bob').Parent('David', 'Carol').Female('Alice').Female('Carol').
Rules (IDB):
1. Define Mother(Child, MotherName):Mother(C, M) :- Parent(C, M), Female(M).
2. Define Grandparent(Grandchild, GParent):Grandparent(GC, GP) :- Parent(GC, P), Parent(P, GP).
Queries:?- Mother('Bob', M). — Result: M = 'Alice'?- Grandparent('David', GP). — Result: GP = 'Alice'
Exam Notes
- Datalog is declarative; it focuses on what to retrieve, not how.
- It's particularly strong in handling recursive queries, which are difficult or impossible in standard Relational Algebra or SQL without extensions.
Set Operations
Relational databases treat relations as sets of tuples. Therefore, standard mathematical set operations can be applied to compatible relations (tables) in SQL. For set operations to be valid, the relations must be union-compatible, meaning they must have the same number of columns, and corresponding columns must have compatible data types.
1. UNION
TheUNIONoperator combines the result sets of two or moreSELECTstatements into a single result set. It automatically removes duplicate rows.
- Syntax:
SELECT column1, column2 FROM TableAUNIONSELECT column1, column2 FROM TableB; - Characteristics:
- Combines results from two or more queries.
- Requires union-compatible relations.
- Removes duplicate rows by default.
- Use
UNION ALLto include duplicates (often more efficient if duplicates are desired).
- Example: Find all unique names of employees who are either in the 'Sales' department or have a salary greater than 50000.
SELECT Name FROM Employees WHERE Department = 'Sales'UNIONSELECT Name FROM Employees WHERE Salary > 50000;
2. INTERSECT
TheINTERSECToperator returns only the rows that are present in the result sets of bothSELECTstatements. It only returns distinct rows.
- Syntax:
SELECT column1 FROM TableAINTERSECTSELECT column1 FROM TableB; - Characteristics:
- Returns common rows from two or more queries.
- Requires union-compatible relations.
- Removes duplicate rows by default.
- Example: Find names of employees who are in the 'Sales' department AND have a salary greater than 50000.
SELECT Name FROM Employees WHERE Department = 'Sales'INTERSECTSELECT Name FROM Employees WHERE Salary > 50000;
3. EXCEPT (or MINUS)
TheEXCEPT(orMINUSin some SQL dialects like Oracle) operator returns all rows from the firstSELECTstatement that are not found in the secondSELECTstatement. It returns only distinct rows.
- Syntax:
SELECT column1 FROM TableAEXCEPTSELECT column1 FROM TableB; - Characteristics:
- Returns rows unique to the first query.
- Requires union-compatible relations.
- Removes duplicate rows by default.
- Example: Find names of employees who are in the 'Sales' department but DO NOT have a salary greater than 50000.
SELECT Name FROM Employees WHERE Department = 'Sales'EXCEPTSELECT Name FROM Employees WHERE Salary > 50000;
Important Observation
- The column names in the final result set are typically taken from the first
SELECTstatement. - Order of columns and data types must match for all queries involved in a set operation.
Aggregate Functions
Aggregate functions perform a calculation on a set of rows and return a single summary value. They are commonly used with the GROUP BY clause to perform calculations on groups of rows.
Common Aggregate Functions
- COUNT()
Counts the number of rows or non-NULL values in a specified column.
COUNT(*): Counts all rows, including those with NULL values.COUNT(column_name): Counts rows wherecolumn_nameis not NULL.COUNT(DISTINCT column_name): Counts the number of unique, non-NULL values in a column.- Example:
SELECT COUNT(*) FROM Students;(Total number of students)SELECT COUNT(DISTINCT Major) FROM Students;(Number of unique majors)
- SUM()
Calculates the sum of all values in a numeric column. Ignores NULL values.
- Example:
SELECT SUM(Salary) FROM Employees;(Total salary of all employees)SELECT SUM(Quantity) FROM OrderDetails WHERE ProductID = 101;
- Example:
- AVG()
Calculates the average of all values in a numeric column. Ignores NULL values.
- Example:
SELECT AVG(Age) FROM Students;(Average age of students)SELECT AVG(Price) FROM Products WHERE Category = 'Electronics';
- Example:
- MIN()
Finds the minimum value in a column. Works with numeric, string, and date/time data types. Ignores NULL values.
- Example:
SELECT MIN(Salary) FROM Employees;(Lowest salary)SELECT MIN(EnrollmentDate) FROM Students;
- Example:
- MAX()
Finds the maximum value in a column. Works with numeric, string, and date/time data types. Ignores NULL values.
- Example:
SELECT MAX(Salary) FROM Employees;(Highest salary)SELECT MAX(DOB) FROM Students;
- Example:
GROUP BY Clause
The GROUP BY clause is used with aggregate functions to group rows that have the same values in specified columns into summary rows. The aggregate function then operates on each group separately.
- Syntax:
SELECT column_name(s), aggregate_function(column_name)FROM table_nameWHERE conditionGROUP BY column_name(s)ORDER BY column_name(s); - Example: Find the average salary for each department.
SELECT Department, AVG(Salary) FROM Employees GROUP BY Department; - Observation: Any column in the
SELECTlist that is not part of an aggregate function must appear in theGROUP BYclause.
HAVING Clause
The HAVING clause is used to filter groups based on a specified condition. It's similar to the WHERE clause but applies to groups after they have been formed and aggregated, rather than individual rows.
- Syntax:
SELECT column_name(s), aggregate_function(column_name)FROM table_nameGROUP BY column_name(s)HAVING condition; - Example: Find departments where the average salary is greater than 60000.
SELECT Department, AVG(Salary) FROM Employees GROUP BY Department HAVING AVG(Salary) > 60000; - Common Mistake: Using
WHEREfor aggregate conditions.WHEREfilters individual rows before grouping;HAVINGfilters groups after grouping and aggregation.
NULL Values
In relational databases, a NULL value represents an unknown, inapplicable, or missing piece of information. It is not the same as zero or an empty string; it signifies the absence of any value.
Characteristics of NULL
- Unknown: The value exists but is not known.
- Not Applicable: The attribute does not apply to a particular tuple.
- Missing: The value should be present but is currently absent.
Implications of NULL Values
- Arithmetic Operations: Any arithmetic operation involving a
NULLvalue will result inNULL.10 + NULL = NULL5 * NULL = NULL - Comparison Operations: Comparing any value with
NULLusing standard comparison operators (=,<,>, etc.) results inUNKNOWN, not true or false. In SQL,UNKNOWNbehaves like false inWHEREclauses.'Apple' = NULLis UNKNOWN10 < NULLis UNKNOWNNULL = NULLis UNKNOWN (NULL is never equal to anything, not even itself) - Logical Operations (AND, OR, NOT): The presence of
NULLintroduces three-valued logic (TRUE, FALSE, UNKNOWN).TRUE AND UNKNOWN= UNKNOWNFALSE AND UNKNOWN= FALSETRUE OR UNKNOWN= TRUEFALSE OR UNKNOWN= UNKNOWNNOT UNKNOWN= UNKNOWN
- Handling NULL in WHERE Clause: Because standard comparisons with
NULLyieldUNKNOWN, special predicates are used to check forNULLvalues.IS NULL: Checks if a value isNULL.IS NOT NULL: Checks if a value is notNULL.- Example:
SELECT Name FROM Employees WHERE Department IS NULL;SELECT Name FROM Employees WHERE Salary IS NOT NULL;
- Impact on Aggregate Functions: By default, most aggregate functions (
SUM,AVG,MIN,MAX) ignoreNULLvalues in their calculations.COUNT(column_name)also ignoresNULLs, butCOUNT(*)counts all rows, including those withNULLs in other columns.- Example: If a column has values {10, 20, NULL, 30}, then
AVG()would calculate (10+20+30)/3 = 20, not (10+20+NULL+30)/4.
- Example: If a column has values {10, 20, NULL, 30}, then
Exam Notes
- Understanding
NULLbehavior is crucial for accurate query results. - Always use
IS NULLorIS NOT NULLfor checkingNULLs, never= NULLor!= NULL. NULLvalues can significantly affect aggregate function results; be aware of their exclusion.