ORDER BY - sorting results#
Rows in a table have no guaranteed order. Use ORDER BY to sort the result:
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.
You can sort by an alias or an expression:
LIMIT and OFFSET - top-N and pages#
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++ |
Number functions#
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:
| 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#
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#
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 mfor 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. COALESCEreplaces NULLs;CASE WHEN ... THEN ... ELSE ... ENDadds conditional logic.