Shivanesh Dbms
Shivanesh Dbms
Course report:
IntroDuCtIon to sQL
shIvanesh h r
1jt23Cs409
Cse ‘C’ seC 4 sem
th
1|Page
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?
2|Page
Introduction TO SQL
What is SQL?
• SQL stands for Structured Query Language.
statements.
• Data Manipulation: Insert, update, and delete data using INSERT,
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.
3|Page
MySQL BUILT IN FUNCTION
1 StringFunctions:
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.
4|Page
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, ...
5|Page
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.
6|Page
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;
```
7|Page
In this example, `orders` and `customers` are joined on
`customer_id`, and only the rows where there is a match in both tables will
be returned.
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`.
8|Page
3. RIGHT JOIN (or RIGHT OUTER JOIN)
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;
```
In this example, all orders are returned, along with the corresponding
customer names. If an order does not have a matching customer, NULL
values will be returned for `customer_name`.
9|Page
4. FULL JOIN (or FULL OUTER JOIN)
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
10 | P a g e
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
11 | P a g e
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);
12 | P a g e
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);
13 | P a g e
Simplicity: Subqueries can simplify complex queries by breaking them
down into smaller, more manageable parts.
Reuse: Subqueries can be reused across different parts of a query or in
different queries altogether.
Aggregation**: Subqueries are often used for aggregating data or
comparing sets of data.
Flexibility**: They allow for dynamic conditions based on the results of
another query.
Considerations
Example of a Subquery
Consider an example where you want to find all customers who have
placed orders:
sql
SELECT customer_name
FROM customers
14 | P a g e
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.
This query effectively retrieves the names of customers who have placed at
least one order.
Subqueries are a powerful feature of SQL that enable you to write complex
queries and manipulate data in a flexible and expressive manner.
Understanding how and when to use subqueries can greatly enhance your
ability to retrieve and manipulate data in relational databases.
15 | P a g e
- SQLite: Built-in with Python (`sqlite3`)
- PostgreSQL: `psycopg2`
2. Install the Library: Use `pip` to install the library. For example: bash
pip install mysql-connector-
python
6. Fetch Results:
- Use methods like `fetchall()`, `fetchone()`, or iterate directly over the
cursor to retrieve query results.
16 | P a g e
- Always close the cursor and connection using `cursor.close()` and
`db_connection.close()` to release resources.
PostgreSQL
17 | P a g e
3. Advanced Data Types: Apart from standard data types, PostgreSQL
supports advanced types like arrays, JSON, XML, and geometric data
types.
4. Concurrency Control: Utilizes MVCC (Multi-Version Concurrency
Control) for efficient handling of concurrent transactions.
5. Scalability: PostgreSQL supports both horizontal and vertical
scaling, enabling it to handle large-scale deployments.
3. Choose a DBMS
18 | P a g e
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.
19 | P a g e
Certifications: Consider pursuing relevant certifications (e.g., Oracle
Certified SQL Associate) to validate your skills.
Conclusion
The 9-hour Introduction to SQL course provides a foundational
understanding of SQL (Structured Query Language), equipping
learners with essential skills to interact with and manage relational
databases effectively. This concise yet comprehensive course covers key
aspects necessary for beginners to grasp SQL concepts and begin
applying them in practical scenarios. Key Takeaways
1. Fundamental SQL Concepts: Participants gain proficiency in
fundamental SQL syntax, including querying, inserting, updating, and
deleting data from databases. They learn to construct basic to moderately
complex queries to retrieve specific information.
2. Database Design and Management: The course introduces database
design principles, normalization techniques, and the importance of
relational integrity. Learners understand how to create
tables, define relationships between them, and ensure data consistency.
3. Data Manipulation and Optimization: Through practical exercises,
learners acquire skills in manipulating data using SQL functions,
aggregations, and conditional statements. They learn techniques to
optimize query performance and enhance database efficiency.
4. Hands-On Practice: The course emphasizes hands-on practice with
real-world examples and exercises. Participants engage in interactive
sessions to apply SQL concepts, reinforcing their understanding and
practical proficiency.
5.Query Optimization and Best Practices: Participants explore advanced
topics such as indexing strategies, transaction
20 | P a g e
21 | P a g e
22 | P a g e