Primers -RDBMS My SQL
Primers -RDBMS My SQL
Evolution to DBMS
1. Centralized Storage
○ Data stored in one location (centralized repository).
○ Supports multiple storage models:
■ Relational Model
■ Hierarchical Model
■ Network Model
2. Improved Data Security
○ Access restricted to authorized users.
○ Policies enforce strict control over data usage.
3. Reduced Redundancy and Inconsistency
○ Data stored once and accessed by all authorized users.
○ Eliminates multiple unsynchronized copies of data.
4. Multi-User Access
○ Simultaneous data access for multiple users from various locations.
5. Backup and Recovery
○ Advanced features for data backup and recovery in case of system
failures.
6. Flexibility and Scalability
○ Supports large volumes of data and dynamic processing needs.
1. Data
○ Raw facts/details (e.g., a number, text, or image).
○ Example: 378-400-1234 could be a phone number or ID but is
meaningless without context.
2. Information
○ Data becomes meaningful when given context (e.g., storing
378-400-1234 as a phone number).
3. Records
○ Logical fields containing items of information grouped together (e.g.,
customer details: name, phone, address).
Introduction to ER Model
1. Key Concepts:
○ Entities: Real-world objects or things represented in a database.
■ Example: John Doe (Employee), Sales (Department).
○ Attributes: Properties describing an entity.
■ Example: Name, ID, Address, DOB.
■ Simple Attributes: Single atomic values (e.g., ID).
■ Composite Attributes: Made of components (e.g., Address =
Street + City + Zip).
2. Entity Type:
○ Grouping of entities sharing similar attributes.
○ Example: Employee with attributes like Name, Address, and Age.
3. Key Attributes:
○ Unique Identifiers: Distinguish each entity instance (e.g., Employee
ID).
○ Composite Keys: Combination of attributes ensuring uniqueness
(e.g., Dept No + Employee No).
4. Relationships:
○ Link Between Entities: E.g., John works in Sales.
○ Relationship Type: Grouping of similar relations (e.g., Works In).
○ Degree of Relationship: Number of participating entities:
■ Binary: Two entities (e.g., Employee-Department).
■ Cardinality:
■ 1:1: One employee works in one department.
■ 1:N: One employee works in multiple departments.
■ M:N: Multiple employees work on multiple projects.
■ Optionality: Determines if relationships are mandatory or
optional.
5. ER Diagram Components:
○ Entities: Represented by rectangles.
○ Relationships: Lines connecting entities, labeled with the relationship
name.
○ Cardinality: Crowfoot notation (1:1, 1
,M
).
○ Optionality: Marked as O for optional or vertical line for mandatory.
Normalization
Conclusion
What is DDL?
1. CREATE TABLE
Syntax:
sql
Copy code
CREATE TABLE table_name (
...
);
Example:
sql
Copy code
CREATE TABLE student (
student_id INT,
student_name VARCHAR(20),
address VARCHAR(50),
department_id CHAR(2)
);
2. ALTER TABLE
Add columns:
sql
Copy code
ALTER TABLE table_name ADD column_name data_type [AFTER
existing_column];
Drop columns:
sql
Copy code
ALTER TABLE table_name DROP COLUMN column_name;
Rename columns:
sql
Copy code
ALTER TABLE table_name CHANGE old_column_name new_column_name
data_type;
3. DROP TABLE
Example:
sql
Copy code
DROP TABLE student;
4. RENAME TABLE
Rename the table:
sql
Copy code
RENAME TABLE old_table_name TO new_table_name;
Example:
sql
Copy code
RENAME TABLE student TO participant;
5. TRUNCATE TABLE
Example:
sql
Copy code
TRUNCATE TABLE participant;
Additional Notes:
Primary Key Addition: After creating a table, you can add a primary key:
sql
Copy code
ALTER TABLE table_name ADD PRIMARY KEY (column_name);
1.
2. Checking Table Structure: Use DESCRIBE table_name to view columns,
data types, and constraints.
3. Saving Scripts: Query scripts can be saved and executed as a whole or
selectively.
4. Execution: Use MySQL Workbench’s interface to run individual or multiple
queries.
Creating a Table with a Primary Key
Syntax example:
sql
Copy code
CREATE TABLE table_name (
column_name datatype,
);
○
2. Using Constraints for Primary Keys:
○ You can explicitly define a constraint for the primary key.
Syntax example:
sql
Copy code
CREATE TABLE table_name (
column_name datatype,
);
○
3. Importance of Naming Constraints:
○ Naming constraints is recommended because:
■ It avoids the system assigning a default name.
■ Makes management tasks, such as dropping constraints,
easier.
○ Without a named constraint, you would need to query the metadata to
find the auto-generated constraint name.
4. Dropping a Named Constraint:
○ Using a named constraint simplifies dropping it later.
Example:
sql
Copy code
ALTER TABLE table_name
1. Purpose:
○ The CREATE TABLE statement is used in SQL to create a table within
a schema or database.
Basic Syntax:
sql
Copy code
CREATE TABLE table_name (
column_name1 datatype(size),
column_name2 datatype(size),
...
);
2.
○ Steps:
1. Start with CREATE TABLE followed by the table_name.
2. Define the columns and their properties (e.g., datatype, size)
within parentheses.
3. Use commas to separate column definitions, except after the
last column.
3. Defining a Primary Key:
Example:
sql
Copy code
CREATE TABLE table_name (
column2 VARCHAR(30)
);
○
4. Adding a Foreign Key:
○
○ The referenced column must be a primary key in the other table.
Example:
sql
Copy code
CREATE TABLE staff (
staff_name VARCHAR(30),
department_id INT,
);
○
5. Constraints Overview:
○ Primary Key: Ensures unique, non-null values for the specified
column(s).
○ Foreign Key: Establishes a link between two tables, referencing the
primary key of another table.
○ Syntax:
1. Primary Key: Directly with the column or using CONSTRAINT.
2. Foreign Key: Add at the end of column definitions.
6. Tips:
○ Use descriptive names for constraints to simplify dropping or modifying
them later.
staff_id INT,
staff_name VARCHAR(30),
department_id INT,
);
○
7. Practical Demo:
○ Task: Create a staff table with the following specifications:
1. staff_id: Integer, Primary Key.
2. staff_name: VARCHAR(30).
3. department_id: Integer, Foreign Key referencing
department(department_id).
Code:
sql
Copy code
CREATE TABLE staff (
staff_name VARCHAR(30),
department_id INT,
○
○ Steps to execute:
1. Write the query in the editor.
2. Compile to check for syntax errors.
3. Evaluate for successful execution.
1. Purpose:
○ The ALTER TABLE statement modifies an existing table in a schema
or database.
Basic Syntax:
sql
Copy code
ALTER TABLE table_name
<modification_clause>;
2.
○ Replace <modification_clause> with the desired action (e.g.,
adding, dropping, or modifying a column).
3. Use Cases for ALTER TABLE:
○ Add a Column:
1. Add a new column to the table.
Syntax:
sql
Copy code
ALTER TABLE table_name
2.
Example:
sql
Copy code
ALTER TABLE busses
3.
○ Drop a Column:
1. Remove an existing column from the table.
Syntax:
sql
Copy code
ALTER TABLE table_name
2.
Example:
sql
Copy code
ALTER TABLE busses
3.
○ Modify a Column:
1. Change the data type or size of an existing column.
Syntax:
sql
Copy code
ALTER TABLE table_name
2.
Example:
sql
Copy code
ALTER TABLE busses
3.
○ Rename a Column:
1. Rename an existing column and define its datatype.
Syntax:
sql
Copy code
ALTER TABLE table_name
2.
Example:
sql
Copy code
ALTER TABLE employee
3.
4. Example Task:
○ Problem: Add a new column AC_available of type VARCHAR(10) to
the busses table.
Solution:
sql
Copy code
ALTER TABLE busses
○
○ Steps:
1. Write the query in the code editor.
2. Save and compile to check for errors.
3. Evaluate for successful execution.
5. Key Points:
○ Use ADD for new columns.
○ Use DROP COLUMN for removing columns (enclose multiple column
names in parentheses if needed).
○ Use MODIFY to adjust data types or sizes.
○ Use CHANGE to rename columns and redefine their properties.
1. Definition:
○ DML is used to manipulate data within database objects such as
tables. Once the structure (schema) of the database is created, DML
commands handle data insertion, updates, and deletions.
2. Primary DML Commands:
○ INSERT: Adds new rows to a table.
○ UPDATE: Modifies existing data in one or more rows.
○ DELETE: Removes rows based on a condition, or all rows if no
condition is specified.
3. Overview of DML Commands:
○ INSERT Command:
■ Adds data to a table.
Syntax:
sql
Copy code
INSERT INTO table_name (column1, column2, ...)
Example:
sql
Copy code
INSERT INTO students (id, name, age)
■
○ UPDATE Command:
■ Modifies existing data.
Syntax:
sql
Copy code
UPDATE table_name
WHERE condition;
Example:
sql
Copy code
UPDATE students
SET age = 21
WHERE id = 101;
■
■ Note: Omitting the WHERE clause updates all rows in the table.
○ DELETE Command:
■ Removes specific rows or all rows from a table.
Syntax:
sql
Copy code
DELETE FROM table_name
WHERE condition;
Example:
sql
Copy code
DELETE FROM students
■
4. TRUNCATE vs. DELETE:
○ TRUNCATE:
■ Removes all rows from a table but retains its structure.
■ Faster than DELETE as it doesn’t log individual row deletions.
■ Not a DML command; it’s a DDL command.
○ DELETE:
■ Allows conditional row deletion.
■ Logs each row deletion, which is slower for large datasets.
5. Key Takeaways:
○ Use INSERT to populate tables.
○ Use UPDATE for modifying specific rows.
○ Use DELETE cautiously, especially without a WHERE clause.
○ Use TRUNCATE when you want to clear all rows quickly without
retaining transactional logs.
1. Definition:
○ DML is used to manipulate data within database objects like tables.
○ Common operations include INSERT, UPDATE, and DELETE.
1. INSERT:
○ Used to add records to a table.
Syntax:
sql
Copy code
INSERT INTO table_name (column1, column2, ...)
Example:
sql
Copy code
INSERT INTO customer (customer_id, name, dob)
○
○ Notes:
■ Date, CHAR, and VARCHAR values must be enclosed in single
quotes (').
■ To insert data into specific columns, mention their names in
parentheses.
2. UPDATE:
○ Used to modify existing records in a table.
Syntax:
sql
Copy code
UPDATE table_name
WHERE condition;
Example:
sql
Copy code
UPDATE customer
○
○ Notes:
■ Without a WHERE clause, all rows in the table will be updated.
3. DELETE:
○ Used to remove records from a table.
Syntax:
sql
Copy code
DELETE FROM table_name
WHERE condition;
Example:
sql
Copy code
DELETE FROM customer
○
○ Notes:
■ Without a WHERE clause, all rows in the table will be deleted.
■ Foreign Key Constraints:
■ ON DELETE CASCADE: Deletes parent and child rows.
■ ON DELETE SET NULL: Sets foreign key in child rows to
NULL when the parent is deleted.
■ RESTRICT (default): Prevents deletion if the record has
dependencies.
DELETE TRUNCATE
Transaction Control:
1. ACID Properties:
○ Atomicity: Transactions are all-or-nothing.
○ Consistency: Ensures data validity.
○ Isolation: Prevents interference between transactions.
○ Durability: Changes persist even after failures.
2. Key Commands:
○ COMMIT:
■ Saves changes permanently.
Syntax:
sql
Copy code
COMMIT;
■
○ ROLLBACK:
■ Undoes changes made in the current transaction.
Syntax:
sql
Copy code
ROLLBACK;
■
○ SAVEPOINT:
■ Sets a marker in a transaction to rollback to a specific point.
Syntax:
sql
Copy code
SAVEPOINT savepoint_name;
ROLLBACK TO savepoint_name;
■
3. Transaction Behavior:
○ Start: A transaction begins when a DML statement is executed.
○ End: Must end with COMMIT or ROLLBACK.
○ DDL Commands: Auto-commit by default.
Locking Mechanisms:
1. Purpose:
○ Ensures data integrity and prevents conflicts between transactions.
2. Types of Locks:
○ Explicit Locking: Manually applied by users.
○ Implicit Locking: Automatically handled by the database.
3. Lock Modes:
○ Exclusive Lock: Prevents other users from accessing the data.
○ Shared Lock: Allows multiple users to read data but restricts
modifications.
4. Lock Behavior:
○ For INSERT, UPDATE, and DELETE: A shared lock is applied on the
table, and an exclusive lock is applied on the row.
○ For SELECT: No lock is required.
○ For DDL: Locks the object definition.
5. Lock Duration:
○ Locks are retained until a COMMIT or ROLLBACK is issued.
Key Takeaways:
1. INSERT Statement
sql
Copy code
Example:
sql
Copy code
INSERT INTO employee (id, name, department)
●
● Notes:
○ You must specify values for columns defined as NOT NULL.
○ If the table contains nullable columns, you can omit them.
sql
Copy code
● Use this method only if you know the exact structure and order of columns in
the table.
Example:
sql
Copy code
INSERT INTO employee
2. UPDATE Statement
Syntax
sql
Copy code
UPDATE table_name
[WHERE condition];
Example:
sql
Copy code
UPDATE employee
○
● With WHERE Clause:
○ Updates specific rows based on a condition.
Example:
sql
Copy code
UPDATE employee
Conditional Updates
Example:
sql
Copy code
UPDATE employee
SET salary = 70000
3. DELETE Statement
Syntax
sql
Copy code
[WHERE condition];
Example:
sql
Copy code
DELETE FROM employee;
○
○ Warning: This clears the table but retains its structure.
● With WHERE Clause:
○ Deletes specific rows based on a condition.
Example:
sql
Copy code
DELETE FROM employee
Key Highlights
● INSERT:
○ Use column names when inserting values selectively.
○ Be cautious of constraints like NOT NULL.
● UPDATE:
○ Can update all rows or a subset of rows with a condition.
○ Ensure correct use of WHERE to avoid unintended modifications.
● DELETE:
○ Deletes data but not the structure of the table.
○ Use WHERE to target specific rows; otherwise, all rows are removed.
DEMO - INSERT:
Task Description
Insert three records into the department table based on the schema provided.
Table Schema
For inserting data, use the INSERT INTO statement. Since all columns are being
filled, column names can be omitted.
sql
Copy code
Validation
Once executed:
Check the table using a SELECT query to confirm the data was added:
sql
Copy code
SELECT * FROM department;
●
● The output should display:
1 CSE 1
2 ECE 2
3 MECH 3
Best Practices
how to update specific rows in the schedule table by adding 5 days to the
travel_date for specific conditions:
Task Description
Goal: Update the travel_date for rows in the schedule table where:
● source = 'Chennai'
● destination = 'Bangalore'
Table Schema
Use the UPDATE statement to update specific rows. The WHERE clause ensures only
the targeted rows are updated.
sql
Copy code
UPDATE schedule
Validation
sql
Copy code
● The travel_date for the filtered rows should now reflect the original date
plus 5 days.
Best Practices
Test on a Subset of Data: Use a SELECT query first to ensure the correct rows are
identified:
sql
Copy code
SELECT * FROM schedule
1.
2. Backup Data: If working on production databases, back up the data before
performing updates.
3. Format Dates Correctly: Ensure the travel_date column uses a
compatible date format for arithmetic operations.
Key Notes
● Condition Importance: Without the WHERE clause, the update applies to all
rows in the table.
● SQL Syntax: The addition of INTERVAL 5 DAY ensures compatibility with
standard SQL date arithmetic.
DEMO - DELETE:
how you can delete specific rows from a table based on a condition using SQL.
This example focuses on deleting rows from the payments table where the
discount_id matches 'd1'.
Task Description
● discount_id: This column stores the discount coupon IDs used during
payment. The data is case-sensitive.
Use the DELETE statement with a WHERE clause to ensure only specific rows are
deleted.
1. Open the Code Editor: Navigate to the SQL code editor on your platform.
Validation
After execution, validate the changes by querying the table to confirm that no records
with discount_id = 'd1' remain:
sql
Important Notes
Example Workflow
The SELECT statement is one of the most commonly used and essential SQL
commands. Unlike other DML statements like INSERT, UPDATE, and DELETE, which
modify data, the SELECT statement is primarily used to retrieve data from tables.
Although it is considered a part of the DML family, it does not manipulate the data
but rather queries it.
The simplest form of the SELECT statement retrieves all columns and rows from a
table:
sql
Copy code
Example:
sql
Copy code
SELECT * FROM employees;
To fetch only certain columns, list the column names in the SELECT clause:
sql
Copy code
Example:
sql
Copy code
SELECT first_name, last_name FROM employees;
● This retrieves only the first_name and last_name columns from the
employees table.
sql
Copy code
Example:
sql
Copy code
SELECT first_name, last_name FROM employees WHERE
department_id = 10;
Ordering Results
sql
Copy code
SELECT column1, column2 FROM table_name ORDER BY column_name
[ASC|DESC];
Example:
sql
Copy code
SELECT first_name, last_name FROM employees ORDER BY last_name
ASC;
Limiting Results
To fetch a specific number of rows, use LIMIT (or TOP in some SQL dialects):
sql
Copy code
Example:
sql
Copy code
SELECT first_name, last_name FROM employees LIMIT 5;
You can combine multiple conditions in a WHERE clause using logical operators:
sql
Copy code
Example:
sql
Copy code
SELECT first_name, last_name FROM employees WHERE
department_id = 10 AND salary > 5000;
The SELECT statement supports aggregate functions like COUNT, SUM, AVG, MAX,
and MIN:
sql
Copy code
Advanced Queries
FROM employees e
2.
The SELECT statement is used to fetch data from a database table. This operation
is often referred to as Data Retrieval Language (DRL) or Data Query Language
(DQL).
Basic Syntax:
sql
Copy code
sql
Copy code
Case Sensitivity:
● SQL statements are not case-sensitive. For example, SELECT and select
are treated the same.
● Data stored in the database is case-sensitive. For instance, "Tom" and
"tom" are treated as different values.
You can select specific columns from a table by listing their names in the SELECT
clause:
sql
Copy code
sql
Copy code
4. Concatenating Strings
sql
Copy code
● This displays customer names along with their addresses in a single column.
sql
Copy code
Example:
sql
Copy code
● Comparison Operators:
○ <, >, <=, >=, =
Example:
sql
Copy code
SELECT * FROM policy WHERE minimum_amount < 1500;
○
● LIKE: Used for pattern matching.
Example:
sql
Copy code
SELECT * FROM customer WHERE customer_name LIKE 'A%'; -- Names
starting with 'A'
○
● BETWEEN: Selects values within a range.
Example:
sql
Copy code
SELECT * FROM policy WHERE minimum_amount BETWEEN 1000 AND
2000;
○
● IN: Matches any value in a list.
Example:
sql
Copy code
SELECT * FROM customer WHERE customer_city IN ('Chennai',
'Bangalore');
○
● IS NULL: Checks for NULL values.
Example:
sql
Copy code
SELECT * FROM policy WHERE policy_description IS NULL;
7. Combining Conditions
Example:
sql
Copy code
SELECT * FROM policy WHERE minimum_amount < 1500 AND
policy_type = 'Health';
Example (Ascending):
sql
Copy code
SELECT * FROM customer ORDER BY customer_name;
●
Example (Descending):
sql
Copy code
SELECT * FROM customer ORDER BY customer_name DESC;
Summary
Practice Task
Try writing a query to retrieve all policies with a minimum amount greater than 2000,
sorted by their policy name in descending order.
sql
Copy code
1. Filtering Rows
● Single condition:
SELECT * FROM employees WHERE salary > 15000;
● Multiple conditions with logical operators:
SELECT * FROM employees WHERE salary > 10000 AND
commission < 30000;
2. Removing Duplicates
● Use DISTINCT:
SELECT DISTINCT department_id FROM employees;
3. Combining Queries
UNION
●
● UNION ALL: Combines results without removing duplicates.
4. Range Conditions
Use BETWEEN:
sql
Copy code
SELECT * FROM employees WHERE salary BETWEEN 12000 AND 18000;
5. Sorting
Order results:
sql
Copy code
SELECT name, salary FROM employees ORDER BY salary DESC;
6. Prioritizing Conditions
7. Intersect-like Functionality
EXCEPT
1. Basic Syntax:
General Form:
sql
Copy code
SELECT column1, column2, ...
FROM table_name
WHERE condition(s);
○
○ Select All Columns: Use SELECT * to retrieve all columns from a
table.
2. Key Clauses:
○ WHERE: Filters rows based on specified conditions.
○ GROUP BY: Groups rows for aggregation (e.g., COUNT, SUM).
○ HAVING: Filters groups created by GROUP BY based on conditions.
○ ORDER BY: Sorts results. Defaults to ascending (ASC), but DESC can
be specified for descending order.
3. Column Aliases:
FROM table_name;
○
○ Enclose aliases in double quotes for names containing spaces or
reserved keywords.
4. Examples:
FROM employee
FROM department
WHERE block_number = 3
ORDER BY department_name;
Pro Tips:
Use Comments:
Include comments to clarify complex queries for better readability.
sql
Copy code
-- Retrieve department names from block 3 in ascending order
SELECT department_name
FROM department
WHERE block_number = 3
ORDER BY department_name;
●
● Practice With Real Data:
Use sample databases like Sakila or AdventureWorks to explore complex
queries.
● Test Different Clauses:
Experiment with combinations of GROUP BY, HAVING, and ORDER BY to
solidify understanding.
● Online SQL Editors:
Use platforms like SQL Fiddle or db-fiddle.com to practice writing and testing
queries.
Code:
sql
Copy code
SELECT *
FROM employee
WHERE department_id = 5001;
Explanation:
1. SELECT *:
○ The * means "select all columns" from the table employee. This will
return all the fields for the employees who match the condition.
2. FROM employee:
○ Specifies the table to fetch data from, in this case, the employee table.
3. WHERE department_id = 5001:
○ This clause filters the rows, so only employees who belong to
department 5001 are included in the result.
Code:
sql
Copy code
SELECT department_name
FROM department
WHERE block_number = 3
ORDER BY department_name;
Explanation:
1. SELECT department_name:
○ Retrieves only the department_name column from the table.
2. FROM department:
○ Indicates that the data should be fetched from the department table.
3. WHERE block_number = 3:
○ Filters rows to include only departments located in block number 3. If
there are rows with other block numbers, they will be excluded from the
result.
4. ORDER BY department_name:
○ Sorts the results by the department_name column alphabetically in
ascending order.
○ If no ASC or DESC is mentioned, the default is ascending (ASC).
department_name block_numb
er
Software 3
Engineering
IT 3
CAC 3
Marketing 2
department_name
CAC
IT
Software
Engineering
Explanation of Sorting:
If you want the column to display a more descriptive name in the results, you can
use an alias:
Code:
sql
Copy code
FROM department
WHERE block_number = 3
ORDER BY department_name;
Department Name
CAC
IT
Software
Engineering
The AS "Department Name" ensures the output column is labeled "Department
Name" instead of department_name.
Practice Ideas:
FROM department
WHERE block_number = 3
ORDER BY department_name;
1.
FROM department
2. GROUP BY block_number;
Code:
sql
Copy code
SELECT *
FROM employee
1. SELECT *:
○ Selects all columns from the table employee.
2. FROM employee:
○ Specifies the source table, which is employee.
3. WHERE name LIKE 'J%':
○ The LIKE operator checks the name column for values matching the
pattern 'J%'.
○ J%:
■ J indicates the first character must be "J".
■ % (wildcard) matches any sequence of characters after "J"
(including no characters).
○ Examples of matching values: John, Janet, James.
○ Examples of non-matching values: Michael, Steve.
ID Name Departmen
t
1 John HR
2 Janet IT
3 Michae Sales
l
4 James Marketing
1 John HR
2 Janet IT
4 Jame Marketing
s
Example 2: Retrieve Students Whose Names Start With 'A' and Sort Results
The task here involves retrieving names that start with "A" from a student table and
sorting them in ascending order.
Code:
sql
Copy code
SELECT student_name
FROM student
Explanation:
1. SELECT student_name:
○ Retrieves only the student_name column.
2. FROM student:
○ Specifies the source table, which is student.
3. WHERE student_name LIKE 'A%':
○ Filters for names starting with "A" and allows any number of characters
after it.
○ Matches examples: Alice, Adam, Aarav.
4. ORDER BY student_name ASC:
○ Sorts the results by student_name in ascending order.
○ Adding ASC is optional because ascending is the default order.
ID Student_Na Grad
me e
1 Alice A
2 Bob B
3 Adam A
4 Aaron C
Student_Na
me
Aaron
Adam
Alice
Using Wildcards in LIKE
1. Single-Row Functions
2. Multi-Row Functions (Aggregate Functions)
1. Single-Row Functions
Single-row functions operate on one row at a time and return one result per row.
They are commonly used in queries to manipulate or format data.
1. String Functions
Used for operations on strings.
Examples:
-- Result: HELLO
○
○ LOWER(): Converts text to lowercase.
○
2. Numeric Functions
Perform operations on numeric data.
Examples:
-- Result: 123.5
○
○ ABS(): Returns the absolute value of a number.
-- Result: 8
○
3. Date Functions
Used to manipulate and format dates.
Examples:
○
○ DATE_ADD(): Adds a specified interval to a date.
-- Result: 9
○
4. Conversion Functions
Convert data types.
Examples:
-- Result: 123
○
○ CONVERT(): Another method for data type conversion.
sql
Copy code
SELECT employee_id,
UPPER(first_name) AS uppercase_name,
ROUND(salary, 2) AS rounded_salary
FROM employee;
This query:
Multi-row functions, also known as group functions, operate on a set of rows and
return a single summarized result. These are typically used with GROUP BY
clauses.
SUM()
Calculates the total of a numeric column.
sql
Copy code
SELECT SUM(salary) AS total_salary
FROM employee;
1.
AVG()
Returns the average value of a numeric column.
sql
Copy code
SELECT AVG(salary) AS average_salary
FROM employee;
2.
COUNT()
Counts the number of rows or non-NULL values.
sql
Copy code
SELECT COUNT(employee_id) AS employee_count
FROM employee;
3.
MAX()
Finds the maximum value in a column.
sql
Copy code
SELECT MAX(salary) AS highest_salary
FROM employee;
4.
MIN()
Finds the minimum value in a column.
sql
Copy code
SELECT MIN(salary) AS lowest_salary
FROM employee;
5.
sql
Copy code
SELECT department_id,
COUNT(employee_id) AS employee_count,
AVG(salary) AS average_salary
FROM employee
GROUP BY department_id;
This query:
Practice Task
Write a query to display the employee names in uppercase along with their salaries
rounded to 2 decimal places.
sql
Copy code
ROUND(salary, 2) AS rounded_salary
FROM employee;
Write a query to find the total and average salaries for each department.
sql
Copy code
SELECT department_id,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary
FROM employee
GROUP BY department_id;
In this module, we have delved into the functionality of SQL functions and their
applications in database management systems, specifically within the context of an
insurance management system. SQL functions are essential for performing
operations, manipulating data, and retrieving meaningful insights.
1. Single-Row Functions
○ Operate on one row at a time.
○ Return one result per row.
2. Multi-Row (Aggregate) Functions
○ Operate on a group of rows.
○ Return one result for the entire group.
1. Single-Row Functions
A. Character Functions
● Accept character data as input and return either character or numeric values.
Examples:
2.
3.
B. Numeric Functions
Examples:
1.
2.
3.
C. Date Functions
● Work with date and time values to perform operations or format output.
Examples:
1.
2.
3.
D. General Functions
Examples:
1.
2.
E. Nesting Functions
● Functions can be nested, where the result of one function is used as input to
another.
Example:
sql
Copy code
FROM customer
These functions operate on a set of rows and return a summarized result. Common
examples include:
1.
AVG(): Calculates the average.
sql
Copy code
SELECT AVG(premium_amount) AS average_premium FROM
policy_enrollment;
2.
3.
4.
5.
sql
Copy code
SELECT policy_type,
COUNT(*) AS total_customers,
SUM(premium_amount) AS total_premium
FROM policy_enrollment
GROUP BY policy_type
In MySQL, functions are divided into two main types based on their scope of
operation:
1. Scalar Functions
2. Aggregate Functions
1. Scalar Functions
1. Character Functions:
○ Work on character/string data.
○ Examples:
■
2. Numeric Functions:
○ Work on numeric data.
○ Examples:
■
3. Date and Time Functions:
○ Operate on date/time values.
○ Examples:
■
DATE_ADD(date, INTERVAL value unit): Adds an interval to a date.
sql
Copy code
SELECT DATE_ADD('2024-01-01', INTERVAL 7 DAY) AS new_date;
■
4. Conversion Functions:
○ Convert data types.
○ Examples:
2. Aggregate Functions
1.
2.
4.
5.
Output Returns one value per row. Returns one value for a group of
rows.
Practical Example
sql
Copy code
FROM orders;
sql
Copy code
FROM orders
GROUP BY customer_id;
Scalar functions focus on row-by-row operations, while aggregate functions
summarize data for analysis across multiple rows. Both are essential for working with
data in MySQL effectively!
Scalar functions in SQL operate on individual rows and return a single value per row.
These are highly useful for performing operations like string manipulation, date
formatting, numeric adjustments, and more.
1. String Functions:
○ Used for manipulating string data.
○ Examples: SUBSTRING, UPPER, LOWER, CONCAT, TRIM, etc.
2. Date Functions:
○ Used for date/time manipulation.
○ Examples: DATE, DAYNAME, MONTHNAME, NOW, DATE_FORMAT, etc.
3. Numeric Functions:
○ Perform calculations on numeric data.
○ Examples: ROUND, FLOOR, CEIL, TRUNCATE.
4. Conversion Functions:
○ Convert data types or format data.
○ Examples: CAST, CONVERT, FORMAT.
5. Null Handling Functions:
○ Manage null values.
○ Examples: IFNULL, COALESCE.
Table: employee
SQL Query:
sql
Copy code
FROM employee;
Output:
Uppercase_Na
me
ALICE
BOB
CHARLIE
Name Phone_Numb
er
John 9876543210
Sarah 8765432109
Michae 7654321098
l
SQL Query:
sql
Copy code
SELECT
Name,
FROM users
ORDER BY Name;
Explanation:
Output:
Name Passwor
d
John Joh987
Michae Mic765
l
Sarah Sar876
Key Points:
● Scalar functions like SUBSTRING, UPPER, and CONCAT process each row
independently.
● They can be used to dynamically generate or modify data in a table.
● Results can be labeled using an alias (AS keyword).
● Conversion functions like CAST ensure compatibility when manipulating
numeric and string data together.
Scalar functions are versatile tools in SQL, enabling efficient row-level operations
tailored to specific data transformation needs.
Aggregate functions in SQL are used to perform calculations on multiple rows and
return a single result for the group of rows. Unlike scalar functions, which operate on
individual rows, aggregate functions summarize data across multiple rows. Common
aggregate functions include:
Table: employee
SQL Query:
sql
Copy code
FROM employee;
Explanation:
Output:
Total_Salar
y
18000
Scenario: Display the types of buses and the number of buses in each type, sorted
by the count in descending order.
Table: busses
Bus_Typ Bus_Numb
e er
AC 101
Non-AC 102
AC 103
Non-AC 104
AC 105
AC 106
SQL Query:
sql
Copy code
FROM busses
GROUP BY Bus_Type
Explanation:
Output:
Bus_Typ Bus_Cou
e nt
AC 4
Non-AC 2
Key Takeaways:
Aggregate functions are powerful tools for analyzing large datasets and generating
summarized information.
In SQL, when you need to retrieve data from multiple tables, joins and subqueries
are commonly used mechanisms. Let's break down both concepts, including their
types and use cases.
Joins
A join allows you to combine rows from two or more tables based on a related
column between them. Joins are essential when you need to work with normalized
data spread across multiple tables. Without a join, you'd end up with multiple
separate queries, making the database operations inefficient.
Types of Joins:
1. Inner Join:
○ Definition: Returns only the rows where there is a match in both
tables.
○ Use Case: To find matching records between two tables.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
ON table1.column_name = table2.column_name;
○
2. Left Outer Join (Left Join):
○ Definition: Returns all rows from the left table and the matching rows
from the right table. If there is no match, NULL values will be returned
for columns from the right table.
○ Use Case: To return all records from the left table and matching
records from the right.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
ON table1.column_name = table2.column_name;
○
3. Right Outer Join (Right Join):
○ Definition: Similar to the left join, but it returns all rows from the right
table and the matching rows from the left table. Non-matching rows
from the left table will contain NULL values.
○ Use Case: When you need to return all records from the right table and
the matching records from the left.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
ON table1.column_name = table2.column_name;
○
4. Full Outer Join:
○ Definition: Combines the results of both left and right joins. It returns
all rows when there is a match in either the left or right table. If there’s
no match, NULL values will be filled in for the missing side.
○ Use Case: To return all records from both tables, with NULL where
there’s no match.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
ON table1.column_name = table2.column_name;
○
5. Cross Join:
○ Definition: Returns the Cartesian product of the two tables, i.e., every
row from the first table combined with every row from the second table.
○ Use Case: To combine all rows from two tables, but be careful as this
can produce a large number of results.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
○
6. Natural Join:
○ Definition: Automatically joins tables based on columns with the same
name and data type.
○ Use Case: When you have tables with columns of the same name and
want to join them based on these columns automatically.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
Subqueries
A subquery (or inner query) is a query that is nested inside another query. It is
typically used when the result of the inner query is required by the outer query for
filtering or computing results.
Types of Subqueries:
1. Scalar Subquery:
○ Definition: Returns a single value (one row, one column).
○ Use Case: For example, to retrieve a specific value for filtering.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
○
2. Correlated Subquery:
○ Definition: A subquery that references columns from the outer query.
○ Use Case: When you want to use data from the outer query to filter the
results of the inner query.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1 t1
FROM table2 t2
○
3. Exists Subquery:
○ Definition: Checks for the existence of rows returned by the subquery.
○ Use Case: To check whether at least one row exists that meets the
condition.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
○
4. IN Subquery:
○ Definition: Tests whether a value matches any value returned by the
subquery.
○ Use Case: When you want to check if a value exists in a set of values
returned by a subquery.
SQL Syntax:
sql
Copy code
SELECT *
FROM table1
employees table:
departments table:
dept_i dept_nam
d e
1 HR
2 Finance
sql
Copy code
FROM employees
Result:
emp_nam dept_nam
e e
Alice HR
Bob Finance
Charlie HR
Query 2: Subquery Example (Find employees with salary higher than average salary
in their department):
sql
Copy code
SELECT emp_name
FROM employees e
Result:
emp_nam
e
Charlie
Conclusion:
● Joins are used to combine data from multiple tables based on related
columns.
● Subqueries are used when you need to nest a query inside another,
especially for filtering or computing based on the results of an inner query.
● Choosing between a join and a subquery depends on the specific
requirements and performance considerations of your query.
1. Joins in SQL
A join allows you to retrieve data from multiple tables based on a related column
between them. There are several types of joins, each serving different purposes.
● Definition: A Cartesian join (or cross join) combines every row from one table
with every row from another, leading to a Cartesian product.
● Use Case: This happens when no join condition is specified.
● Example: If you want to combine customer data with policy enrollment without
specifying a condition, you'll get every customer’s details combined with every
policy enrollment, leading to a huge number of results.
● Definition: This join uses the equal to operator to match records between two
tables. It returns only the rows where there is a match in both tables.
● Example: You can join the customer table with the policy enrollment table
based on a customer ID that exists in both.
Non-Equi Join
● Definition: This join uses any operator other than the equality operator, like >,
<, >=, <=, <>, in the join condition.
● Example: Joining based on some condition like “penalty > 1000” instead of a
direct equality.
Outer Joins
Outer joins return rows even if there is no match in one of the tables.
● Left Outer Join: Returns all rows from the left table and matching rows from
the right table. If there's no match, NULL is returned for columns of the right
table.
● Right Outer Join: Returns all rows from the right table and matching rows
from the left table. If there's no match, NULL is returned for columns of the left
table.
● Full Outer Join: In systems that support it (like Oracle), it returns all rows
from both tables. If no match exists, NULL is returned for missing data from
either side. In MySQL, you can emulate a full outer join using a combination of
LEFT JOIN, RIGHT JOIN, and the UNION operator.
Self Join
● Definition: A self join is a join where a table is joined with itself. This is useful
for relationships within the same table, such as hierarchical data (e.g.,
employees and managers).
● Example: Using aliases to distinguish between different instances of the
same table in the join.
Natural Join
● Definition: A natural join automatically joins tables based on columns with the
same name and data type.
● Example: If two tables have a column named customer_id, the natural join
will automatically match rows based on that column.
● Using the USING clause: When multiple columns with the same name exist
but not the same data type, you can specify which column to join on using the
USING clause.
2. Subqueries in SQL
A subquery is a query nested inside another query, and the result of the subquery is
used by the outer query.
Types of Subqueries:
1. Single-Row Subquery:
○ Definition: Returns only one row (and typically one value).
○ Example: You can use a subquery to find customers who paid a higher
penalty than the average penalty of all customers.
2. Multi-Row Subquery:
○ Definition: Returns more than one row.
○ Example: A subquery that returns multiple penalty amounts to
compare with each customer.
○ Operators used: IN, ANY, ALL.
■ IN: Checks if a value is in a set returned by the subquery.
■ ANY: Compares with any value returned by the subquery.
■ ALL: Compares with every value returned by the subquery.
3. Correlated Subquery:
○ Definition: A correlated subquery references columns from the outer
query. It is evaluated once for each row processed by the outer query.
○ Example: For each customer, you can compare their penalty with the
highest penalty paid by a different customer.
4. Subqueries in Different Clauses:
○ SELECT Clause: A subquery can return a value that will be selected in
the outer query.
○ FROM Clause: A subquery can act as a derived table, providing a
temporary result set for the outer query.
○ INSERT/UPDATE/DELETE Statements: Subqueries can be used to
specify values or conditions for these statements.
Example Queries:
FROM customers;
1.
2.
UNION
3.
● Joins: Used to combine data from multiple tables. The main types are Inner
Join, Outer Joins (Left, Right, Full), and Self Join.
● Subqueries: Queries nested inside another query. They can be single-row,
multi-row, or correlated subqueries.
● Equi Join: The most common type of join where tables are joined based on
equality.
● Non-Equi Join: Uses operators other than equality.
● Outer Joins: Return unmatched rows from one or both tables.
● Natural Join: Automatically joins tables based on columns with the same
name.
By mastering joins and subqueries, you can efficiently retrieve and manipulate data
across multiple tables in SQL.
DEMO:
In this demo, the explanation revolves around the SQL join operation and how it can
be used to retrieve data from multiple tables. The two tables in the example are:
● Employee Table: Contains information about employees, including the
employee_id (primary key) and department_id (foreign key referring to
the department).
● Department Table: Contains information about departments, including
department_id (primary key) and location.
Types of Joins:
The goal is to display all employee names along with their department locations. The
query uses a Left Outer Join to ensure that all employees are included, even those
without a department.
sql
Copy code
FROM employee e
LEFT JOIN department d
ON e.department_id = d.department_id;
This query ensures that you get all employee names, and for employees who do not
have a department, the location column will be NULL.
SQL Query for Student Data with Department and Sorted by School
For a similar scenario where you need to display student names and their respective
department names, sorted by school, here’s an example query based on the
scenario:
sql
Copy code
FROM student s
ON s.department_id = d.department_id
ORDER BY s.school;
This query will return all students and their department names (if available), sorted
by their school.
Problem:
You need to find the employee who is getting the maximum salary in the employee
table. Instead of manually entering the maximum salary value (like 20,000), you want
to calculate the maximum salary dynamically and use it in the query.
sql
Copy code
SELECT employee_name
FROM employee
This approach hardcodes the value 20,000, which works if the salary is fixed, but
isn't flexible.
To avoid hardcoding the salary value, you can use a subquery that retrieves the
maximum salary from the employee table and pass it to the main query. The
subquery will dynamically return the maximum salary, and the outer query will then
use that value.
sql
Copy code
SELECT employee_name
FROM employee
Explanation:
Example:
employee_na salar
me y
Alice 2000
0
Bob 2500
0
Charlie 3000
0
Dave 3000
0
● Charlie and Dave because they both have the maximum salary of 30,000.
Benefits:
This approach avoids hardcoding and makes the query more robust for varying
data scenarios.
DEMO:
In this demo on SQL subqueries, you're explaining how subqueries can be used to
handle dynamic conditions in queries, allowing you to write more flexible and
reusable SQL code. Let’s summarize the key concepts and queries explained:
Problem:
You need to find the employee who earns the maximum salary in the employee
table. Instead of hardcoding the maximum salary (e.g., 20,000), you use a subquery
to dynamically calculate the maximum salary.
Approach:
Step 2: Use the result of the subquery to find the employee with that salary:
sql
Copy code
SELECT employee_name
FROM employee
This approach ensures that the query adapts to future changes in salary values, so it
will always return the employee with the current maximum salary.
Problem:
You need to display the names of staff members who are not handling any
subjects. This requires checking the staff table and the subject table. If a staff ID
does not appear in the subject table, that staff member is not handling any subjects.
Approach:
Step 1: Retrieve all staff IDs from the subject table, representing staff who are
handling subjects:
sql
Copy code
SELECT staff_id
FROM subject;
Step 2: Use a subquery to filter out staff members who are handling subjects and
select staff who are not in the subject table:
sql
Copy code
SELECT staff_name
FROM staff
ORDER BY staff_name;
Key Points:
● The subquery inside the NOT IN clause fetches the staff IDs of employees
handling subjects.
● The outer query checks for staff members whose IDs do not appear in the
subject table, indicating they are not handling any subjects.
● Handling NULL values: If the subquery contains NULL values (e.g., due to
missing staff IDs), the outer query will return an empty result. To avoid this, we
use the condition WHERE staff_id IS NOT NULL inside the subquery.
This ensures that you correctly identify and display the staff members who are not
handling any subjects, and the results are sorted by staff name in ascending order.
Conclusion:
Data Control Language (DCL) and Database Objects, several concepts related to
managing permissions, views, indexing, and optimizing database queries are
covered. Let's break down the key points discussed:
FROM policy;
● Views allow you to abstract complex queries and show only the data needed,
helping to simplify data access and improve security by controlling which data
a user can see.
Read-Only Views: In MySQL, there isn't a built-in option to make views read-only.
However, you can indirectly ensure read-only behavior by creating a user with
SELECT privileges only and using the SQL SECURITY DEFINER clause in the
CREATE VIEW statement.
Example:
sql
Copy code
CREATE VIEW policy_view
3. Inline Views
Example:
sql
Copy code
SELECT *
FROM (SELECT policy_id, policy_name FROM policy WHERE
policy_type = 'Health') AS subquery;
● Inline views are temporary and are only available during the execution of the
query.
4. Top N Analysis
FROM employee
LIMIT 10;
5. Auto Increment
Example:
sql
Copy code
CREATE TABLE customer (
customer_name VARCHAR(100)
);
6. Indexes
● Indexes are used to speed up query performance, especially on large tables.
They can be created on columns that are frequently searched or used in joins.
○ You can create an index at the time of table creation or after the table
has been created.
Example:
sql
Copy code
CREATE INDEX idx_policy_name ON policy(policy_name);
●
● Viewing and Dropping Indexes:
○ To view indexes: SHOW INDEX FROM table_name;
To drop an index:
sql
Copy code
DROP INDEX idx_policy_name ON policy;
7. Key Takeaways:
● DCL commands allow you to control user access to data using GRANT and
REVOKE.
● Views are used to simplify complex queries and control data access. Views
can be simple or complex and provide a virtual layer over actual data.
● Inline views are used for temporary query simplification and don't persist
beyond the query execution.
● Top N Analysis helps to retrieve the highest or lowest values from a dataset,
like the top 10 salaries.
● Auto Increment helps automatically generate unique values for columns,
typically used for primary keys.
● Indexes improve query performance, especially on large tables or columns
with a wide range of values.
What is a View?
● A view is a virtual table that does not store any data. Instead, it stores a
query definition that retrieves data from other tables when executed.
● Views are used to simplify complex queries and to ensure security by
exposing only relevant data to users.
● For example, if a table has many columns but you only want to show a few,
you can create a view to restrict which columns or rows are displayed.
View Syntax
To create a view, the syntax is similar to creating a table, but instead of defining a
structure, you specify a SELECT query.
sql
Copy code
FROM table_name
WHERE condition;
The CREATE OR REPLACE part ensures that if the view already exists, it will be
replaced with the new definition.
Consider an employee table with columns like employee_id, name, salary, etc.
You want to create a view showing only the employees from a specific department
(e.g., department ID 50,001).
sql
Copy code
SELECT *
FROM employee
sql
Copy code
In the case of a bus management system, you might need a view that joins data
from multiple tables, like users, tickets, and schedule.
1. Tables:
○ users: Contains user_id, username, etc.
○ tickets: Contains user_id, schedule_id, etc.
○ schedule: Contains schedule_id, source, destination, etc.
2. Goal: Create a view that shows user_id, username, source, and
destination from these tables.
sql
Copy code
FROM users u
ORDER BY u.user_id;
This query joins the users, tickets, and schedule tables on their respective
keys, and then creates a view showing the travel details for each user, ordered by
user_id.
● Views simplify complex queries: By using views, you can abstract away the
complexity of complex JOINs and WHERE conditions.
● Security: Views allow you to control what data users can access. For
example, you can create a view that shows only relevant columns or rows,
hiding sensitive information.
● Performance: While views simplify data retrieval, they don't store data
themselves, so every time you query a view, it executes the underlying query.
● Ambiguity in Joins: When using joins from multiple tables that have common
column names (e.g., user_id in both users and tickets), specify the
table alias to avoid ambiguity (e.g., u.user_id vs. t.user_id).
Conclusion:
Views are a powerful tool for simplifying data access, improving security, and making
your SQL queries more readable and maintainable. By using views, you can create a
cleaner, more controlled way of interacting with your data.
5. Which of the following are valid uses for SQL views? (Choose all that
apply)
○ A) To show only specific columns or rows from a table
○ B) To store data permanently
○ C) To simplify complex queries
○ D) To hide sensitive data from users
6. Answer: A) To show only specific columns or rows from a table, C) To simplify
complex queries, D) To hide sensitive data from users
7. Which of the following statements about views are true? (Choose all that
apply)
○ A) A view stores a subset of data from a table
○ B) A view can be used to prevent data modifications through the view
○ C) A view can be indexed like a table
○ D) A view is always updated when the underlying tables change
8. Answer: A) A view stores a subset of data from a table, B) A view can be
used to prevent data modifications through the view, D) A view is always
updated when the underlying tables change
3. True or False
11. A view is a ________ table that contains a SQL query definition, which is
executed when queried.
Answer: virtual
12. To create a view, the correct SQL syntax is ________ followed by the
view name and the SELECT query.
6. Scenario-based Question
13. You have a table employees with 1000 rows and 50 columns. You want
to create a view that shows only the employee_id, name, and salary
columns for employees in department 50,001. What is the correct SQL
to create this view?
A)
sql
Copy code
CREATE VIEW sales_employees AS
B)
sql
Copy code
CREATE VIEW sales_employees AS
C)
sql
Copy code
CREATE VIEW sales_employees AS
D)
sql
Copy code
CREATE VIEW sales_employees AS
●
Answer: A) sql CREATE VIEW sales_employees AS SELECT
employee_id, name, salary FROM employees WHERE department_id =
50001;