Wa0003.
Wa0003.
Wa0003.
Course report:
Introduction to SQL..
Yashwanth m s
1jt22cs190
Cse ‘C’ seC 4 SEMTH
CONTENTS
• Introduction to SQL
• Sql and its installation
• MySql built in functions
• Group by and having
• Joins in SQL
• SubQuery in SQL
• Triggers in SQL
• SQL with python
• Postgre SQL
• How to become an SQL developer?
Introduction TO SQL
What is SQL?
• SQL stands for Structured Query Language.
• It is a standard language for relational database management
systems (RDBMS).
Key Features:
• Data Querying: Retrieve data from a database using SELECT
statements.
• Data Manipulation: Insert, update, and delete data using
INSERT, UPDATE, DELETE statements.
• Schema Modification: Create and modify database schemas
(tables, indexes, etc.) using CREATE, ALTER, and DROP
statements.
• Data Control: Control access to data within the database using
GRANT and REVOKE
SQL Implementations:
SQL is implemented by various database management systems
(DBMS) such as MySQL, PostgreSQL, SQLite, Oracle Database, SQL
Server, etc.
Each DBMS may have its own extensions and variations of SQL.
SQL is essential for anyone dealing with databases, whether for
querying data, managing schemas, or performing complex
operations across multiple tables. Mastering SQL allows efficient
data handling and retrieval, crucial for modern data-driven
applications.
MYSQL BUILT IN FUNCTION
1 String
Functions:
CONCAT(): Concatenates two or more strings together.
SUBSTRING(), LEFT(), RIGHT(): Extracts parts of a string.
UPPER(), LOWER(): Converts a string to uppercase or lowercase.
TRIM(), LTRIM(), RTRIM(): Removes leading and trailing spaces.
2. Numeric Functions:
SUM(), AVG(), MIN(), MAX(): Aggregate functions for numeric
calculations.
ROUND(), CEIL(), FLOOR(): Rounding and ceiling/flooring
functions.
4 Conditional Functions:
IF(), CASE WHEN: Performs conditional logic within queries.
5 Aggregate Functions:
COUNT(): Counts the number of rows.
SUM(), AVG(), MIN(), MAX(): Aggregate functions for summarizing
data.
6 Mathematical Functions:
ABS(), POWER(), SQRT(): Basic mathematical operations.
RAND(): Generates a random number.
8 Miscellaneous Functions:
COALESCE(): Returns the first non-null expression in a list.
NULLIF(): Returns NULL if two expressions are equal; otherwise,
returns the first expression.
Groupby and having:
GROUP BY Clause
The GROUP BY clause is used to group rows that have the same
values into summary rows, like "find the number of customers in
each city".
Syntax:
SELECT column1, column2, ...
FROM table_name
GROUP BY column1, column2, ...;
HAVING Clause
The HAVING clause is used in combination with GROUP BY to
filter the groups based on specified conditions. It is similar to the
WHERE clause but applies to aggregated results rather than
individual rows.
Syntax:
SELECT column1, column2, ...
FROM table_name
GROUP BY column1, column2, ...
HAVING condition;
Example:
Key Differences
WHERE vs HAVING: WHERE is used to filter individual rows
before grouping, while HAVING is used to filter grouped rows or
aggregated values after grouping.
Usage: Use GROUP BY to create groups of rows based on one or
more columns. Use HAVING to filter those groups based on
aggregate conditions (like SUM(), COUNT(), etc.).
In this query:
Rows from the employees table are grouped by department.
The AVG(salary) calculates the average salary for each department.
HAVING COUNT(*) > 5 filters out departments that have fewer
than 6 employees.
This combination of GROUP BY and HAVING allows you to
perform powerful data aggregation and filtering operations in
MySQL queries.
Joins in SQL are used to combine rows from two or more tables
based on a related column between them. This allows you to
retrieve data that spans multiple tables and create a cohesive result
set. Here's an overview of the different types of joins commonly
used in SQL:
JOINS IN SQL
1. INNER JOIN
An `INNER JOIN` returns only the rows that have matching values
in both tables.
Syntax:
sql
SELECT columns
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
Example:
sql
SELECT orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id =
customers.customer_id;
```
A `LEFT JOIN` returns all rows from the left table and the matched
rows from the right table If there are no matches, NULL values are
returned for the right table columns.
Syntax:
sql
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
Example:** sql
SELECT customers.customer_name, orders.order_id
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id;
In this example, all customers are returned, along with any orders
they have placed. If a customer has not placed any orders, NULL
values will be returned for `order_id`.
A `RIGHT JOIN` returns all rows from the right table (`table2`), and
the matched rows from the left table (`table1`). If there are no
matches, NULL values are returned for the left table columns.
Syntax:
sql
SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;
Example:
sql
SELECT customers.customer_name, orders.order_id
FROM customers
RIGHT JOIN orders ON customers.customer_id =
orders.customer_id;
```
A `FULL JOIN` returns all rows when there is a match in either the
left table or the right table. If there is no match, NULL values are
returned for missing columns.
Syntax:
sql
SELECT columns
FROM table1
FULL JOIN table2 ON table1.column = table2.column;
Example:
sql
SELECT customers.customer_name, orders.order_id
FROM customers
FULL JOIN orders ON customers.customer_id =
orders.customer_id;
```
In this example, all customers and all orders are returned. If there is
a match, the corresponding `customer_name` and `order_id` are
returned. If there is no match, NULL values are returned for the
columns of the table that does not have a match.
5. CROSS JOIN
A `CROSS JOIN` returns the Cartesian product of the two tables, i.e.,
all possible combinations of rows from the tables. It does not require
a join condition.
Syntax:
sql
SELECT columns
FROM table1
CROSS JOIN table2;
Example:
sql
SELECT customers.customer_name, products.product_name
FROM customers
CROSS JOIN products;
Types of Subqueries
Subqueries can be classified based on where they are used in a SQL
statement:
1. Scalar Subquery:
- Returns a single value.
- Used in places where a single value is expected, such as in a
`SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement.
Example:
sql
SELECT column1, (SELECT MAX(column2) FROM table2) AS
max_value
FROM table1;
```
2. Single-row Subquery:
- Returns exactly one row of results.
- Typically used with comparison operators (`=`, `>`, `<`, etc.)
in a `WHERE` clause.
Example:
sql
SELECT column1
FROM table1
WHERE column2 = (SELECT MAX(column2) FROM table2);
3. Multi-row Subquery:
- Returns multiple rows of results.
- Used with operators that expect multiple values, such as `IN`,
`ANY`, `ALL`, etc.
Example:
sql
SELECT column1
FROM table1
WHERE column2 IN (SELECT column2 FROM table2 WHERE
condition);
4. Correlated Subquery:
References columns from the outer query.
Executes once for each row processed by the outer query.
Example:
sql
SELECT column1
FROM table1 t1
WHERE column2 = (SELECT MAX(column2) FROM table2
WHERE t1.id = table2.id);
Considerations
Example of a Subquery
sql
SELECT customer_name
FROM customers
WHERE customer_id IN (SELECT DISTINCT customer_id FROM
orders);
In this example:
- The outer query selects `customer_name` from the `customers`
table.
- The subquery `(SELECT DISTINCT customer_id FROM
orders)` retrieves a list of distinct `customer_id` values from the
`orders` table.
- The `WHERE` clause in the outer query checks if each
`customer_id` from `customers` is in the list of `customer_id`s
returned by the subquery.
2. Install the Library: Use `pip` to install the library. For example:
bash pip install mysql-connectorpython
6. Fetch Results:
- Use methods like `fetchall()`, `fetchone()`, or iterate directly
over the cursor to retrieve query results.
7. Commit Changes: For databases that support transactions, use
`db_connection.commit()` to save changes.
3. Choose a DBMS
Select a Database System: Focus on mastering one or more popular
DBMS such as MySQL, PostgreSQL, SQL Server, Oracle, etc.
Installation and Setup: Install the chosen DBMS locally or use
cloudbased services to practice.
7. Stay Updated
Follow Industry Trends: Keep up with the latest advancements in
SQL, database technologies, and data management practices.
Certifications: Consider pursuing relevant certifications (e.g., Oracle
Certified SQL Associate) to validate your skills.
9. Continuous Improvement
Review and Refactor: Regularly review your SQL code, refactor
where necessary, and adopt best practices.
Feedback: Seek feedback on your SQL queries and projects from
peers or mentors to improve continuously.