Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of % in SQL

Tags:

sql

Could someone explain the difference between % in SQL?

I understand that % is a wildcard that allows you to query results with LIKE results, i.e. a% for words starting with a, but I am confused why the wildcard can be used as % 2 = 0 to query for even numbers?

I saw an explanation that said % can be used as divide but I thought / was divide.

like image 638
Josh Neal Avatar asked Oct 27 '25 10:10

Josh Neal


2 Answers

a % 2 = 0 here % as Modulus arithmetic operator.

Syntax: dividend % divisor

Sample: SELECT 15 % 2 AS Remainder it will return the result as 1

Demo on db<>fiddle

like image 187
Arulkumar Avatar answered Oct 28 '25 22:10

Arulkumar


When used outside of a string, the percentage symbol % is the modulus operator, i.e. an operator which returns the remainder following division of the number preceding the operator by that following it.

Therefore, in your example, the expression % 2 = 0 will be validated if the number preceding the percentage symbol is even, e.g. 12 % 2 = 0 will return True.

Whereas, when used in the pattern argument of a like expression, the percentage symbol represents a wildcard operator matching any sequence of characters (or no characters at all).

like image 40
Lee Mac Avatar answered Oct 29 '25 00:10

Lee Mac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!