Repository navigation
Expand file tree
/
Copy pathFUNCTIONS.sql
More file actions
1732 lines (1398 loc) · 70.1 KB
/
Copy pathFUNCTIONS.sql
File metadata and controls
1732 lines (1398 loc) · 70.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- tinySQL Function Examples
-- Selected examples of the tinySQL SQL dialect. See ../sql-semantics.md
-- for exact compatibility rules. Later sections may require their setup
-- statements, local sample files, network access, or optional build tags.
-- ============================================================
-- CHECKED SEMANTICS EXAMPLES
-- ============================================================
-- This section runs in the native test suite. Examples are independent,
-- deterministic and require no files, network, session language or timezone.
-- ISO weekdays use Monday=1 through Sunday=7 in the input's explicit offset.
SELECT ISODOW('2024-03-01T00:30:00+14:00') AS friday,
DATEPART(ISO_WEEKDAY,'2024-03-03T23:30:00-12:00') AS sunday;
-- DATEDIFF counts UTC boundaries; TIMESTAMPDIFF counts complete elapsed units.
-- Calendar months are not approximated as 30 days.
SELECT DATEDIFF(MONTH,'2024-01-31','2024-02-29') AS boundaries,
TIMESTAMPDIFF(MONTH,'2024-01-31','2024-02-29') AS complete_months;
-- Equivalent instants and DST transitions use elapsed UTC time.
SELECT DATEDIFF(DAY,'2024-03-01T00:30:00+01:00','2024-02-29T23:30:00Z') AS same_instant,
TIMESTAMPDIFF(HOUR,'2024-03-30T12:00:00+01:00','2024-03-31T12:00:00+02:00') AS elapsed_hours;
-- NULL is distinct from empty text, zero and FALSE. ISNULL is a Boolean test.
SELECT ISNULL(NULL) AS missing, ISNULL('') AS empty_text,
0 IS NOT NULL AS zero_present, FALSE IS NOT NULL AS false_present;
-- Replacement functions evaluate only the arguments they need.
SELECT COALESCE('ok',1/0) AS lazy_value, IFNULL(NULL,FALSE) AS replacement;
-- Trimming accepts a set of Unicode characters. An empty set removes nothing.
SELECT LTRIM('🙂xxtext','🙂x') AS characters,
TRIM(' text ','') AS empty_set, TRIM(NULL,1/0) AS lazy_null;
-- STRING_SPLIT uses a literal, possibly multi-character delimiter.
-- Empty fields are preserved; request ordinals and ORDER BY for stable order.
SELECT value,ordinal FROM STRING_SPLIT('alpha::beta::::','::',1) ORDER BY ordinal;
-- FILTER restricts aggregate input without removing the group itself.
WITH reference_values AS (SELECT 1 AS v UNION ALL SELECT 2 AS v UNION ALL SELECT NULL AS v)
SELECT COUNT(*) FILTER (WHERE v IS NOT NULL) AS non_null_rows,
SUM(v) FILTER (WHERE v>=2) AS selected_total FROM reference_values;
-- JSON_GET reads structured JSON values, not unparsed SQL text.
-- Nested objects from JSON table input can be accessed using dotted/bracket paths.
SELECT JSON_GET(meta,'items[0].sku') AS sku, JSON_GET(meta,'value') AS json_null
FROM TABLE_FROM_JSON('[{"meta":{"items":[{"sku":"A"}],"value":null}}]');
-- JSON table functions currently decode numeric cells as float64.
-- Transport identifiers above 2^53 as JSON strings to retain their precision.
SELECT id AS exact_id
FROM TABLE_FROM_JSON('[{"id":"9007199254740993"}]');
-- JSON Lines accepts one object per line, including surrounding blank lines.
SELECT id,name FROM TABLE_FROM_JSON_LINES('
{"id":1,"name":"Ada"}
{"id":2,"name":"Lin"}
') ORDER BY id;
-- END CHECKED SEMANTICS EXAMPLES
-- ============================================================
-- DATE AND TIME FUNCTIONS
-- ============================================================
-- Current date and time
SELECT NOW() as current_timestamp;
SELECT CURRENT_DATE() as today;
SELECT CURRENT_TIME() as current_time;
-- Date part extraction
SELECT YEAR(NOW()) as current_year;
SELECT MONTH(NOW()) as current_month;
SELECT DAY(NOW()) as current_day;
SELECT HOUR(NOW()) as current_hour;
SELECT MINUTE(NOW()) as current_minute;
SELECT SECOND(NOW()) as current_second;
SELECT QUARTER(NOW()) as current_quarter;
SELECT DAYOFWEEK(NOW()) as day_of_week;
SELECT DAYOFYEAR(NOW()) as day_of_year;
SELECT WEEKOFYEAR(NOW()) as week_of_year;
-- EXTRACT function (alternative to individual functions)
SELECT EXTRACT('YEAR', NOW()) as year;
SELECT EXTRACT('MONTH', NOW()) as month;
SELECT EXTRACT('DAY', NOW()) as day;
SELECT EXTRACT('QUARTER', NOW()) as quarter;
SELECT EXTRACT('WEEK', NOW()) as week;
SELECT EXTRACT('DAYOFWEEK', NOW()) as dow;
-- Date arithmetic
SELECT DATE_ADD(CURRENT_DATE(), 7, 'DAY') as next_week;
SELECT DATE_SUB(CURRENT_DATE(), 30, 'DAY') as last_month;
SELECT DATEDIFF('DAYS', '2024-01-01', '2024-12-31') as days_in_2024;
-- ADD_MONTHS function
SELECT ADD_MONTHS(CURRENT_DATE(), 3) as three_months_later;
SELECT ADD_MONTHS(CURRENT_DATE(), -6) as six_months_ago;
-- DATE_TRUNC function (truncate to period start)
SELECT DATE_TRUNC('YEAR', NOW()) as start_of_year;
SELECT DATE_TRUNC('QUARTER', NOW()) as start_of_quarter;
SELECT DATE_TRUNC('MONTH', NOW()) as start_of_month;
SELECT DATE_TRUNC('WEEK', NOW()) as start_of_week;
SELECT DATE_TRUNC('DAY', NOW()) as start_of_day;
SELECT DATE_TRUNC('HOUR', NOW()) as start_of_hour;
-- EOMONTH function (end of month)
SELECT EOMONTH(CURRENT_DATE()) as end_of_current_month;
SELECT EOMONTH(CURRENT_DATE(), 1) as end_of_next_month;
SELECT EOMONTH(CURRENT_DATE(), -1) as end_of_last_month;
-- IN_PERIOD function (period membership checks)
SELECT IN_PERIOD('TODAY', CURRENT_DATE()) as is_today;
SELECT IN_PERIOD('YTD', '2024-06-15') as is_year_to_date;
SELECT IN_PERIOD('MTD', CURRENT_DATE()) as is_month_to_date;
SELECT IN_PERIOD('QTD', CURRENT_DATE()) as is_quarter_to_date;
SELECT IN_PERIOD('L12M', DATE_SUB(CURRENT_DATE(), 180, 'DAY')) as is_last_12_months;
SELECT IN_PERIOD('CURRENT_QUARTER', CURRENT_DATE()) as is_current_quarter;
SELECT IN_PERIOD('PREVIOUS_QUARTER', DATE_SUB(CURRENT_DATE(), 120, 'DAY')) as was_previous_quarter;
SELECT IN_PERIOD('CURRENT_YEAR_FULL', CURRENT_DATE()) as is_current_year;
-- Date formatting
SELECT STRFTIME('%Y-%m-%d', NOW()) as iso_date;
SELECT STRFTIME('%d.%m.%Y', NOW()) as german_date;
SELECT STRFTIME('%A, %B %d, %Y', NOW()) as long_date;
SELECT DATE(NOW()) as date_only;
SELECT TIME(NOW()) as time_only;
-- ============================================================
-- STRING FUNCTIONS
-- ============================================================
-- Case conversion
SELECT UPPER('hello world') as uppercase;
SELECT LOWER('HELLO WORLD') as lowercase;
SELECT INITCAP('hello world from tinysql') as title_case;
-- String manipulation
SELECT CONCAT('Hello', ' ', 'World') as concatenated;
SELECT CONCAT_WS(', ', 'Apple', 'Banana', 'Cherry') as joined_with_separator;
SELECT LENGTH('Hello World') as string_length;
SELECT CHAR_LENGTH('Hello') as char_length;
SELECT SUBSTRING('Hello World', 7, 5) as substring_result;
SELECT SUBSTR('Hello World', 1, 5) as substr_result;
SELECT LEFT('Hello World', 5) as left_chars;
SELECT RIGHT('Hello World', 5) as right_chars;
SELECT REVERSE('Hello') as reversed;
SELECT REPEAT('Ha', 3) as repeated;
-- String trimming
SELECT TRIM(' Hello ') as trimmed;
SELECT LTRIM(' Hello') as left_trimmed;
SELECT RTRIM('Hello ') as right_trimmed;
-- String padding
SELECT LPAD('42', 5, '0') as left_padded;
SELECT RPAD('42', 5, '0') as right_padded;
-- String replacement
SELECT REPLACE('Hello World', 'World', 'Universe') as replaced;
-- String search
SELECT INSTR('Hello World', 'World') as position;
SELECT LOCATE('World', 'Hello World') as locate_position;
-- String formatting
SELECT PRINTF('Value: %d, Name: %s', 42, 'Test') as formatted;
SELECT FORMAT('Pi is approximately %.2f', 3.14159) as formatted_number;
-- SPLIT function (returns array)
SELECT SPLIT('apple,banana,cherry', ',') as fruit_array;
-- Split and extract part (existing function)
SELECT SPLIT_PART('apple,banana,cherry', ',', 2) as second_fruit;
-- Special string functions
SELECT SPACE(10) as ten_spaces;
SELECT ASCII('A') as ascii_value;
SELECT CHAR(65) as char_from_ascii;
SELECT SOUNDEX('Smith') as soundex_code;
SELECT QUOTE('It''s a test') as quoted_string;
-- ============================================================
-- REGEX FUNCTIONS
-- ============================================================
-- Pattern matching
SELECT REGEXP_MATCH('test@example.com', '.*@.*\.com') as is_email;
SELECT REGEXP_MATCH('12345', '^\d+$') as is_numeric;
-- Pattern extraction
SELECT REGEXP_EXTRACT('Order #12345 processed', '#\d+') as order_number;
SELECT REGEXP_EXTRACT('Email: test@example.com', '\w+@\w+\.\w+') as email;
-- Pattern replacement
SELECT REGEXP_REPLACE('2024-11-27', '-', '/') as date_with_slashes;
SELECT REGEXP_REPLACE('Hello123World456', '\d+', 'X') as numbers_replaced;
-- ============================================================
-- FULL-TEXT SEARCH FUNCTIONS
-- ============================================================
-- FTS_MATCH: boolean match against a query (term, phrase, boolean, wildcard)
SELECT FTS_MATCH('the quick brown fox', 'fox') as has_fox;
SELECT FTS_MATCH('the quick brown fox', 'quick AND fox') as has_both;
SELECT FTS_MATCH('the quick brown fox', 'cat OR fox') as has_either;
SELECT FTS_MATCH('the quick brown fox', 'NOT cat') as lacks_cat;
SELECT FTS_MATCH('the quick brown fox jumps', '"quick brown"') as has_phrase;
SELECT FTS_MATCH('the database stores information', 'inform*') as has_prefix;
-- ? / _ match one character; * / % match zero or more characters.
SELECT FTS_MATCH('colour palette', 'colo?r') as single_char_wildcard;
SELECT FTS_MATCH('database systems', 'data%') as multi_char_wildcard;
-- FTS_RANK / BM25: relevance score for the same query syntax (higher = more relevant)
SELECT FTS_RANK('the quick brown fox', 'fox AND quick') as relevance;
SELECT BM25('the quick brown fox', 'fox AND quick') as relevance_alias;
-- FTS_SNIPPET / FTS_HIGHLIGHT: return the text with matches wrapped in markers
SELECT FTS_SNIPPET('the quick brown fox', 'fox', '<em>', '</em>', '', 10) as excerpt;
-- FTS_WORD_COUNT: number of (stop-word-filtered, stemmed) tokens
SELECT FTS_WORD_COUNT('hello world foo') as token_count;
-- FTS_SEARCH table-valued function: ranked search across a real table.
-- With no column arguments it searches the WHOLE ROW (every column, not
-- just TEXT ones); pass explicit column names to restrict the search.
-- Repeated calls against an unchanged table reuse a cached tokenization,
-- so it's cheap for interactive/repeated queries.
CREATE TABLE fts_demo_articles (id INT, title TEXT, body TEXT);
INSERT INTO fts_demo_articles VALUES (1, 'Go Programming', 'Go is a fast compiled language for systems programming');
INSERT INTO fts_demo_articles VALUES (2, 'Python Tutorial', 'Python is a dynamic scripting language popular for data science');
INSERT INTO fts_demo_articles VALUES (3, 'Database Design', 'Relational databases store data in tables with relationships');
SELECT id, title, _fts_score, _fts_rank
FROM FTS_SEARCH('fts_demo_articles', 'programming language', 2)
ORDER BY _fts_rank;
-- Restrict the search to a single column
SELECT id, title FROM FTS_SEARCH('fts_demo_articles', 'relational', 5, 'body');
DROP TABLE fts_demo_articles;
-- ROW_TO_TEXT: ad-hoc whole-row substring search inside an ordinary WHERE
-- clause, combinable with other conditions. Cheaper to set up than
-- FTS_SEARCH (no ranking, no table function) but also less precise; good
-- for a quick "search everywhere" filter.
CREATE TABLE row_to_text_demo (id INT, customer TEXT, status TEXT);
INSERT INTO row_to_text_demo VALUES (1, 'Acme Corp', 'open');
INSERT INTO row_to_text_demo VALUES (2, 'Globex', 'closed');
SELECT id FROM row_to_text_demo WHERE ROW_TO_TEXT() LIKE '%Acme%' AND status = 'open';
DROP TABLE row_to_text_demo;
-- CONTAINS_ALL / CONTAINS_ANY / CONTAINS_SCORE: a friendlier, case-insensitive
-- alternative to chaining "ROW_TO_TEXT() LIKE '%term%' AND ROW_TO_TEXT() LIKE
-- '%other%' ..." for each term. Terms are literal substrings, not patterns —
-- unlike LIKE, '%' and '_' have no wildcard meaning here.
CREATE TABLE contains_demo (id INT, description TEXT);
INSERT INTO contains_demo VALUES (1, 'Widget A2000 - blue, waterproof');
INSERT INTO contains_demo VALUES (2, 'Widget B300 - red');
INSERT INTO contains_demo VALUES (3, 'Gadget C100 - blue, waterproof, wireless');
-- CONTAINS_ALL: every term must be present (case-insensitive substring match)
SELECT id, description FROM contains_demo
WHERE CONTAINS_ALL(description, 'blue', 'waterproof');
-- CONTAINS_ANY: at least one term must be present
SELECT id, description FROM contains_demo
WHERE CONTAINS_ANY(description, 'wireless', 'red');
-- CONTAINS_SCORE: count of matched terms (0..N) - use in ORDER BY to rank
-- rows by how many search terms they contain
SELECT id, description, CONTAINS_SCORE(description, 'blue', 'waterproof', 'wireless') as match_count
FROM contains_demo
ORDER BY match_count DESC;
DROP TABLE contains_demo;
-- ============================================================
-- NUMERIC FUNCTIONS
-- ============================================================
-- Basic math
SELECT ABS(-42) as absolute_value;
SELECT SIGN(-15) as sign_of_number;
SELECT ROUND(3.14159, 2) as rounded;
SELECT FLOOR(3.7) as floor_value;
SELECT CEIL(3.2) as ceiling_value;
SELECT CEILING(3.2) as ceiling_value2;
SELECT TRUNCATE(3.14159, 2) as truncated;
SELECT TRUNC(3.14159, 2) as trunc_value;
-- Advanced math
SELECT POWER(2, 8) as power_of_two;
SELECT POW(3, 3) as cube;
SELECT SQRT(16) as square_root;
SELECT MOD(17, 5) as modulo;
-- Logarithms and exponentials
SELECT LOG(100) as natural_log;
SELECT LN(2.71828) as ln_value;
SELECT LOG10(1000) as log_base_10;
SELECT LOG2(1024) as log_base_2;
SELECT EXP(1) as euler_number;
-- Trigonometry
SELECT PI() as pi_value;
SELECT SIN(PI() / 2) as sine_90_degrees;
SELECT COS(0) as cosine_0_degrees;
SELECT TAN(PI() / 4) as tangent_45_degrees;
SELECT ASIN(1) as arcsine;
SELECT ACOS(0) as arccosine;
SELECT ATAN(1) as arctangent;
SELECT ATAN2(1, 1) as atan2_value;
SELECT DEGREES(PI()) as radians_to_degrees;
SELECT RADIANS(180) as degrees_to_radians;
-- Random numbers
SELECT RANDOM() as random_value;
SELECT RAND() as rand_value;
-- ============================================================
-- ARRAY FUNCTIONS
-- ============================================================
-- Create arrays
SELECT SPLIT('red,green,blue', ',') as colors;
-- Array element access
SELECT FIRST(SPLIT('alpha,beta,gamma', ',')) as first_element;
SELECT LAST(SPLIT('alpha,beta,gamma', ',')) as last_element;
-- Array properties
SELECT ARRAY_LENGTH(SPLIT('one,two,three,four', ',')) as array_size;
-- Array membership
SELECT ARRAY_CONTAINS(SPLIT('apple,banana,cherry', ','), 'banana') as has_banana;
SELECT IN_ARRAY(SPLIT('1,2,3,4,5', ','), '3') as has_three;
-- Array to string
SELECT ARRAY_JOIN(SPLIT('hello,world', ','), ' ') as joined_array;
SELECT ARRAY_JOIN(SPLIT('a,b,c', ','), ' - ') as joined_with_dash;
-- Array manipulation
SELECT ARRAY_DISTINCT(SPLIT('a,b,a,c,b,d', ',')) as unique_elements;
SELECT ARRAY_SORT(SPLIT('zebra,apple,mango,banana', ',')) as sorted_array;
-- ============================================================
-- AGGREGATE FUNCTIONS
-- ============================================================
-- Create a sample table for aggregate examples
CREATE TABLE temp_numbers (group_id INT, value INT);
INSERT INTO temp_numbers VALUES (1, 10), (1, 20), (1, 30);
INSERT INTO temp_numbers VALUES (2, 5), (2, 15), (2, 25);
INSERT INTO temp_numbers VALUES (3, 100), (3, 200);
-- COUNT
SELECT group_id, COUNT(*) as total_count FROM temp_numbers GROUP BY group_id;
SELECT group_id, COUNT(value) as non_null_count FROM temp_numbers GROUP BY group_id;
-- Basic aggregates (use with GROUP BY in real queries)
-- SELECT COUNT(*) as total_count FROM table;
-- SELECT COUNT(column) as non_null_count FROM table;
-- SELECT SUM(amount) as total FROM table;
-- SELECT AVG(value) as average FROM table;
-- SELECT MIN(price) as minimum FROM table;
-- SELECT MAX(price) as maximum FROM table;
-- MIN_BY and MAX_BY - Get value from row with min/max of another column
-- These are useful for time-series data and finding associated values
-- Create a sample sales table
CREATE TABLE temp_sales (product TEXT, sale_date TEXT, amount INT);
INSERT INTO temp_sales VALUES ('Laptop', '2025-01-15', 1200);
INSERT INTO temp_sales VALUES ('Mouse', '2025-03-20', 25);
INSERT INTO temp_sales VALUES ('Keyboard', '2025-02-10', 75);
INSERT INTO temp_sales VALUES ('Monitor', '2025-01-05', 350);
-- Get the product name from the row with the earliest date
SELECT MIN_BY(product, sale_date) as earliest_product FROM temp_sales;
-- Get the product name from the row with the latest date
SELECT MAX_BY(product, sale_date) as latest_product FROM temp_sales;
-- Get the product name with the lowest amount
SELECT MIN_BY(product, amount) as cheapest FROM temp_sales;
-- Get the product name with the highest amount
SELECT MAX_BY(product, amount) as most_expensive FROM temp_sales;
-- Get the amount from the row with the earliest date
SELECT MIN_BY(amount, sale_date) as earliest_amount FROM temp_sales;
-- Get the amount from the row with the latest date
SELECT MAX_BY(amount, sale_date) as latest_amount FROM temp_sales;
-- Aliases ARG_MIN and ARG_MAX are also supported
SELECT ARG_MIN(product, amount) as cheapest_via_argmin FROM temp_sales;
SELECT ARG_MAX(product, amount) as most_expensive_via_argmax FROM temp_sales;
-- Clean up
DROP TABLE temp_sales;
DROP TABLE temp_numbers;
-- ============================================================
-- COMPARISON AND RANGE PREDICATES
-- ============================================================
-- BETWEEN: inclusive range check, equivalent to (x >= lo AND x <= hi)
SELECT 5 BETWEEN 1 AND 10 as in_range;
SELECT 15 BETWEEN 1 AND 10 as out_of_range;
SELECT 5 NOT BETWEEN 1 AND 10 as not_in_range;
-- BETWEEN also works on dates and strings (lexicographic range for strings)
SELECT '2024-06-15' BETWEEN '2024-01-01' AND '2024-12-31' as in_2024;
SELECT 'mango' BETWEEN 'apple' AND 'peach' as alphabetically_between;
-- The comparand is evaluated exactly once even for expensive/non-deterministic
-- expressions, e.g. RANDOM() BETWEEN 0.0 AND 1.0 is always true, never
-- comparing two different random draws against each other.
SELECT RANDOM() BETWEEN 0.0 AND 1.0 as random_is_always_in_unit_range;
-- ============================================================
-- LIMIT / OFFSET
-- ============================================================
CREATE TABLE limit_demo (id INT);
INSERT INTO limit_demo VALUES (1);
INSERT INTO limit_demo VALUES (2);
INSERT INTO limit_demo VALUES (3);
INSERT INTO limit_demo VALUES (4);
INSERT INTO limit_demo VALUES (5);
-- LIMIT ALL means "no limit" (same as omitting LIMIT entirely)
SELECT * FROM limit_demo ORDER BY id LIMIT ALL;
-- LIMIT/OFFSET accept any constant expression, not just a bare literal
SELECT * FROM limit_demo ORDER BY id LIMIT 2 + 1 OFFSET 1 * 2;
-- SQL:2008 standard syntax: OFFSET n ROWS FETCH {FIRST|NEXT} m ROWS ONLY
SELECT * FROM limit_demo ORDER BY id OFFSET 1 ROWS FETCH FIRST 2 ROWS ONLY;
DROP TABLE limit_demo;
-- ============================================================
-- CONDITIONAL AND NULL HANDLING
-- ============================================================
-- NULL handling
SELECT COALESCE(NULL, NULL, 'default') as first_non_null;
SELECT NVL(NULL, 'replacement') as nvl_result;
SELECT IFNULL(NULL, 'value') as ifnull_result;
SELECT NULLIF(5, 5) as nullif_equal;
SELECT NULLIF(5, 3) as nullif_different;
-- Conditional
SELECT IF(10 > 5, 'yes', 'no') as if_result;
SELECT IIF(2 + 2 = 4, 'correct', 'wrong') as iif_result;
SELECT GREATEST(10, 25, 15, 30) as greatest_value;
SELECT LEAST(10, 25, 15, 30) as least_value;
-- CASE expressions
SELECT
CASE
WHEN 10 > 20 THEN 'impossible'
WHEN 10 > 5 THEN 'correct'
ELSE 'wrong'
END as case_result;
-- ============================================================
-- CRYPTOGRAPHIC AND ENCODING FUNCTIONS
-- ============================================================
-- Hashing
SELECT MD5('password') as md5_hash;
SELECT SHA1('password') as sha1_hash;
SELECT SHA256('password') as sha256_hash;
SELECT SHA512('password') as sha512_hash;
-- Encoding
SELECT BASE64('Hello World') as base64_encoded;
SELECT BASE64_DECODE('SGVsbG8gV29ybGQ=') as base64_decoded;
SELECT HEX('Hello') as hex_encoded;
SELECT UNHEX('48656C6C6F') as hex_decoded;
-- ============================================================
-- JSON FUNCTIONS
-- ============================================================
-- JSON columns decode stored JSON text; JSON_GET/JSON_EXTRACT read the value.
CREATE TABLE json_reference (id INT, meta JSON);
INSERT INTO json_reference VALUES (1, '{"name":"John","user":{"name":"Jane"},"items":[{"sku":"A"}]}');
SELECT JSON_GET(meta,'name') AS json_name, JSON_EXTRACT(meta,'user.name') AS nested_value FROM json_reference;
UPDATE json_reference SET meta=JSON_SET(meta,'items[0].sku','B') WHERE id=1;
SELECT JSON_GET(meta,'items[0].sku') AS updated_sku FROM json_reference;
DROP TABLE json_reference;
-- ============================================================
-- TYPE CONVERSION AND INTROSPECTION
-- ============================================================
-- Type casting
SELECT CAST('123' AS INTEGER) as string_to_int;
SELECT CAST(3.14 AS INTEGER) as float_to_int;
SELECT CAST(42 AS TEXT) as int_to_string;
-- Type checking
SELECT TYPEOF(42) as integer_type;
SELECT TYPEOF('text') as string_type;
SELECT TYPEOF(3.14) as float_type;
-- ============================================================
-- UTILITY FUNCTIONS
-- ============================================================
-- UUID generation
SELECT UUID() as unique_id;
-- Version info
SELECT VERSION() as tinysql_version;
-- ============================================================
-- WINDOW FUNCTIONS
-- ============================================================
-- Window functions operate on a set of rows (window) relative to the current row
-- Syntax: function() OVER (PARTITION BY ... ORDER BY ... frame_clause)
-- Create sample table for window function examples
CREATE TABLE window_demo (
product TEXT,
category TEXT,
sale_date TEXT,
amount INT
);
INSERT INTO window_demo VALUES ('Laptop', 'Electronics', '2025-01-15', 1200);
INSERT INTO window_demo VALUES ('Mouse', 'Electronics', '2025-01-20', 25);
INSERT INTO window_demo VALUES ('Desk', 'Furniture', '2025-01-25', 350);
INSERT INTO window_demo VALUES ('Keyboard', 'Electronics', '2025-02-10', 75);
INSERT INTO window_demo VALUES ('Chair', 'Furniture', '2025-02-15', 200);
-- ROW_NUMBER: Assign unique row numbers
SELECT
product,
amount,
ROW_NUMBER() OVER (ORDER BY amount) as row_num
FROM window_demo
ORDER BY amount;
-- ROW_NUMBER with PARTITION BY: Restart numbering per partition
SELECT
product,
category,
amount,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount) as row_in_category
FROM window_demo
ORDER BY category, amount;
-- RANK: like ROW_NUMBER, but tied rows share a rank and the next rank
-- skips ahead by the tie-group size (e.g. 1, 1, 3)
SELECT
product,
amount,
RANK() OVER (ORDER BY amount DESC) as rank_by_amount
FROM window_demo
ORDER BY amount DESC;
-- DENSE_RANK: like RANK, but no gaps after ties (e.g. 1, 1, 2)
SELECT
product,
amount,
DENSE_RANK() OVER (ORDER BY amount DESC) as dense_rank_by_amount
FROM window_demo
ORDER BY amount DESC;
-- PERCENT_RANK and CUME_DIST: relative standing within the partition, as a
-- fraction in [0, 1]
SELECT
product,
amount,
PERCENT_RANK() OVER (ORDER BY amount) as percent_rank,
CUME_DIST() OVER (ORDER BY amount) as cume_dist
FROM window_demo
ORDER BY amount;
-- NTILE: split the partition into N (approximately) equal-sized buckets
SELECT
product,
amount,
NTILE(3) OVER (ORDER BY amount) as tercile
FROM window_demo
ORDER BY amount;
-- LAG: Access previous row value
SELECT
product,
amount,
LAG(amount, 1) OVER (ORDER BY sale_date) as previous_amount
FROM window_demo
ORDER BY sale_date;
-- LAG with default value for first row
SELECT
product,
amount,
LAG(amount, 1, 0) OVER (ORDER BY sale_date) as previous_or_zero
FROM window_demo
ORDER BY sale_date;
-- LEAD: Access next row value
SELECT
product,
amount,
LEAD(amount, 1) OVER (ORDER BY sale_date) as next_amount
FROM window_demo
ORDER BY sale_date;
-- FIRST_VALUE: Get first value in window
SELECT
product,
amount,
FIRST_VALUE(product) OVER (ORDER BY amount) as cheapest_product
FROM window_demo
ORDER BY amount;
-- FIRST_VALUE with PARTITION BY
SELECT
product,
category,
amount,
FIRST_VALUE(product) OVER (PARTITION BY category ORDER BY amount) as cheapest_in_category
FROM window_demo
ORDER BY category, amount;
-- LAST_VALUE: Get last value in window (up to current row by default)
SELECT
product,
amount,
LAST_VALUE(product) OVER (ORDER BY amount) as most_expensive_so_far
FROM window_demo
ORDER BY amount;
-- MOVING_SUM: Calculate moving/rolling sum
SELECT
product,
sale_date,
amount,
MOVING_SUM(3, amount) OVER (ORDER BY sale_date) as rolling_sum_3days
FROM window_demo
ORDER BY sale_date;
-- MOVING_AVG: Calculate moving/rolling average
SELECT
product,
sale_date,
amount,
MOVING_AVG(3, amount) OVER (ORDER BY sale_date) as rolling_avg_3days
FROM window_demo
ORDER BY sale_date;
-- Complex example: LAG with PARTITION BY
SELECT
product,
category,
amount,
LAG(amount, 1) OVER (PARTITION BY category ORDER BY sale_date) as prev_in_category
FROM window_demo
ORDER BY category, sale_date;
-- Clean up
DROP TABLE window_demo;
-- ============================================================
-- COMPLEX QUERIES COMBINING MULTIPLE FUNCTIONS
-- ============================================================
-- Example 1: Date range analysis with period check
SELECT
CURRENT_DATE() as today,
DATE_TRUNC('MONTH', CURRENT_DATE()) as month_start,
EOMONTH(CURRENT_DATE()) as month_end,
IN_PERIOD('MTD', CURRENT_DATE()) as is_month_to_date,
DATEDIFF('DAYS', DATE_TRUNC('MONTH', CURRENT_DATE()), CURRENT_DATE()) as days_into_month;
-- Example 2: String processing with regex
SELECT
REGEXP_EXTRACT('Order #12345', '#(\d+)') as order_id,
UPPER(REGEXP_REPLACE('test@EXAMPLE.com', '@.*', '')) as username,
ARRAY_LENGTH(SPLIT('item1,item2,item3', ',')) as item_count;
-- Example 3: Numeric calculations
SELECT
ROUND(PI() * POWER(5, 2), 2) as circle_area_r5,
DEGREES(ATAN2(3, 4)) as angle_degrees,
ABS(SIGN(-42) * 100) as absolute_signed;
-- Example 4: Array operations
SELECT
FIRST(ARRAY_SORT(ARRAY_DISTINCT(SPLIT('zebra,apple,zebra,mango', ',')))) as first_sorted_unique,
ARRAY_JOIN(ARRAY_SORT(SPLIT('3,1,4,1,5,9', ',')), ' -> ') as sorted_numbers;
-- Example 5: Conditional logic with dates
SELECT
CASE
WHEN IN_PERIOD('TODAY', CURRENT_DATE()) THEN 'Today'
WHEN IN_PERIOD('MTD', CURRENT_DATE()) THEN 'This Month'
WHEN IN_PERIOD('QTD', CURRENT_DATE()) THEN 'This Quarter'
WHEN IN_PERIOD('YTD', CURRENT_DATE()) THEN 'This Year'
ELSE 'Historical'
END as period_classification;
-- Example 6: NULL handling with coalesce chain
SELECT
COALESCE(
NULL,
NULLIF('', ''),
REGEXP_EXTRACT('No match here', 'PATTERN'),
'Final Default'
) as coalesce_result;
-- ============================================================
-- PIVOT
-- ============================================================
-- PIVOT spreads the distinct values of one column into new output columns,
-- aggregating another column into each. Every other selected column becomes
-- an implicit GROUP BY key. Scope: one aggregate function and a static
-- (literal) value list.
CREATE TABLE pivot_demo (region TEXT, category TEXT, amount INT);
INSERT INTO pivot_demo VALUES ('East', 'Electronics', 100);
INSERT INTO pivot_demo VALUES ('East', 'Furniture', 50);
INSERT INTO pivot_demo VALUES ('West', 'Electronics', 200);
INSERT INTO pivot_demo VALUES ('West', 'Furniture', 75);
-- One row per region, one column per category, aliased for clean output names
SELECT *
FROM pivot_demo
PIVOT (SUM(amount) FOR category IN ('Electronics' AS electronics, 'Furniture' AS furniture));
-- WHERE filters the source rows before pivoting
SELECT *
FROM pivot_demo
WHERE amount >= 100
PIVOT (SUM(amount) FOR category IN ('Electronics' AS electronics));
-- COUNT works too, not just SUM
SELECT *
FROM pivot_demo
PIVOT (COUNT(amount) FOR category IN ('Electronics' AS electronics_count, 'Furniture' AS furniture_count));
DROP TABLE pivot_demo;
-- ============================================================
-- PRACTICAL USE CASES
-- ============================================================
-- Use Case 1: Email validation and extraction
SELECT
REGEXP_MATCH('user@example.com', '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$') as is_valid_email,
SPLIT_PART('user@example.com', '@', 1) as username,
SPLIT_PART('user@example.com', '@', 2) as domain;
-- Use Case 2: Date-based filtering helper
SELECT
IN_PERIOD('LAST_12_MONTHS', ADD_MONTHS(CURRENT_DATE(), -6)) as in_last_year,
IN_PERIOD('CURRENT_QUARTER', CURRENT_DATE()) as in_current_quarter,
EXTRACT('QUARTER', CURRENT_DATE()) as current_quarter_number;
-- Complex Example: DISTINCT ON + ROW_NUMBER, string concatenation,
-- column names with spaces, and timestamp helpers.
CREATE TABLE demo_orders (
order_id INT,
customer TEXT,
order_date TEXT,
total INT,
"customer name" TEXT
);
INSERT INTO demo_orders VALUES
(1, 'alice', '2025-01-10 09:15:00', 120, 'Alice A'),
(2, 'alice', '2025-02-05 14:20:00', 200, 'Alice A'),
(3, 'bob', '2025-01-12 11:05:00', 75, 'Robert B'),
(4, 'bob', '2025-03-01 08:30:00', 50, 'Robert B'),
(5, 'carol', '2025-02-20 16:45:00', 300, 'Carol C');
-- Use DISTINCT ON to pick the most recent order per customer.
-- Note: DISTINCT ON keeps the first row per key; ORDER BY controls which row is first.
SELECT DISTINCT ON (customer)
customer,
"customer name",
total,
order_date,
-- STRING CONCAT via + operator (also works with CONCAT)
customer + ' - ' + CAST(total AS TEXT) AS summary,
-- ROW_NUMBER demonstrates window function numbering per PARTITION
ROW_NUMBER() OVER (PARTITION BY customer ORDER BY order_date DESC) AS rn,
-- TIMESTAMP helpers
GETDATE() AS now_ts,
TODAY() AS today_date,
FROM_TIMESTAMP(0) AS epoch_zero,
TIMESTAMP('2023-05-01 00:00:00') AS ts_epoch
FROM demo_orders
ORDER BY customer, order_date DESC;
-- Show all rows with ROW_NUMBER and LAG for context
SELECT
order_id,
customer,
"customer name",
order_date,
total,
ROW_NUMBER() OVER (PARTITION BY customer ORDER BY order_date) AS rn_asc,
LAG(total, 1) OVER (PARTITION BY customer ORDER BY order_date) AS prev_total
FROM demo_orders
ORDER BY customer, order_date;
-- Cleanup demo table
DROP TABLE demo_orders;
-- Use Case 3: String normalization
SELECT
UPPER(TRIM(REGEXP_REPLACE(' Hello World ', '\s+', ' '))) as normalized_string;
-- Use Case 4: Array processing from CSV
SELECT
ARRAY_LENGTH(SPLIT('red,green,blue,yellow', ',')) as color_count,
ARRAY_CONTAINS(SPLIT('red,green,blue', ','), 'green') as has_green,
ARRAY_JOIN(ARRAY_SORT(ARRAY_DISTINCT(SPLIT('b,a,c,a,b', ','))), ',') as sorted_unique;
-- Use Case 5: Complex date arithmetic
SELECT
ADD_MONTHS(DATE_TRUNC('YEAR', CURRENT_DATE()), 6) as mid_year,
EOMONTH(ADD_MONTHS(CURRENT_DATE(), 3), 0) as end_of_quarter,
DATEDIFF('DAYS',
DATE_TRUNC('YEAR', CURRENT_DATE()),
EOMONTH(DATE_TRUNC('YEAR', CURRENT_DATE()), 11)
) as days_in_year;
-- ============================================================
-- CTE (Common Table Expression) EXAMPLES
-- ============================================================
-- Non-recursive CTE: useful for organizing complex subqueries
WITH recent_sales AS (
SELECT * FROM (SELECT '2025-01-01' AS sale_date, 'A' AS product) AS t
)
SELECT * FROM recent_sales;
-- Recursive CTE example: generate numbers 1..5
WITH RECURSIVE nums AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM nums WHERE n < 5
)
SELECT * FROM nums ORDER BY n;
-- Fibonacci via recursive CTE: generate first 10 Fibonacci numbers
WITH RECURSIVE fib AS (
-- n: index, a: current fib value, b: next fib value
SELECT 0 AS n, 0 AS a, 1 AS b
UNION ALL
SELECT n + 1, b, a + b FROM fib WHERE n < 9
)
SELECT n, a AS fib_value FROM fib ORDER BY n;
-- ============================================================
-- IO AND TRANSFORM FUNCTIONS
-- URL helpers: parse components, query values, references, and path segments
SELECT URL_PARSE('https://example.org/a%20b?q=geo+data#result') as url_components;
SELECT URL_QUERY_GET('https://example.org/search?q=geo+data', 'q') as query_value;
SELECT URL_RESOLVE('https://example.org/a/b/', '../tiles/12/2200/1400.pbf') as resolved_url;
SELECT URL_ENCODE('key=value & more') as encoded_query_value;
SELECT URL_DECODE('key%3Dvalue+%26+more') as decoded_query_value;
SELECT URL_PATH_ENCODE('tiles/Altstadt Nord') as encoded_path_segment;
SELECT URL_PATH_DECODE('tiles%2FAltstadt%20Nord') as decoded_path_segment;
-- Context-aware HTML rendering with JSON template data
SELECT HTML_ESCAPE('<strong>untrusted</strong>') as escaped_html;
SELECT HTML_TEMPLATE('<a href="{{.url}}">{{.label}}</a>',
'{"url":"/map","label":"Map & data"}') as rendered_html;
-- GUNZIP and its alias UNZIP accept up to 64 MiB of decoded output per call.
SELECT LENGTH(GZIP('tinySQL gzip test string')) as gzip_compressed_length;
SELECT GUNZIP(GZIP('roundtrip test')) as gunzip_roundtrip;
-- BASE64 encoding/decoding (safe examples)
SELECT BASE64_ENCODE('hello world') as base64_encoded_example;
SELECT BASE64_DECODE(BASE64_ENCODE('hello world')) as base64_decoded_roundtrip;
-- AccessWeb, tinysqld, cmd/server and the MCP server require -allow-sql-host-io for FILE and HTTP.
SELECT FILE('./data/data.json') as file_content;
-- HTTP: Fetch an HTTP GET response (30 second timeout, 8 MiB response limit)
SELECT HTTP('https://jsonplaceholder.typicode.com/todos/1') as http_response;
-- Combined example: Read and decompress a gzipped file
SELECT GUNZIP(FILE('./data/data.csv.gz')) as decompressed_content;
-- Combined example: Fetch and decode base64 data from HTTP
SELECT HTTP('https://jsonplaceholder.typicode.com/todos/1') as decoded_api_response;
SELECT * FROM TABLE_FROM_JSON(FILE('data/data.json')) ;
SELECT * FROM TABLE_FROM_CSV(FILE('data/sample.csv'), '{"delimiter":",","header":true}');
-- ============================================================
-- TABLE-VALUED FUNCTIONS (TVF)
-- ============================================================
-- Table-valued functions can be used in FROM and JOIN clauses.
-- File examples below use paths relative to the repository root.
-- TABLE_FROM_JSON: Parse JSON array into table
SELECT * FROM TABLE_FROM_JSON('[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]');
-- TABLE_FROM_JSON_LINES: Parse JSON Lines (JSONL) format
SELECT * FROM TABLE_FROM_JSON_LINES(FILE('data/data.jsonl'));
-- TABLE_FROM_CSV: Parse CSV data with configurable delimiter
SELECT * FROM TABLE_FROM_CSV(FILE('data/sample.csv'), '{"delimiter":",","header":true}');
-- Combined example: Query JSON data from HTTP endpoint
-- Use local demo JSON instead of external HTTP endpoint
SELECT * FROM TABLE_FROM_JSON(FILE('data/data.json')) WHERE id > 0;
-- Combined example: Join CSV file with database table
-- Ensure `users` demo table exists before JOIN examples
CREATE TABLE IF NOT EXISTS users (
id INT,
name TEXT,
email TEXT
);
INSERT INTO users VALUES (1, 'Alice', 'alice@example.com') ON CONFLICT DO NOTHING;
INSERT INTO users VALUES (2, 'Bob', 'bob@example.com') ON CONFLICT DO NOTHING;
INSERT INTO users VALUES (3, 'Carol', 'carol@example.com') ON CONFLICT DO NOTHING;
-- Combined example: Join CSV file with database table
SELECT u.name, o.amount
FROM users u
JOIN TABLE_FROM_CSV(FILE('./data/orders.csv'), '{"delimiter":",","header":true}') o ON u.id = o.user_id;
-- ============================================================
-- SYSTEM CATALOG
-- ============================================================
-- Note: System catalog tables are implemented and available via the Go API.
-- SQL syntax for querying catalog is planned for future release:
-- List all tables
SELECT * FROM catalog.tables;
-- Find columns for a specific table
SELECT * FROM catalog.columns WHERE table_name = 'users';
-- View all registered functions
SELECT name, function_type, return_type FROM catalog.functions;
-- Check scheduled jobs
SELECT name, enabled, schedule_type, next_run_at FROM catalog.jobs WHERE enabled = true;
-- ============================================================
-- JOB SCHEDULER
-- ============================================================
-- Note: Job scheduler is fully implemented and operational via the Go API.
-- SQL syntax for job management is planned for future release:
-- Create a CRON job
CREATE JOB cleanup_logs
SCHEDULE CRON '0 0 3 * * *' -- Daily at 3 AM
TIMEZONE 'UTC'
MAX_RUNTIME 300000 -- 5 minutes
NO_OVERLAP
AS
DELETE FROM logs WHERE created_at < datetime('now', '-7 days');
-- Create an INTERVAL job
CREATE JOB refresh_stats
SCHEDULE INTERVAL 30000 -- Every 30 seconds
MAX_RUNTIME 10000 -- 10 seconds
AS
INSERT INTO stats_cache SELECT * FROM compute_stats();
-- Create a ONCE job
CREATE JOB send_report
SCHEDULE ONCE '2025-12-31 23:59:59'
TIMEZONE 'America/New_York'
AS
SELECT generate_report('annual');
-- Enable/disable jobs
ALTER JOB cleanup_logs ENABLE;
ALTER JOB cleanup_logs DISABLE;
-- Drop a job
DROP JOB cleanup_logs;
-- ============================================================