Many SQL operators go unnoticed or do not seem to be used widely. They can be handy to pull data from your database. Like: BETWEEN and NOT BETWEEN, IN and NOT IN, LIKE and NOT LIKE, NULL and NOT NULL, Calculated or Virtual field.
BETWEEN checks if a value is between two other values. The comparison is always inclusive, and the value of the arrange must be arranged from lower to higher.
SELECT * FROM Employees WHERE Salary BETWEEN 50000 AND 70000;
NOT BETWEEN is opposite of BETWEEN.
SELECT * FROM Employees WHERE Salary NOT BETWEEN 50000 AND 70000;
The IN operator checks if a given value is found within a list of values (Placed in parentheses). The value to check must match a full (not partial) value on the list. The list could be in any order:
SELECT * FROM Employees WHERE Dept IN ('SL', 'IT', 'MK');
NOT IN will give us the opposite result of IN:
SELECT * FROM Employees WHERE Dept NOT IN ('SL', 'IT', 'MK');
The LIKE operator performs text comparisons with wildcards. The wildcard symbols used are:
%
_ (Underscore)
SELECT * FROM Employees WHERE LName LIKE 'M%';
SELECT * FROM Employees WHERE LName LIKE '_M%';
There is also a NOT LIKE operator to reverse the results:
SELECT * FROM Employees WHERE LName NOT LIKE 'M%';
The "=" operator cannot be used to match NULL values. It will evaluate to unknown (NULL in MySQL), even the value being compared to is in fact NULL.
SELECT * FROM Employees WHERE Phone = NULL;
SELECT * FROM Employees WHERE Phone <> NULL;
SELECT * FROM Employees WHERE Phone IS NULL;
SELECT * FROM Employees WHERE Phone IS NOT NULL;
Besides including the fields (Columns) from your tables in the SELECT statement, you can define Calculated/Virtual fields "On the fly". For instance, assume that you want to see what each employee's total earnings will be by adding their salary and bonus columns:
SELECT FName, LName, Salary + Bonus FROM Employees;
SELECT FName, LName, Salary + Bonus FROM Employees;
By default, SQL will use the expression itself as the column heading. Therefore, it is best to use an Alias for a calculated field:
SELECT FName, LName, Salary + Bonus AS `Gross Pay` FROM Employees;
It's not allowed to refer to a column Alias in a WHERE clause, so we would have to repeat the expression in the following case:
SELECT FName, LName, Salary + Bonus AS `Gross Pay` FROM Employees WHERE Salary + Bonus >= 80000;