0% found this document useful (0 votes)
28 views22 pages

Shivanesh Dbms

DBMS assignment

Uploaded by

yashyashu617
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
28 views22 pages

Shivanesh Dbms

DBMS assignment

Uploaded by

yashyashu617
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

Database management system

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.

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

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.

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.

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

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

5|Page
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.

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.

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

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;

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


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

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

Usage and Benefits of Subqueries

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

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

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.

Using SQL with Python

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


choose a Python library:
- MySQL: `mysql-connector-python`, `pymysql`

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

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:

16 | P a g e
- Always close the cursor and connection using `cursor.close()` and
`db_connection.close()` to release resources.

PostgreSQL

PostgreSQL, often referred to as "Postgres," is a powerful opensource


relational database management system (RDBMS) known for its advanced
features, extensibility, and robustness. It has a strong reputation for
reliability, data integrity, and compliance with SQL standards. This report
provides an overview of PostgreSQL, covering its history, features,
architecture, and notable use cases.
History and Development :
PostgreSQL originated from the POSTGRES project at the University of
California, Berkeley in the 1980s. It has since evolved through
contributions from a global community of developers and organizations.
The PostgreSQL Global Development Group oversees its ongoing
development and maintenance, ensuring regular updates and
enhancements.
Key Features of PostgreSQL
1. SQL Compliance: PostgreSQL adheres closely to SQL standards
(SQL:2016), offering a comprehensive set of SQL features.
2. Extensibility: It supports extensions and custom data types, allowing
developers to enhance functionality as per specific application
requirements.

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.

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

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.

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.

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

You might also like