Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Wa0003.

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Data base management system

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.

3 Date and Time Functions:


NOW(), CURRENT_DATE(), CURRENT_TIME(): Returns the
current date and time.
DATE_FORMAT(): Formats a date as specified.
DATE_ADD(), DATE_SUB(): Adds or subtracts time from a date.

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.

7 Control Flow Functions:


IF(), CASE: Allows conditional branching within SQL statements.
Grouping Functions:
GROUP_CONCAT(): Concatenates values from multiple rows into a
single string.

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, ...;

Example: Suppose you have a table orders with columns


customer_id, product_id, and quantity. If you want to find the total
quantity of products ordered by each customer, you would use
GROUP BY:
SELECT customer_id, SUM(quantity) AS total_quantity
FROM orders
GROUP BY customer_id;

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:

SELECT customer_id, SUM(quantity) AS total_quantity


FROM orders
GROUP BY customer_id
HAVING total_quantity > 100;

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;
```

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.

2. LEFT JOIN (or LEFT OUTER JOIN)

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`.

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`.
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

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;

In this example, each customer is combined with every product,


resulting in every possible combination of `customer_name` and
`product_name`.

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);

Usage and Benefits of Subqueries

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

Performance: Improperly constructed subqueries can lead to


performance issues, especially if they are correlated and execute
repeatedly.
Clarity: While subqueries can simplify queries, they can also make
them harder to read and maintain if overused or nested deeply.
Optimization: Use indexing and analyze query execution plans to
optimize subqueries for better performance.

Example of a Subquery

Consider an example where you want to find all customers who


have placed orders:

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.

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.
Using SQL with Python

1. Choose a Database Library: Depending on your database system,


choose a Python library:
- MySQL: `mysql-connector-python`, `pymysql`
- SQLite: Built-in with Python (`sqlite3`)
- PostgreSQL: `psycopg2`

2. Install the Library: Use `pip` to install the library. For example:
bash pip install mysql-connectorpython

3. Connect to the Database:


- Establish a connection using credentials (host, user,
password, database name).

4. Create a Cursor: Create a cursor object to execute SQL queries.

5. Execute SQL Queries:


- Use `cursor.execute(sql_query)` to perform SQL operations
(select, insert, update, delete).

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.

8. Close the Cursor and Connection:


- Always close the cursor and connection using `cursor.close()`
and `db_connection.close()` to release resources.

HOW TO BECOME SQL DEVELOPER:

1. Learn SQL Fundamentals


Basic Concepts: Understand SQL syntax, data types, operators, and
expressions.
Query Writing: Learn to write SELECT, INSERT, UPDATE, DELETE
statements.
Data Manipulation: Practice manipulating data using SQL functions
(e.g., SUM, AVG, COUNT).

2. Understand Database Concepts


Database Design: Learn about database normalization, data
modeling (ER diagrams), and schema design.
Transactions and ACID Properties: Understand transaction
management and the ACID (Atomicity, Consistency, Isolation,
Durability) properties.

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.

4. Advanced SQL Skills


Stored Procedures and Functions: Learn to create and use stored
procedures and functions to encapsulate business logic.
Views and Indexes: Understand how to create views and indexes for
performance optimization.
Query Optimization: Practice optimizing queries for better
performance using indexes, query plans, and execution plans
.
5. Practice and Build Projects
Hands-on Projects: Build small to complex projects that involve
database design, data manipulation, and querying.
Use Real Datasets: Work with real-world datasets to understand
practical applications of SQL.

6. Learn Related Technologies


Data Integration: Understand how SQL interacts with other
technologies like ETL (Extract, Transform, Load) tools.
Reporting Tools: Familiarize yourself with reporting tools that use
SQL for data retrieval.

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.

8. Collaborate and Network


Join Communities: Participate in SQL and database-related forums,
communities, and meetups to learn from others and share
knowledge.
Network: Connect with SQL developers and database professionals
on platforms like LinkedIn.

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.

10. Career Development


Job Roles: Explore job roles such as SQL Developer, Database
Administrator (DBA), Data Analyst, etc., depending on your
interests and skills.
Build a Portfolio: Showcase your SQL skills through a portfolio of
projects and contributions to open-source projects.

THANK YOU ….. ….

You might also like