⚡0 XP🔥0

Sorting, Limiting and SQL Functions

Lesson 3 of 10 ⏱ 4 min read ✎ 3 exercises ❓ 4-question quiz ▶ Runs SQL

Sort results with ORDER BY, take the top rows with LIMIT and OFFSET, and use text, number, date, NULL-handling and CASE expressions.

ORDER BY - sorting results#

Rows in a table have no guaranteed order. Use ORDER BY to sort the result:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
  • ASC (default) - smallest first / A to Z / oldest date first.
  • DESC - largest first.
  • Sort by several columns: the second is used only when the first is equal.
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

You can sort by an alias or an expression:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

LIMIT and OFFSET - top-N and pages#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Note

LIMIT works in SQLite, MySQL and PostgreSQL. SQL Server uses SELECT TOP 3 ...; Oracle and the SQL standard use FETCH FIRST 3 ROWS ONLY.

हिंदी में समझें

ORDER BY से result को क्रम में लगाते हैं - ASC छोटे से बड़ा, DESC बड़े से छोटा। LIMIT 3 सिर्फ़ पहली 3 rows देता है, इसलिए "top 3" निकालने के लिए पहले ORDER BY ... DESC फिर LIMIT 3 लिखें। OFFSET से शुरू की कुछ rows छोड़ी जाती हैं - website पर page 1, page 2 ऐसे ही बनते हैं।

Text functions#

Function (SQLite) Example Result
UPPER(s), LOWER(s) UPPER('java') JAVA
LENGTH(s) LENGTH('Indore') 6
SUBSTR(s, start, len) SUBSTR('Vindhya', 1, 3) Vin
TRIM(s) TRIM(' hi ') hi
REPLACE(s, a, b) REPLACE('a-b', '-', '/') a/b
INSTR(s, sub) INSTR('a@b.com', '@') 2
s1 || s2 'C' || '++' C++
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Number functions#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Date functions#

SQLite stores dates as text in YYYY-MM-DD format, so they sort and compare correctly as text. Date functions differ the most between databases:

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Task SQLite MySQL PostgreSQL
current date date('now') CURDATE() CURRENT_DATE
year of a date strftime('%Y', d) YEAR(d) EXTRACT(YEAR FROM d)
add days date(d, '+7 days') DATE_ADD(d, INTERVAL 7 DAY) d + INTERVAL '7 days'
difference in days julianday(a) - julianday(b) DATEDIFF(a, b) a - b

Handling NULL: COALESCE and IFNULL#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

COALESCE(a, b, c) returns the first non-NULL value. MySQL also has IFNULL(a, b); SQL Server has ISNULL(a, b).

CASE - if/else inside a query#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

CASE can also be used inside ORDER BY, WHERE and aggregate functions - you will use it constantly in reports.

Summary#

  • ORDER BY col [ASC|DESC], multiple columns break ties; LIMIT n OFFSET m for top-N and pagination.
  • Text: UPPER, LENGTH, SUBSTR, INSTR, REPLACE, ||. Numbers: ROUND, ABS, CAST.
  • Dates are stored as YYYY-MM-DD; date functions differ by database.
  • COALESCE replaces NULLs; CASE WHEN ... THEN ... ELSE ... END adds conditional logic.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Top 5 students

Show the name and cgpa of the 5 students with the highest CGPA, highest first. Break ties by name (A-Z).

Database: college (see the tables in this lesson)
2

Grade bands with CASE

Show name, cgpa and a column band: Distinction for CGPA >= 9, First class for >= 7.5, otherwise Second class. Order by cgpa descending.

Database: college (see the tables in this lesson)
3

Faculty experience

Show each faculty member's name, joining_date and the joining year as join_year (use strftime('%Y', joining_date) or substr), for those who joined in 2015 or later, oldest first.

Database: college (see the tables in this lesson)

Quick Quiz

Q1.

What is the default sort direction of ORDER BY?

Q2.

LIMIT 5 OFFSET 10 returns...

Q3.

What does COALESCE(email, 'not given') do?

Q4.

Which expression gives different values based on conditions?