Informatics Practices: Class 12 — Chapter 1: Querying and SQL Functions

1.1 Introduction & Database Schema

In database management systems, SQL (Structured Query Language) is utilized to populate, manipulate, and retrieve data from relational databases. This chapter builds upon basic SQL concepts to explore advanced querying mechanisms, single-row functions, aggregate functions, grouping operations, and multi-table relations using MySQL.

Technical Profile: CARSHOWROOM Database Environment

  • Architecture Layer / Tier: Relational Database Management System (RDBMS) / MySQL Backend
  • Operational Mechanics: Consists of four interconnected relations linked via primary and foreign key constraints to maintain referential integrity.
  • System Impact & Execution Outputs: Serves as the transactional and analytical data store for inventory tracking, customer sales, and employee management.
Database Schema & Relations

The CARSHOWROOM database consists of the following four relations:

  • INVENTORY: Stores name, price, model, year of manufacturing, and fuel type for each car in the showroom.
  • CUSTOMER: Stores customer ID, name, address, phone number, and email.
  • SALE: Stores invoice number, car ID, customer ID, sale date, mode of payment, sales person's employee ID, and selling price.
  • EMPLOYEE: Stores employee ID, name, date of birth, date of joining, designation, and salary.

Table 1.1: INVENTORY

CarId CarName Price Model YearManufacture Fueltype
D001 Car1 582613.00 LXI 2017 Petrol
D002 Car1 673112.00 VXI 2018 Petrol
B001 Car2 567031.00 Sigma1.2 2019 Petrol
B002 Car2 647858.00 Delta1.2 2018 Petrol
E001 Car3 355205.00 5 STR STD 2017 CNG
E002 Car3 654914.00 CARE 2018 CNG
S001 Car4 514000.00 LXI 2017 Petrol
S002 Car4 614000.00 VXI 2018 Petrol

Table 1.2: CUSTOMER

CustId CustName CustAdd Phone Email
C0001 AmitSaha L-10, Pitampura 4564587852 amitsaha2@gmail.com
C0002 Rehnuma J-12, SAKET 5527688761 rehnuma@hotmail.com
C0003 CharviNayyar 10/9, FF, Rohini 6811635425 charvi123@yahoo.com
C0004 Gurpreet A-10/2, SF, MayurVihar 3511056125 gur_singh@yahoo.com

Table 1.3: SALE

InvoiceNo CarId CustId SaleDate PaymentMode EmpID SalePrice
I00001 D001 C0001 2019-01-24 Credit Card E004 613247.00
I00002 S001 C0002 2018-12-12 Online E001 590321.00
I00003 S002 C0004 2019-01-25 Cheque E010 604000.00
I00004 D002 C0001 2018-10-15 Bank Finance E007 659982.00
I00005 E001 C0003 2018-12-20 Credit Card E002 369310.00
I00006 S002 C0002 2019-01-30 Bank Finance E007 620214.00

Table 1.4: EMPLOYEE

EmpID EmpName DOB DOJ Designation Salary
E001 Rushil 1994-07-10 2017-12-12 Salesman 25550
E002 Sanjay 1990-03-12 2016-06-05 Salesman 33100
E003 Zohar 1975-08-30 1999-01-08 Peon 20000
E004 Arpit 1989-06-06 2010-12-02 Salesman 39100
E006 Sanjucta 1985-11-03 2012-07-01 Receptionist 27350
E007 Mayank 1993-04-03 2017-01-01 Salesman 27352
E010 Rajkumar 1987-02-26 2013-10-23 Salesman 31111
1.2 Functions in SQL

SQL functions are built-in operations used to perform calculations, manipulate strings, or format dates. They are broadly categorized into Single Row Functions (Scalar) and Multiple Row Functions (Aggregate).

1.2.1 Single Row Functions (Scalar)

Single row functions operate on a single value from a single row and return a single value as output. They are categorized into Numeric, String, and Date & Time functions.

(A) Numeric Functions Reference Matrix

Computing Method / Keyword Exact Syntactic Execution Signature Supported Parameters & Arguments Algorithmic Purpose & Output Representation
POWER() / POW() POWER(X, Y) X (Base number), Y (Exponent) Calculates X raised to the power of Y . Returns a numeric value.
ROUND() ROUND(N, D) N (Numeric value), D (Decimal places, optional, defaults to 0) Rounds off number N to D decimal places. If D is negative, rounds off to the left of the decimal point.
MOD() MOD(A, B) A (Dividend), B (Divisor) Returns the remainder of A divided by B . Equivalent to the modulo operator.

(B) String Functions Reference Matrix

Computing Method / Keyword Exact Syntactic Execution Signature Supported Parameters & Arguments Algorithmic Purpose & Output Representation
UCASE() / UPPER() UCASE(string) string (Target \text) Converts all characters in the string to uppercase.
LCASE() / LOWER() LCASE(string) string (Target \text) Converts all characters in the string to lowercase.
MID() / SUBSTRING() / SUBSTR() MID(string, pos, n) string (Target \text), pos (Starting index, 1-based), n (Length of substring, optional) Extracts a substring of size n starting from position pos . If n is omitted, extracts to the end of the string.
LENGTH() LENGTH(string) string (Target \text) Returns the length of the string in bytes (number of characters).
LEFT() LEFT(string, N) string (Target \text), N (Number of characters) Returns the leftmost N characters from the string.
RIGHT() RIGHT(string, N) string (Target \text), N (Number of characters) Returns the rightmost N characters from the string.
INSTR() INSTR(string, substring) string (Target \text), substring (Search \text) Returns the 1-based index of the first occurrence of substring in string . Returns 0 if not found.
LTRIM() LTRIM(string) string (Target \text) Removes leading whitespace characters from the string.
RTRIM() RTRIM(string) string (Target \text) Removes trailing whitespace characters from the string.
TRIM() TRIM(string) string (Target \text) or TRIM(remstr FROM string) Removes both leading and trailing whitespaces or specified characters from the string.

(C) Date and Time Functions Reference Matrix

Computing Method / Keyword Exact Syntactic Execution Signature Supported Parameters & Arguments Algorithmic Purpose & Output Representation
NOW() NOW() None Returns the current system date and time in 'YYYY-MM-DD HH:MM:SS' format.
DATE() DATE(expr) expr (Date or datetime expression) Extracts the date part of a date or datetime expression.
MONTH() MONTH(date) date (Date expression) Returns the numeric month value (1 to 12) for the given date.
MONTHNAME() MONTHNAME(date) date (Date expression) Returns the full name of the month (e.g., 'November') for the given date.
YEAR() YEAR(date) date (Date expression) Returns the four-digit year value (e.g., 2019) for the given date.
DAY() DAY(date) date (Date expression) Returns the day of the month (1 to 31) for the given date.
DAYNAME() DAYNAME(date) date (Date expression) Returns the name of the weekday (e.g., 'Wednesday') for the given date.
1.2.2 Aggregate Functions (Multiple Row)

Aggregate functions work on a set of records as a whole and return a single summarized value for each column on which they are applied.

Table 1.8: Differences between Single Row and Multiple Row Functions

Single Row Functions Multiple Row (Aggregate) Functions
Operate on a single row at a time. Operate on groups of rows.
Return one result per row. Return one result for a group of rows.
Can be used in SELECT, WHERE, and ORDER BY clauses. Can be used in SELECT and HAVING clauses (not directly in WHERE).
Examples: POWER() , UPPER() , DAY() . Examples: SUM() , COUNT() , AVG() .

Aggregate Functions Reference Matrix

Computing Method / Keyword Exact Syntactic Execution Signature Supported Parameters & Arguments Algorithmic Purpose & Output Representation
MAX() MAX(column) column (Numeric, string, or date column) Returns the maximum value in the specified column.
MIN() MIN(column) column (Numeric, string, or date column) Returns the minimum value in the specified column.
AVG() AVG(column) column (Numeric column) Returns the average value of the specified column. Ignores NULL values.
SUM() SUM(column) column (Numeric column) Returns the sum of all values in the specified column. Ignores NULL values.
COUNT() COUNT(column) column (Any column) Returns the count of non-NULL values in the specified column.
COUNT(*) COUNT(*) None Returns the total number of rows in the table, including NULLs and duplicates.
1.3 GROUP BY in SQL

The GROUP BY clause is used to group rows that have the same values in specified columns into summary rows. It is frequently used with aggregate functions to perform calculations on each group.

HAVING Clause

The HAVING clause is used to apply filter conditions on grouped records. Unlike the WHERE clause, which filters rows before grouping, HAVING filters groups after GROUP BY has been applied.

  
    mysql> SELECT CustID, COUNT(*)
    FROM SALE
    GROUP BY CustID
    HAVING COUNT(*) > 1;
  
1.4 Operations on Relations

Relational algebra operations allow merging and manipulating tuples from two or more tables. These operations require the participating relations to be Union Compatible (same number of attributes, with corresponding attributes sharing the same domain).

Set Operations
  • UNION (U): Combines the selected rows of two tables, eliminating duplicate rows.
  • INTERSECT (∩): Returns only the common tuples present in both tables.
  • MINUS (-): Returns tuples present in the first table but absent in the second table.
  • Cartesian Product (X): Combines each row of the first table with every row of the second table. The degree of the resulting relation is the sum of the degrees of both tables ($Degree = D_1 + D_2$), and the cardinality is the product of their cardinalities ($Cardinality = C_1 \times C_2$).
1.5 Using Two Relations in a Query

To retrieve data from multiple tables, SQL provides mechanisms to perform Cartesian products and Joins.

Cartesian Product & Joins

When multiple tables are specified in the FROM clause separated by commas without a join condition, a Cartesian product is performed.

  
  mysql> SELECT * FROM DANCE, MUSIC;

JOIN Operations:

  • Equi-Join: Joins tables based on an equality condition between common columns using the WHERE clause.
  • Explicit JOIN Clause: Uses the JOIN keyword along with the ON clause to specify join conditions.
  • NATURAL JOIN: An automated join that matches columns with identical names in both tables and automatically eliminates duplicate columns from the output.
  
  mysql> SELECT * FROM UNIFORM NATURAL JOIN COST;