-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.sql
More file actions
51 lines (44 loc) · 1.55 KB
/
program.sql
File metadata and controls
51 lines (44 loc) · 1.55 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
-- Branchless Programming Examples in MariaDB SQL
-- Demonstrates arithmetic-based conditionals without CASE/IF statements
-- Function to determine the sign of an integer (1 for positive/zero, 0 for negative)
-- Uses: (num >= 0) evaluates to 1 or 0 in MariaDB
DELIMITER //
CREATE FUNCTION getSign(num INT) RETURNS INT DETERMINISTIC
BEGIN
-- Boolean expression returns 1 if true, 0 if false
-- No IF/CASE needed - arithmetic comparison is branchless
RETURN (num >= 0);
END//
DELIMITER ;
-- Function to find the minimum of two integers using branchless approach
DELIMITER //
CREATE FUNCTION minBranchless(a INT, b INT) RETURNS INT DETERMINISTIC
BEGIN
-- (a < b) returns 1 if true, 0 if false
-- a * (a < b) + b * (a >= b) selects the smaller value
RETURN a * (a < b) + b * (a >= b);
END//
DELIMITER ;
-- Function to find the maximum of two integers using branchless approach
DELIMITER //
CREATE FUNCTION maxBranchless(a INT, b INT) RETURNS INT DETERMINISTIC
BEGIN
RETURN a * (a > b) + b * (a <= b);
END//
DELIMITER ;
-- Test the functions
SELECT 'Sign Tests:' AS test_type;
SELECT 42 AS num, getSign(42) AS sign
UNION ALL SELECT -7, getSign(-7)
UNION ALL SELECT 0, getSign(0);
SELECT 'Min/Max Tests:' AS test_type;
SELECT 15 AS a, 9 AS b,
minBranchless(15, 9) AS min_result,
maxBranchless(15, 9) AS max_result;
SELECT 3 AS a, 7 AS b,
minBranchless(3, 7) AS min_result,
maxBranchless(3, 7) AS max_result;
-- Cleanup
DROP FUNCTION IF EXISTS getSign;
DROP FUNCTION IF EXISTS minBranchless;
DROP FUNCTION IF EXISTS maxBranchless;