0% found this document useful (0 votes)
13 views16 pages

MYSql

Uploaded by

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

MYSql

Uploaded by

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

farjaadrizvi@gmail.

com
pw : Rizvi@110725

Module one.
This module introduces the fundamentals of MySQL database engineering at Meta.
You'll learn how to:

Filter data using logical operators (AND, OR, NOT, IN, BETWEEN, LIKE).
Join tables using different join types (INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL
OUTER JOIN, UNION).
Group data using the GROUP BY and HAVING clauses.
By the end of this module, you'll have a solid understanding of basic MySQL query
operations.

Module 2

This module focuses on advanced MySQL operations. You'll learn how to:

Update and insert data using the MySQL REPLACE statement.


Work with constraints to enforce data integrity.
Modify table structure using ALTER TABLE and COPY TABLE commands.
Use subqueries and complex comparison operators.
Create and use views to query data from virtual tables.
By the end of this module, you'll have a deeper understanding of MySQL database
management and be able to perform more complex tasks.

Module 3 Summary:

This module focuses on MySQL functions and stored procedures. You'll learn how to:

Use various types of functions including numeric, string, date, comparison, and
control flow functions.
Create and deploy stored procedures to encapsulate complex logic and improve code
reusability.
By the end of this module, you'll have a strong understanding of MySQL functions
and be able to write efficient and modularized code.

Module 4 Summary:

In the last module, you'll have an opportunity to recap what you learned and
identify your strengths and target topics that you would like to revisit in this
course.

By the end of this module you will be able to:

Demonstrate the skills and knowledge you have gained on this course.

===================================================================================
==================================================

Summary of SQL Concepts


Data Types:

Numeric: Used for numbers (e.g., integers, decimals).


String: Used for text data (e.g., names, addresses).
Default Values: Automatically assigned values to columns if no value is provided.
CRUD Operations:

Create: Used to create databases, tables, and data records.


Read: Used to retrieve data from databases.
Update: Used to modify existing data in databases.
Delete: Used to remove data from databases.
SQL Operators:

Arithmetic: Used for mathematical calculations (e.g., +, -, *, /).


Comparison: Used to compare values (e.g., =, <, >, <=, >=).
Clauses:

ORDER BY: Used to sort data.


WHERE: Used to filter data.
SELECT DISTINCT: Used to retrieve unique values.
Database Design:

Schema: Defines the structure of a database.


Relational Database Design: Establishes relationships between tables using keys.
Keys: Primary, secondary, candidate, and foreign keys.
Database Normalization:

Normal Forms: First, second, and third normal forms.


Purpose: To reduce data redundancy and improve data integrity.
By understanding these concepts, you have a solid foundation for working with MySQL
databases and managing their structures effectively.

===================================================================================
==============================================

Retrieving information: Searching for and finding data from a database, file, or
other source.

The video provides a comprehensive overview of using logical operators in SQL to


filter data. Here's a summary of the key points:

Logical Operators:

AND: Requires all conditions to be true for a record to be included.


OR: Requires at least one condition to be true for a record to be included.
NOT: Reverses the result of a condition, selecting records where the condition is
not true.
Syntax:

AND: WHERE condition1 AND condition2


OR: WHERE condition1 OR condition2
NOT: WHERE NOT condition
Example:

To find customers from Gila county who made purchases over $2,000:

SQL
SELECT * FROM customer_purchases
WHERE purchases > 2000 AND location = 'Gila county';
Use code with caution.
To find customers from Gila county or Santa Cruz county:

SQL
SELECT * FROM customer_purchases
WHERE location = 'Gila county' OR location = 'Santa Cruz county';
Use code with caution.

To find customers who are not from Gila county or Santa Cruz county:

SQL
SELECT * FROM customer_purchases
WHERE NOT (location = 'Gila county' OR location = 'Santa Cruz county');
Use code with caution.

Remember:

Parentheses can be used to group conditions.


The NOT operator can be applied to a single condition or a group of conditions.
Practice using these operators in various scenarios to solidify your understanding.

===================================================================================
====================================

The video provides a comprehensive overview of using the IN, BETWEEN, and LIKE
logical operators in SQL to filter data. Here's a summary of the key points:

IN Operator:

Used to specify multiple values in the WHERE clause.


Syntax: WHERE column_name IN (value1, value2, ...)
Equivalent to multiple OR conditions.
Can also use NOT IN to filter the opposite results.
BETWEEN Operator:

Used to select values within a given range.


Syntax: WHERE column_name BETWEEN value1 AND value2
Includes the beginning and ending values of the range.
LIKE Operator:

Used to filter data based on pattern matching.


Syntax: WHERE column_name LIKE pattern
Uses wildcard characters:
%: Represents zero, one, or multiple characters.
_: Represents a single character.
Example:

To find customers from Gila county or Santa Cruz county who made purchases over
$2,000:

SQL
SELECT * FROM customer_purchases
WHERE location IN ('Gila county', 'Santa Cruz county')
AND purchases > 2000;
Use code with caution.

To find customers whose purchases are between $1,000 and $2,000:

SQL
SELECT * FROM customer_purchases
WHERE purchases BETWEEN 1000 AND 2000;
Use code with caution.

To find customers whose locations start with "g" and are at least three characters
long:

SQL
SELECT * FROM customer_purchases
WHERE location LIKE 'g__%';
Use code with caution.

By understanding these operators, you can perform more complex data filtering tasks
in your SQL queries.

===================================================================================
==================
AND Operatior
SELECT * FROM employees WHERE AnnualSalary >= 50000 AND Department = 'Marketing';
NOT Operator
SELECT * FROM employees WHERE NOT AnnualSalary > 50000;
IN Operator
SELECT * FROM employees WHERE AnnualSalary < 50000 AND Department IN('Marketing',
'Finance', 'Legal');
BETWEEN OPERATOR
SELECT * FROM employees WHERE AnnualSalary BETWEEN 10000 AND 50000;
LIKE Operator
SELECT * FROM employees WHERE EmployeeName LIKE 'S___%';
===================================================================================
===============
The WHERE clause is a powerful tool in SQL that allows you to filter data based on
specific conditions. It can be used in SELECT, UPDATE, and DELETE statements to
limit the rows affected by the query.

Here are some examples of how to use the WHERE clause with different operators and
conditions:

SELECT statement:

SQL
SELECT * FROM employees WHERE Department = 'Marketing';
Use code with caution.

This query selects all columns from the employees table where the Department is
equal to 'Marketing'.

UPDATE statement:

SQL
UPDATE employees SET Salary = 55000 WHERE EmployeeID = 3;
Use code with caution.

This query updates the Salary of the employee with EmployeeID 3 to 55000.

DELETE statement:

SQL
DELETE FROM employees WHERE AnnualSalary < 30000;
Use code with caution.

This query deletes all rows from the employees table where the AnnualSalary is less
than 30,000.

Using logical operators:

SQL
SELECT * FROM employees WHERE Department = 'Marketing' AND AnnualSalary >= 50000;
Use code with caution.

This query selects employees from the 'Marketing' department who earn a salary of
$50,000 or more.

SQL
SELECT * FROM employees WHERE Department = 'Marketing' OR Department = 'Sales';
Use code with caution.

This query selects employees from either the 'Marketing' or 'Sales' departments.

Using IN operator:

SQL
SELECT * FROM employees WHERE Department IN ('Marketing', 'Sales');
Use code with caution.

This query is equivalent to the previous query using OR. It selects employees from
the specified departments.

Using BETWEEN operator:

SQL
SELECT * FROM employees WHERE AnnualSalary BETWEEN 40000 AND 60000;
Use code with caution.

This query selects employees with an annual salary between $40,000 and $60,000
(inclusive).

Using LIKE operator:

SQL
SELECT * FROM employees WHERE EmployeeName LIKE 'John%';
Use code with caution.

This query selects employees whose names start with 'John'.

SQL
SELECT * FROM employees WHERE EmployeeName LIKE '%Smith';
Use code with caution.

This query selects employees whose names end with 'Smith'.

SQL
SELECT * FROM employees WHERE EmployeeName LIKE '_o_';
Use code with caution.

This query selects employees whose names have a 'o' in the second position.

By combining these operators and conditions, you can create complex WHERE clauses
to filter data in your SQL queries.

===================================================================================
=====================

The video provides a comprehensive overview of using aliases in MySQL to simplify


database queries and make them more readable. Here are the key points:

What is an Alias?

An alias is a temporary name given to a table or column in a SQL query.


It makes the output of the query easier to understand and use.
When to Use Aliases:

Long or complex table or column names: Simplify them with aliases.


Concatenation: Combine multiple columns into one using aliases.
Multiple tables: Use aliases to distinguish between columns from different tables.
Syntax:

Renaming a table or column: SELECT column_name AS alias_name FROM table_name;


Concatenation: SELECT CONCAT(column1, ' ', column2) AS alias_name FROM table_name;
Multiple tables: SELECT x.column1, y.column2 FROM table1 AS x, table2 AS y WHERE
x.condition = y.condition;
Example:

To rename the date_food_order_placed_with_supplier and


date_food_order_received_from_supplier columns in the food_orders_delivery_status
table to date_placed and date_received, respectively:

SQL
SELECT order_id, date_food_order_placed_with_supplier AS date_placed,
date_food_order_received_from_supplier AS date_received
FROM food_orders_delivery_status;
Use code with caution.

To create a new column called full_name by concatenating the first_name and


last_name columns in the clients table:

SQL
SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM clients;

mysql> select s.StarterName, s.Cost, c.CourseName, c.Cost from Courses AS c,


Starters AS s where c.Cost < 12 AND s.Cost < 5;
===================================================================================
==============================================

Joins are used to combine rows from two or more tables based on a related column
between them. Here's a breakdown of the different types of joins in MySQL, along
with examples:

INNER JOIN
Purpose: Returns rows that have matching values in both tables.
Syntax:
SQL
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
Use code with caution.
Example:

SQL
SELECT
orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;
Use code with caution.

This query joins the orders and customers tables to retrieve orders with customer
names.

LEFT JOIN
Purpose: Returns all rows from the left table, even if there are no matches in the
right table.
Syntax:
SQL
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
Use code with caution.

Example:

SQL
SELECT orders.order_id, customers.customer_name
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.customer_id;

Use code with caution.

This query will return all orders, even if there's no corresponding customer in the
customers table.

RIGHT JOIN
Purpose: Returns all rows from the right table, even if there are no matches in the
left table.
Syntax:
SQL
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Use code with caution.

Example:

SQL
SELECT orders.order_id,
customers.customer_name
FROM orders
RIGHT JOIN customers ON orders.customer_id = customers.customer_id;
Use code with caution.

This query will return all customers, even if there are no corresponding orders in
the orders table.

SELF JOIN
Purpose: Joins a table to itself based on a related column within the same table.
Syntax:
SQL
SELECT e1.employee_id, e1.manager_id, e2.employee_name AS manager_name: This part
specifies the columns you want to retrieve from the tables. You're selecting the
employee_id and manager_id of the current employee (e1) and the employee_name of
their manager (e2).
FROM employees AS e1: This part specifies the first instance of the employees
table. You're using the alias e1 to refer to this instance.
JOIN employees AS e2: This part joins the employees table to itself. You're using
the alias e2 to refer to the second instance of the employees table.
ON e1.manager_id = e2.employee_id: This is the join condition. It specifies that
the manager_id of the current employee (e1) should be equal to the employee_id of
another employee (e2). This allows you to find the manager-employee relationships
within the table.
In essence, this query is retrieving the employee ID, manager ID, and manager name
for each employee in the table. By joining the table to itself, you can find the
corresponding manager information for each employee.

Example:

SQL
SELECT e1.employee_id, e1.manager_id, e2.employee_name AS manager_name
FROM employees AS e1
JOIN employees AS e2 ON e1.manager_id = e2.employee_id;
Use code with caution.

This query joins the employees table to itself to find each employee's manager.

Key points to remember:

The ON clause specifies the condition for joining the tables.


The JOIN type determines which rows are included in the result set.
You can use aliases for tables to make the query more readable.
===================================================================================
====================================
JOIN Concept:

A JOIN clause is used to combine rows from two or more tables based on a common
column.
It allows you to retrieve information from multiple related tables in a single
query.
Types of JOINs:

INNER JOIN: Returns rows that have matching values in both tables.
LEFT JOIN: Returns all rows from the left table, even if there are no matches in
the right table.
RIGHT JOIN: Returns all rows from the right table, even if there are no matches in
the left table.
SELF JOIN: Joins a table to itself based on a related column within the same table.
Syntax:

INNER JOIN:
SQL
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
Use code with caution.

LEFT JOIN:
SQL
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
Use code with caution.

RIGHT JOIN:
SQL
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

Use code with caution.

SELF JOIN:
SQL
SELECT column_name(s)
FROM table_name AS t1
JOIN table_name AS t2 ON t1.column_name = t2.column_name;
Use code with caution.

Example:

To join the customers and orders tables based on the customer_id column and
retrieve customer names and their orders:

SQL
SELECT customers.customer_name, orders.order_id
FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;

Use code with caution.

By understanding these JOIN types and their syntax, you can effectively combine
data from multiple tables in your MySQL queries to retrieve the information you
need.

Sources and related content


===================================================================================
===============================
INNER JOIN:

Used to retrieve rows that have matching values in both tables.


The ON clause specifies the condition for joining the tables.
Syntax:

SQL
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
Use code with caution.
Example:

To join the clients and orders tables based on the client_id column and retrieve
customer names and their orders:

SQL
SELECT clients.full_name, orders.order_id
FROM clients
INNER JOIN orders ON clients.client_id = orders.client_id;
Use code with caution.

Using Aliases:

Aliases can be used to create temporary column names that are more readable.
The AS keyword is used to create aliases.
Example:

SQL
SELECT clients.client_id AS client_id, clients.full_name AS full_name,
orders.order_id AS order_id, orders.product_id AS product_id,
orders.quantity AS quantity, orders.cost AS cost
FROM clients
INNER JOIN orders ON clients.client_id = orders.client_id;
Use code with caution.

By understanding the INNER JOIN clause and using aliases, you can effectively
combine data from multiple tables in your MySQL queries to retrieve the information
you need.

===================================================================================
=====================
The video provides a comprehensive overview of using the LEFT JOIN and RIGHT JOIN
clauses in MySQL to combine data from multiple tables. Here are the key points:

LEFT JOIN:

Returns all rows from the left table, even if there are no matches in the right
table.
Useful for finding records in the left table that have no corresponding records in
the right table.
RIGHT JOIN:

Returns all rows from the right table, even if there are no matches in the left
table.
Useful for finding records in the right table that have no corresponding records in
the left table.
Syntax:

LEFT JOIN:
SQL
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
Use code with caution.

RIGHT JOIN:
SQL
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

Use code with caution.

Example:

To join the clients and orders tables based on the client_id column using a LEFT
JOIN to find all clients and their orders (even if some clients have no orders):

SQL
SELECT clients.client_id, clients.full_name, orders.order_id
FROM clients
LEFT JOIN orders ON clients.client_id = orders.client_id;
Use code with caution.

To use a RIGHT JOIN to find all orders and their corresponding clients (even if
some orders have no associated clients):

SQL
SELECT orders.order_id, orders.product_id, clients.client_name
FROM orders
RIGHT JOIN clients ON orders.client_id = clients.client_id;
Use code with caution.

Using Aliases:

Aliases can be used to create temporary column names and table names.
The AS keyword is used to create aliases.
By understanding the LEFT JOIN and RIGHT JOIN clauses and using aliases, you can
effectively combine data from multiple tables in your MySQL queries to retrieve the
information you need, even when there are unmatched records.

Sources and related content

mysql> SELECT c.ClientID AS "Client ID", c.FullName AS "Full name", o.OrderID AS


"Order ID", o.Quantity, o.Cost
FROM Clients AS C RIGHT JOIN orders ASO ON c.ClientID = o.ClientID

===================================================================================
=========================

It seems like you've provided a detailed explanation of how to use a self-join


clause in MySQL to determine which roles employees are assigned to in the Lucky
Shrub database.

To summarize, the task is to list the full names of all line managers and the
employees they manage. This can be achieved by creating an inner join between the
employees table and itself, using aliases to distinguish between the two instances
of the table.

Here is the MySQL query to accomplish this:

sql

Verify

Open In Editor
Edit
Copy code
SELECT
e1.FullName AS LineManager,
e2.FullName AS Employee
FROM
employees e1
INNER JOIN
employees e2
ON
e1.EmployeeID = e2.LineManagerID;
This query creates two instances of the employees table, e1 and e2, and joins them
on the condition that the EmployeeID in e1 matches the LineManagerID in e2. The
resulting output will show the full names of line managers and the employees they
manage.

===================================================================================
===================================================

UNION Operator:

Combines the results of multiple SELECT statements into a single result set.
Requires that the SELECT statements have the same number of columns, and the
corresponding columns must have the same data types and order.
By default, removes duplicate values from the combined result set.
The ALL keyword can be used to retain all values, including duplicates.
Syntax:

SQL
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Use code with caution.

Example:

To combine the results of two SELECT statements that retrieve employee information
from different tables:

SQL
SELECT FullName, Location FROM full_time_employees
UNION
SELECT FullName, Location FROM part_time_employees;
Use code with caution.

Important Notes:

The UNION ALL keyword can be used to retain all values, including duplicates.
The UNION DISTINCT keyword (default behavior) removes duplicate values from the
combined result set.
===================================================================================
=======================

SELECT
FullName,
Location
FROM
full_time_employees
UNION
SELECT
FullName,
Location
FROM
part_time_employees;

SELECT
FullName,
Location
FROM
full_time_employees
UNION ALL
SELECT
FullName,
Location
FROM
part_time_employees;

===================================================================================
========================

To summarize, the task is to group the records in the Order table by department and
calculate various statistics such as the number of orders, total order value,
minimum order quantity, and average order total for each department.

Here are the MySQL queries to accomplish this:

Grouping records by department

sql

Verify

Open In Editor
Edit
Copy code
SELECT
Department
FROM
orders
GROUP BY
Department;
This query groups the records in the Order table by department and returns a list
of unique departments.

Counting the number of orders for each department

sql

Verify

Open In Editor
Edit
Copy code
SELECT
Department,
COUNT(OrderID) AS NumberOfOrders
FROM
orders
GROUP BY
Department;
This query uses the COUNT aggregate function to count the number of orders for each
department.

Calculating the total order value for each department

sql

Verify

Open In Editor
Edit
Copy code
SELECT
Department,
SUM(OrderTotal) AS TotalOrderValue
FROM
orders
GROUP BY
Department;
This query uses the SUM aggregate function to calculate the total order value for
each department.

Finding the minimum order quantity for each department

sql

Verify

Open In Editor
Edit
Copy code
SELECT
Department,
MIN(OrderQuantity) AS MinOrderQuantity
FROM
orders
GROUP BY
Department;
This query uses the MIN aggregate function to find the minimum order quantity for
each department.

Calculating the average order total for each department

sql

Verify

Open In Editor
Edit
Copy code
SELECT
Department,
AVG(OrderTotal) AS AverageOrderTotal
FROM
orders
GROUP BY
Department;
This query uses the AVG aggregate function to calculate the average order total for
each department.

GROUP BY Clause:

Used to group rows in a table based on specified columns.


Creates subgroups or summary rows for each unique combination of values in the
grouped columns.
Must be placed after the WHERE clause if present.
Columns listed in the GROUP BY clause must also be included in the SELECT clause.
Aggregate Functions:

Used to perform calculations on groups of data.


Common aggregate functions include:
SUM(): Calculates the sum of values.
AVG(): Calculates the average of values.
MAX(): Returns the maximum value.
MIN(): Returns the minimum value.
COUNT(): Counts the number of rows.
Syntax:

SQL
SELECT column_name(s), aggregate_function(column_name)
FROM table_name
GROUP BY column_name(s);

HAVIG Clause
HAVING Clause:

Used to filter groups of data created by the GROUP BY clause.


Applies conditions to the aggregated results.
Must be placed after the GROUP BY clause.
Syntax:

SQL
SELECT column_name(s), aggregate_function(column_name)
FROM table_name
GROUP BY column_name(s)
HAVING SUM(column_name) operator value;
Use code with caution.

Example:

To find departments with a total order quantity greater than 100:

SQL
SELECT Department, SUM(Quantity) AS TotalQuantity
FROM orders
GROUP BY Department
HAVING SUM(Quantity) > 100;
Use code with caution.

Key Points:

The HAVING clause is similar to the WHERE clause, but it applies to groups of data
rather than individual rows.
You can use aggregate functions within the HAVING clause to filter based on
calculated values.
The HAVING clause is often used in conjunction with the GROUP BY clause to analyze
grouped data.

You might also like