0% found this document useful (0 votes)
48 views9 pages

SQL Operators Functions and Keywords

SQL operators and functions notes

Uploaded by

damasdaniel653
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views9 pages

SQL Operators Functions and Keywords

SQL operators and functions notes

Uploaded by

damasdaniel653
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

FUNCTIONS AND OPERATORS IN SQL

Working with functions and operators in SQL is essential for performing various operations on
data within relational databases.
OPERATORS, OPERANDS, EXPRESSIONS
WHAT IS AN OPERATOR?
AN OPERATOR: is a symbol that tells the compiler/interpreter to perform specific
mathematical, relational or logical operation to produce a desired result.
In 5 + 8 =13, a (+) is an operator.

WHAT IS AN OPERAND?
AN OPERAND: is an object which is operated upon by any operator to produce a result.
In 5 + 8 =13, (5 and 8) are operands.

WHAT IS AN EXPRESSION?
AN EXPRESSION: is a combination of one or more operators and operands which together
produce a meaningful result.
In 5 + 8 =13, (5 + 8) is an expression.
NB: every operator has its own type of operands on which they can operate. They cannot operate
on every kind of operands.
Basically, there are four types of operators.

OPERATORS
ARITHMETIC OPERATORS - (+,-,/,*,%)
COMPARISON OPERATORS - (=,>;<,>=,<=,<>/!=)
LOGICAL OPERATORS - (AND, OR,LIKE,BETWEEN,NOT)
BITWISE OPERATORS - (&,|,^) : This will not be covered

ARITHMETIC OPERATORS
They are used for mathematical calculations.

+ Addition 7+5=12 Gives sum of operands


- Subtraction 7-5=2 Gives difference of operands
* Multiplication 7*5=35 Gives product of operands
/ Division 7/5=1.4 Gives quotient of 7 divided by 5
% Modulo 7%5=2 Gives remainder of 7 divided by 5

COMPARISON OPERATORS
They are used to compare the operands and give results in TRUE & FALSE

= Equals to 5=5 Gives true if operands are equal


> Greater than 5>4 Gives true if left operand is greater
< Less than 3<5 Gives true if left operand is lesser
>= Greater than or 5>=5 Gives true if left operand is greater or equal to
Equals to right operand
<= Less than or Equals 5<=6 Gives true if left operand is lesser or equal to
to right operand
< > OR Not Equals to 5< Gives true if operands are unequal
!= >3

NB: True is denoted by 1 and False is denoted by 0.

LOGICAL OPERATORS
They connect two or more Boolean expressions such that the result of the compound expression
depends on the result of the original expressions and on the meaning of the operator. Results are
in True and False.

AND 3!=5 AND 11>5 Gives true if all conditions separated by AND are true
OR 5>4 OR 10=6 Gives true if any conditions separated by OR is
TRUE.
NOT NOT 2<4 Gives true if condition is false, false if condition is
true
LIKE ‘Hello’ LIKE ‘%o’ Gives true if operand matches a pattern
BETWEEN 4 BETWEEN 1 AND 10 Gives true if operand is within the range of
comparisons.
MORE FROM AI

Fundamental operators for constructing SQL queries with various conditions and logic.

Operator Description Example SQL Statement


= Equal to SELECT * FROM table_name WHERE column_name = value;
<> or != Not equal to SELECT * FROM table_name WHERE column_name <> value;

> Greater than SELECT * FROM table_name WHERE column_name > value;

< Less than SELECT * FROM table_name WHERE column_name < value;

>= Greater than or equal to SELECT * FROM table_name WHERE column_name >= value;
<= Less than or equal to SELECT * FROM table_name WHERE column_name <= value;
SELECT * FROM table_name WHERE column_name BETWEEN
BETWEEN Between a range value1 AND value2;
SELECT * FROM table_name WHERE column_name LIKE
LIKE Pattern matching pattern;
SELECT * FROM table_name WHERE column_name IN (value1,
IN Matches any value in a list value2, ...);
SELECT * FROM table_name WHERE column_name NOT IN
NOT IN Does not match any value in a list (value1, value2, ...);
IS NULL Checks if a value is NULL SELECT * FROM table_name WHERE column_name IS NULL;
IS NOT
NULL Checks if a value is not NULL SELECT * FROM table_name WHERE column_name IS NOT NULL;
SELECT * FROM table_name WHERE condition1 AND
AND Logical AND condition2;
SELECT * FROM table_name WHERE condition1 OR
OR Logical OR condition2;
NOT Negates a condition SELECT * FROM table_name WHERE NOT condition;
Used with IN or NOT IN for pattern
SELECT * FROM table_name WHERE column_name LIKE
LIKE matching pattern;

Examples of commonly used SQL functions.

Function
Name Purpose Example SQL Statement
Counts the number of rows
COUNT() in a result set SELECT COUNT(*) FROM table_name WHERE condition;

SUM() Calculates the sum of values SELECT SUM(column_name) FROM table_name WHERE condition;
Calculates the average of
AVG() values SELECT AVG(column_name) FROM table_name WHERE condition;

MIN() Finds the minimum value SELECT MIN(column_name) FROM table_name WHERE condition;
MAX() Finds the maximum value SELECT MAX(column_name) FROM table_name WHERE condition;
Function
Name Purpose Example SQL Statement
Converts a string to
UPPER() uppercase SELECT UPPER(column_name) FROM table_name WHERE condition;
Converts a string to
LOWER() lowercase SELECT LOWER(column_name) FROM table_name WHERE condition;
Concatenates two or more
SELECT CONCAT(column1, column2) AS concatenated_string
CONCAT() strings FROM table_name WHERE condition;
Extracts a substring from a
SELECT SUBSTRING(column_name, start_index, length) FROM
SUBSTRING() string table_name WHERE condition;
SELECT DATE_FORMAT(date_column, 'format_string') FROM
DATE_FORMAT() Formats date values table_name WHERE condition;
Calculates the difference
SELECT DATEDIFF(end_date, start_date) AS date_difference
DATEDIFF() between dates FROM table_name WHERE condition;
Returns the first non-null
SELECT COALESCE(column1, column2, default_value) FROM
COALESCE() expression table_name WHERE condition;
Returns one of two values
SELECT IF(condition, value_if_true, value_if_false) FROM
IF() depending on a condition table_name;
CASE SELECT CASE WHEN condition1 THEN result1 WHEN condition2
statement Conditional logic THEN result2 ELSE default_result END FROM table_name;

A list of commonly used SQL keywords along with their descriptions

Keyword Description Example SQL Statement


Retrieves data from one or more
SELECT column1, column2 FROM table_name WHERE
SELECT tables condition;
INSERT INTO table_name (column1, column2) VALUES
INSERT Adds new rows into a table (value1, value2);
UPDATE table_name SET column1 = value1, column2 =
UPDATE Modifies existing rows in a table value2 WHERE condition;

DELETE Removes rows from a table DELETE FROM table_name WHERE condition;
Creates a new table, index, view, or
CREATE TABLE table_name (column1 datatype, column2
CREATE other database object datatype, ...);
Modifies an existing database
ALTER object ALTER TABLE table_name ADD column_name datatype;

DROP Deletes an existing database object DROP TABLE table_name;


Removes all rows from a table, but
TRUNCATE keeps the structure TRUNCATE TABLE table_name;
Combines rows from two or more
SELECT * FROM table1 JOIN table2 ON
JOIN tables based on a related column table1.column_name = table2.column_name;
Keyword Description Example SQL Statement

INNER
Returns only the rows that have SELECT * FROM table1 INNER JOIN table2 ON
JOIN matching values in both tables table1.column_name = table2.column_name;
Returns all rows from the left table,
and the matched rows from the
SELECT * FROM table1 LEFT JOIN table2 ON
LEFT JOIN right table table1.column_name = table2.column_name;
Returns all rows from the right
RIGHT
table, and the matched rows from SELECT * FROM table1 RIGHT JOIN table2 ON
JOIN the left table table1.column_name = table2.column_name;
Returns rows when there is a match
SELECT * FROM table1 FULL JOIN table2 ON
FULL JOIN in one of the tables table1.column_name = table2.column_name;
Filters rows based on specified
WHERE conditions SELECT * FROM table_name WHERE condition;
Groups rows that have the same
SELECT column_name1, COUNT(column_name2) FROM
GROUP BY values into summary rows table_name GROUP BY column_name1;
Filters groups based on specified SELECT column_name1, COUNT(column_name2) FROM
table_name GROUP BY column_name1 HAVING
HAVING conditions COUNT(column_name2) > value;
Sorts the result set by one or more SELECT * FROM table_name ORDER BY column_name
ORDER BY columns ASC/DESC;
Limits the number of rows returned
LIMIT by a query SELECT * FROM table_name LIMIT number_of_rows;
Specifies the starting point for the
SELECT * FROM table_name LIMIT number_of_rows OFFSET
OFFSET results returned by the LIMIT clause offset_value;
DISTINCT Returns unique values in a column SELECT DISTINCT column_name FROM table_name;
Renames a column or table in the
AS result set SELECT column_name AS alias_name FROM table_name;

PRACTICAL EXAMPLE

GROUPING AND AGGREGATING DATA


Let's create a scenario where we have a database of students and their exam scores in different
subjects. We'll have two tables: one for student information and another for their exam scores.

1. Student Table (students):

• Columns: student_id (Primary Key), student_name, age, gender

2. Exam Scores Table (exam_scores):


• Columns: student_id (Foreign Key), subject, score

Let's populate these tables with some sample data:

-- Create students table


CREATE TABLE students (
student_id INT(10) PRIMARY KEY,
student_name VARCHAR(50),
age INT(3),
gender VARCHAR(10)
);

-- Insert sample data into students table


INSERT INTO students (student_id, student_name, age, gender)
VALUES
(1, 'John Doe', 20, 'Male'),(2, 'Jane Smith', 22, 'Female'),
(3, 'Alice Johnson', 21, 'Female'), (4, 'Bob Williams', 23, 'Male'),
(5, 'Emily Brown', 19, 'Female'), (6, 'Bob wine', 27, 'Male');

-- Create exam_scores table


CREATE TABLE exam_scores (
score_id INT(10) PRIMARY KEY,
student_id INT(10),
subject VARCHAR(50),
score INT(3),
FOREIGN KEY (student_id) REFERENCES students(student_id)
);

-- Insert sample data into exam_scores table


INSERT INTO exam_scores (score_id, student_id, subject, score)
VALUES
(1, 1, 'Math', 85),(2, 1, 'Science', 90), (3, 1, 'English', 88),(4, 2, 'Math', 78),
(5, 2, 'Science', 92), (6, 2, 'English', 85),(7, 3, 'Math', 90), (8, 3, 'Science', 88),
(9, 3, 'English', 91),(10, 4, 'Math', 82),(11, 4, 'Science', 80), (12, 4, 'English', 75),
(13, 5, 'Math', 88), (14, 5, 'Science', 86),(15, 5, 'English', 90);

let's write SQL statements to group and aggregate the data:

1. Grouping Data:
-- Group exam scores by subject and calculate average score for each subject
SELECT subject, AVG(score) AS average_score
FROM exam_scores GROUP BY subject;

2. Aggregating Data:
-- Calculate the total number of students and average age of students
SELECT COUNT(*) AS total_students, AVG(age) AS average_age FROM students;

3. Filtering Grouped Data:


using the HAVING clause to filter the grouped data:
-- Group exam scores by subject and calculate average score for each subject, but only show subjects
with an average score greater than 85
SELECT subject, AVG(score) AS average_score FROM exam_scores GROUP BY subject

HAVING AVG(score) > 85;

NB: This query will group the exam scores by subject and calculate the average score for each subject, but
it will only display subjects with an average score greater than 85.

You might also like