Lesson 06 Working With Operators Constraints and Data Types
Lesson 06 Working With Operators Constraints and Data Types
Data Types
Learning Objectives
Syntax
Problem Statement: You are a junior analyst in your organization. You need to help the HR
team determine salaries of employees for different scenarios.
Objective: Use arithmetic operators to determine the new values based on each scenario.
Arithmetic Operators: Example
Consider the employee table given below, which has columns: Emp_ID, Emp_First_Name,
Emp_Last_Name, Emp_Salary, and Emp_Annual_Bonus.
Emp_Annual
Emp_ID Emp_F_Name Emp_L_Name Emp_Salary
Bonus
If you want to add the salary and bonus, use the addition operator. You get the following
results.
Syntax
SELECT Emp_ID, Emp_Salary +Emp_Annual_Bonus as
Emp_Total_Earning FROM Employee_Records;
Arithmetic Operators: Example
Suppose for the same table there is another column named deductions, and you are required
to deduct this amount from the final earning. Here, you should use the subtract operator.
Emp_ID Deductions
1256 200
1300 150
Syntax
SELECT Emp_ID, Emp_Salary – Deductions as Emp_Final_Earning
FROM Employee_Records;
Arithmetic Operators: Example
If you want to increase the salary of employees by two times, then you must use the
multiplication operator to get the following results.
Syntax
SELECT Emp_Salary * 2 as New_Salary FROM Employee_Records;
Arithmetic Operators: Example
Similarly, if you want to reduce the salary of each employee by 50%, then you can use the
division operator to obtain the following results.
Syntax
SELECT Emp_Salary / 2 as New_Salary FROM Employee_Records;
Bitwise Operators
Bitwise operators perform bit manipulations between two expressions of integer data type.
Operator Description
& AND
│ OR
^ Exclusive OR
They take two integer values, convert them to binary bits, and then apply AND, OR, or NOT
operations on each bit.
Bitwise Operators: Example
Consider the same employee table used for arithmetic operators. If you want to apply Bitwise AND on
salary and annual bonus, use the syntax below.
Syntax
Syntax
For Bitwise OR operation, use the syntax given below.
SELECT Emp_Salary | Emp_Annual_Bonus from Employee_Records;
Comparison Operators
Comparison operators compare values between operands and return TRUE or FALSE based
on the condition.
Operator Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
Syntax
The example that was shown before has been used here. If you want to find the employees whose
salary is more than 2500, then you use the greater than operator.
Syntax
SELECT Emp_ID, Emp_Salary from Employee_Records WHERE
Emp_Salary > 25000;
Similarly, other comparison operators like less than, equal to, greater than equal to, or less
than equal to can be used based on the requirement.
Compound Operators
Compound operators operate where variables are operated upon and assigned in the same line.
Syntax
SELECT column1+= condition FROM table1;
Logical Operators
Logical operators compare two conditions at a time to determine whether a row can be selected for an
output or not.
Syntax
SELECT column1, column 2 FROM table1 WHERE logical condition;
Syntax:
Logical Operators: Example
Consider the same employee records table. If you want to extract data based on two conditions, that
are salary and location, then you use the AND operator.
Syntax
If you want to extract data based on any one of the two conditions mentioned, that are salary or annual
bonus, then you use OR operator.
Syntax
Syntax:
Logical Operators: Example
If you want to extract data by excluding a certain data record, that is, excluding employees from New
York, then you use the NOT operator.
Syntax
Syntax:
Logical Operators: Example
If you want to extract data starting with a specific character or ending with a specific character, that is
employees whose name starts with M, then the LIKE operator is used.
Syntax
Syntax:
Assisted Practice: Logical Operator
Duration: 20 Mins
Problem Statement: You are required to use a logical operator to identify the candidates in the age
group of 22 to 35 from the created table in the MySQL Workbench.
Assisted Practice: Logical Operator
Steps to be performed:
1. Create a database example, then make a table candidates that has columns FirstName, LastName,
and Age.
TABLE CREATION
Steps to be performed:
2. Insert values in the table candidates.
VALUE INSERTION
Steps to be performed:
3. Write a query to select all the people in the age group of 22 to 35.
QUERY
Indexes are used to find rows with specific column values quickly.
Indexing in MySQL
Create Index
Indexing in MySQL
Syntax
CREATE TABLE t_index
(
col1 INT PRIMARY KEY,
col2 INT NOT NULL,
col3 INT NOT NULL,
col4 VARCHAR(20),
INDEX (col2,col3)
);
Indexing in MySQL
Syntax
Problem statement: Consider the junior DBA wants to improve the speed and result of the query by
adding an index.
Instructions: Refer the emp_data table which was created and shown before.
Table Description
EMP_ID Employee ID
ROLE Designation of the employee (Junior, Senior, Lead, and Associate Data
Scientist)
Rating for the employee (1: Not Achieved Any Goals, 2: Below
EMP_RATING Expectations, 3: Meeting Expectations, 4: Excellent Performance, 5:
Overachiever
Execute the following statement to return the result of the employee who is a manager:
Example:
If you want to check how MySQL performs the previous query internally, execute the following query:
Example:
Example:
CREATE INDEX indx ON sys.emp_data (role);
If you want to show the indexes of a table, execute the following query:
Example:
If you want to drop the index of a table, execute the following query:
Example:
SELECT
Returns or derives the
required data
1
HAVING FROM
Filters the aggregated 6 2 Selects the table from
data which the data is obtained
3 JOIN
GROUP BY 5
Derives common data
Aggregates the data
from a different table
4
WHERE
Applies a condition to
filter data
Order of Execution: Example
Consider the following syntax taken from the example of logical operators.
Syntax
Here, the FROM clause is executed first to determine the table. Next, the WHERE clause is executed
to determine the condition. The SELECT statement is executed to extract the data that satisfies this
condition in the table.
Order of Execution: Example
Consider that you have a customers table with customer ID, customer name, and their location.
If you want to identify the locations of more than five customers, then use the following syntax.
Syntax
Here, the FROM clause is executed first to determine the table. Next, the GROUP BY clause
aggregates the same location records. It is followed by the HAVING clause that determines the
condition. The SELECT statement is executed to extract the data that satisfies this condition in the
table.
MySQL Constraints
MySQL Constraints
Constraint is a condition that specifies the type of data that can be entered into a table.
NOT NULL constraint prevents the column from having NULL or empty values.
Example
CREATE table Employee (ID int, First_Name text NOT NULL, Last_Name text NOT_NULL,
City VARCHAR(30))
Primary Constraint
Primary constraint provides a distinct identity to each record in a table. A table can only have one
primary key.
Example
CREATE table People (ID int Primary Key, Name varchar (30) NOT NULL, Age int)
Primary and NOT NULL Constraints: Example
Problem Statement: As a product manager, you are required to create a table with product details,
such as product ID which is the primary key, product name, and date of manufacturing which is not a
not value.
Example
CREATE table Product_Details (Pro_ID int Primary Key, Pro_Name varchar (30) NOT
NULL, Date_Manf DATE);
Primary and NOT NULL Constraints: Example
After creating the table, if there is no record for the NOT NULL field as shown below, then you are
prompted with an error.
Example
Foreign key constraint is used to connect two tables. It corresponds to the primary key of a
different table.
Example
CREATE table Teachers (Teacher_ID int Primary Key, Name varchar (30) NOT NULL,
Age int, College_ID int Foreign Key )
Disable Foreign Key Check
Foreign key check is a feature in SQL that prevents us from making any changes to tables that have
foreign keys in them.
Example
SET foreign_key_checks = 0
Foreign Key Constraint: Example
Problem statement: You are the sales manager of a store. You have data of your customers and their
orders in two different tables. You must ensure that the customer data added to the table on orders is
not different from the original data.
Objective: Use a foreign key to specify the column that must contain only the data present in the
primary table.
Foreign Key Constraint: Example
Steps to perform:
• Create a table with data on customers, like customer name, last name, age, and customer ID as
primary key
• Create a table with data on orders, with order ID, order number, and person ID as the foreign key
• Set foreign key to zero to ensure that there are no external changes
Foreign Key Constraint: Example
After creating the two tables, set foreign check to zero and insert them with the following data:
Example
If you try to enter any customer ID that is not present in the customers table, MySQL will
prompt an error.
Unique Constraint
Unique constraint ensures that there are no entries with the same value in a column.
Example
Create table Names (ID int NOT NULL, Name varchar (30), Age int, UNIQUE (ID))
Unique Constraint: Example
Create a table named names using the syntax shown before. Add values to this table.
Example
insert into names (ID, Name, Age) values (1, 'George', 35),(2, 'Lily', 28);
You can see that there is an ID with 2 as value. If you try to enter a new record with the same ID, you
will be prompted with the following error.
Check Constraints
Check constraint can be used to verify the value being entered into a record.
Example
Create table Tenants (ID int NOT NULL, Name varchar (30), Age int, Check
(Age >=18))
Check Constraints: Example
Consider the example shown before for unique constraint. Add the check condition to verify that ID is
not more than 10.
Example
Create table Names (ID int NOT NULL, Name varchar (30), Age int, UNIQUE (ID),
Check (ID<=10));
When the ID entered is more than 10, the you will get the following error prompt.
Check Constraints Emulation
Duration: 10 Min.
Problem Statement: You are required to create a new table with constraints and assign
Candidate_No. as the primary key in the MySQL Workbench.
Assisted Practice: Constraint
Steps to be performed:
1. Create a table named candidates, name columns as Candidate_No., FirstName, LastName, and
Age, and assign Candidate_No. as the primary key.
TABLE CREATION
CREATE TABLE `example`.`candidates` (
Data type refers to the nature or format of data that is entered into the database.
VARCHAR 2 3 BINARY
CHAR 1 4 VARBINARY
LONGTEXT 7 5 TEXT
6
TINYTEXT
String Data Type: Example
Problem Statement: You are an IT administrator and want to create a table that shows the office
assets assigned to each employee, with the employee ID, employee Name with a restriction of number
of characters, and asset name which does not have any character limit.
Objective: Create a table with employee name of char data type and asset name of varchar data type.
String Data Type: Example
Syntax
Employee name has a character limit. When you enter a longer name as shown below in the third
instance, you will get an error notification.
Syntax
insert into Asset_Tracker (Emp_ID, Emp_Name, Asset_Name)
values (23, 'Michael', 'Printer'),(46, 'John', 'Laptop'),(36,
'Samantha', 'Desktop Printer');
Numeric Data Types in SQL
INT FLOATING
Used to represent integer value Used to specify a number in floating
point format
NUMERIC
BIT DATA DOUBLE CHECK
Used to denote bit-value type Used as a standard floating-point
number
Numeric Data Type: Example
Problem Statement: You are a sales manager who wants to create a table with price and quantity of
each item that has been sold.
Objective: Create a table with product name, quantity, and price with varchar, int, and float data
type respectively.
Numeric Data Type: Example
Syntax
CREATE TABLE Sales_Tracker (Pro_Name varchar(255), Pro_Price float,
Pro_Quantity int);
Price is a float data type, because prices can have decimal values; quantity is always an integer.
Syntax
insert into Sales_Tracker (Pro_Name, Pro_Price, Pro_Quantity) values (‘Mobiles’,
8999.99, 26),(‘Laptops’,24455.77, 48),(‘Washing_Machines’,2344.55, 34);
Date and Time Data Types in SQL
DATE DATETIME
TIME TIMESTAMP
Assisted Practice: Data Type
Duration: 10 Min.
Problem Statement: You are required to create a new table with a field DOB with datatype as DATE in
the MySQL Workbench.
Assisted Practice: Data Type
Steps to be performed:
1. Create a table named candidates; name columns: Candidate_No. as Integer, FirstName
as Varchar, LastName as Varchar, Age as Integer, and DOB as Date. Assign Candidate_No.
as the primary key.
TABLE CREATION
A. Comparison operators
B. Compound operators
C. Logical operators
D. Arithmetic operators
Knowledge
Check
Which of the following operators is used to compare two conditions?
1
A. Comparison operators
B. Compound operators
C. Logical operators
D. Arithmetic operators
A. WHERE
B. FROM
C. SELECT
D. HAVING
Knowledge
Check In the logical sequence of execution in an SQL query, which of the following clauses is
2 processed first?
A. WHERE
B. FROM
C. SELECT
D. HAVING
A. Primary key
B. Foreign key
C. Unique constraint
D. Check constraint
Knowledge
Check Which of the following constraints is used to provide a unique identity to a column in
3 a table?
A. Primary key
B. Foreign key
C. Unique constraint
D. Check constraint
Primary key is the constraint that is used to provide a unique identity to a column in a table.
Lesson-End Project: School Ranking Analysis
Problem statement:
You are a database administrator in an institution, and you have been asked
to store the students’ details and their marks to track their progress. The
database helps to view the students’ marks with a rank that can be viewed,
updated, and evaluated to evaluate their performance.
Objective:
The objective is to design a database to retrieve the information of a student
as needed for the records.
Tasks to be performed:
1. Write a query to create a students table with the student ID, first name,
last name, class, and age fields and ensure that the last name, first name,
and student ID fields have the NOT NULL constraint and that the student
ID field is a primary key
2. Write a query to create a marksheet table with score, year, ranking, class,
and student ID fields
3. Write a query to insert values into the students and marksheet tables
Lesson-End Project: School Ranking Analysis
Tasks to be performed:
4. Write a query to display the student ID and first name of every student in
the students table whose age is greater than or equal to 16 and whose
last name is Kumar
5. Write a query to display the details of every student from the marksheet
table whose score is between 800 and 1000
6. Write a query to increase the score in the marksheet table by five and
create a new score column to display this new score
Lesson-End Project: School Ranking Analysis
Tasks to be performed:
Note: Download the solution document from the Course Resources section
and follow the steps given in the document
Key Takeaways