Quarterly Revenue Query and Largest-File Shell Script
SQL & DataModel answerLast updated
Write a SQL query that totals 2023 sales by quarter, and a robust bash script that finds the largest file under a directory, handling odd filenames and error cases.
This exercise has two small tasks that cover everyday engineering tooling.
Part 1: Revenue per quarter (SQL)
You have a table sales with these columns:
sale_id(integer)amount(decimal)sale_date(datetime)
Write a query that returns the total revenue for each calendar quarter of 2023. The result must have two columns:
quarter: a number from 1 to 4total_revenue: the sum ofamountfor that quarter
Example of the expected shape:
| quarter | total_revenue |
|---|---|
| 1 | 5000.00 |
| 2 | 7200.50 |
Use standard PostgreSQL or MySQL syntax. Explain which dialect you chose.
Part 2: Find the biggest file (Bash)
Write a bash script that accepts one argument, a directory path. It must:
- Search the directory and all its subdirectories.
- Print the name (path) and size of the single largest file.
- If the directory does not exist, or contains no files, print a clear error message to stderr and exit with a non-zero status.
Requirements:
- You may use utilities such as
find,duorsort. - Filenames containing spaces must work correctly.
Be ready to discuss how your solution behaves with very large inputs, ties, and unusual filenames.
Hints
Hint 1
For the SQL part, filter the year with a half-open range (`>= '2023-01-01' AND < '2024-01-01'`) rather than wrapping the column in a function or using BETWEEN with a date-only upper bound. Think about which one keeps indexes usable and does not lose late-December timestamps.
Hint 2
Derive the quarter with EXTRACT(QUARTER FROM ...) in PostgreSQL or QUARTER(...) in MySQL, then GROUP BY it and ORDER BY it so the output order is deterministic.
Hint 3
For the shell part, `du -h | sort -rh` is approximate and fragile. Let `find -type f -printf '%s\t%p\0'` emit exact byte sizes with NUL-terminated records, and keep a running maximum in a `while read -d ''` loop fed by process substitution.
Hint 4
Validate the argument first: wrong argument count, missing path, not a directory, unreadable. After the loop, treat 'no file seen' as the empty-directory error. Send all errors to stderr with `>&2`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Quarterly revenue
Approach
- Keep only rows from calendar year 2023.
- Convert each date to its quarter number.
- Group by quarter and sum
amount.
Query
PostgreSQL:
SELECT
EXTRACT(QUARTER FROM sale_date)::int AS quarter,
SUM(amount) AS total_revenue
FROM sales
WHERE sale_date >= '2023-01-01'
AND sale_date < '2024-01-01'
GROUP BY EXTRACT(QUARTER FROM sale_date)
ORDER BY quarter;
MySQL:
SELECT
QUARTER(sale_date) AS quarter,
SUM(amount) AS total_revenue
FROM sales
WHERE sale_date >= '2023-01-01'
AND sale_date < '2024-01-01'
GROUP BY QUARTER(sale_date)
ORDER BY quarter;
Why this form
- Half-open range.
sale_date < '2024-01-01'includes everything up to the last fraction of a second on 31 December.BETWEEN '2023-01-01' AND '2023-12-31'silently drops most of 31 December, because'2023-12-31'means midnight. - No function on the filtered column.
WHERE YEAR(sale_date) = 2023forces the database to evaluate the function per row and usually prevents an index onsale_datefrom being used. The range form can use an index. - ORDER BY. SQL gives no ordering guarantee without it.
- NULLs.
SUMignores NULL amounts, so they do not break the total. - Cast. In PostgreSQL,
EXTRACTreturns a numeric type, so cast tointfor a cleanquartercolumn.
Complexity
With an index on sale_date, the cost is proportional to the number of 2023 rows. Without one it is a full table scan. Memory is tiny because there are at most four groups.
Edge cases and follow-up
- Quarters with no sales are absent from the result. To show them as zero, build the four quarters and
LEFT JOINthe sales onto them, with the date filter in theONclause (notWHERE, which would turn it back into an inner join) andCOALESCE(SUM(...), 0). In PostgreSQL usegenerate_series(1,4). In MySQL use aUNION ALLof four constants. - Time zones. If timestamps are stored in UTC but the business reports in local time, convert before bucketing.
Part 2: Largest file script
Why not du | sort?
du -ah dir | sort -rh | head -1 is fine as a quick one-liner, but it has real flaws:
dureports disk usage (blocks), not the file's byte size. Sparse or compressed files look very different.-houtput is rounded, so near-equal files are ambiguous.- It includes directories unless you filter them out.
- Line-based pipelines break on filenames containing newlines.
- Sorting is O(n log n) when a single pass is enough.
Approach
Use find -type f -printf '%s\t%p\0' to emit the exact size and path of each regular file, terminated by NUL (the one byte that cannot appear in a path). Read these records in a loop and track the maximum. This uses constant memory and one pass.
Script
#!/usr/bin/env bash
# Usage: largest_file.sh <directory>
set -u
if [[ $# -ne 1 ]]; then
echo "Usage: ${0##*/} <directory>" >&2
exit 2
fi
dir=$1
if [[ ! -e $dir ]]; then
echo "Error: '$dir' does not exist." >&2
exit 1
fi
if [[ ! -d $dir ]]; then
echo "Error: '$dir' is not a directory." >&2
exit 1
fi
if [[ ! -r $dir || ! -x $dir ]]; then
echo "Error: '$dir' is not readable." >&2
exit 1
fi
max_size=-1
max_path=""
while IFS= read -r -d '' record; do
size=${record%%$'\t'*} # text before the first tab
path=${record#*$'\t'} # everything after it (tabs in names survive)
if (( size > max_size )); then
max_size=$size
max_path=$path
fi
done < <(find "$dir" -type f -printf '%s\t%p\0')
if (( max_size < 0 )); then
echo "Error: no files found under '$dir'." >&2
exit 1
fi
printf 'Largest file: %s\nSize: %d bytes\n' "$max_path" "$max_size"
Why it works
"$dir"is always quoted, and records are NUL-delimited, so spaces, tabs and even newlines in names are safe.IFS= read -r -d ''preserves leading whitespace and backslashes.- Process substitution (
< <(...)) keeps the loop in the current shell. Withfind ... | while read, the loop runs in a subshell andmax_sizewould be lost afterwards. - Starting
max_sizeat -1 means a zero-byte file still counts as a file, so only a truly file-less directory triggers the error. - Exit codes: 2 for misuse, 1 for runtime errors, 0 on success. All messages go to stderr.
Complexity
O(n) time over n files, O(1) extra memory. sort would be O(n log n) and might spill to disk.
Edge cases and trade-offs
- Ties: the first file found wins. Say so explicitly, or change
>to>=for last-wins. - Symlinks:
-type fskips symlinks andfinddoes not follow them by default, which avoids double counting and loops. - Permission-denied subdirectories:
findwarns on stderr and continues. That is usually the right behavior, but mention it. - Portability:
-printfis GNU-specific. On macOS/BSD usefind "$dir" -type f -exec stat -f '%z%t%N' {} +or install GNU findutils.
Follow-ups
- Millions of files:
findstreams, so memory stays flat, but a bash loop is slow per iteration. Pipe the NUL-delimited output intogawkwithRS='\0'andFS='\t', and use-xdevor-pruneto skip irrelevant trees. - Excluding extensions: add
! \( -name '*.tmp' -o -name '*.bak' \)before-printf.
Common mistakes
- Using
BETWEENwith a date-only end bound on a datetime column. - Applying
YEAR()to the column inWHERE. - Parsing
lsordu -houtput. - Piping into
while readand then reading variables after the loop. - Forgetting to quote variables, or printing errors to stdout.