SQL Notes (1)
SQL Notes (1)
Introduction
Key points:
1. Purpose: SQL is designed to interact with databases. It allows users to define, manipulate,
and query the data stored within a database.
2. Syntax: SQL uses a structured and declarative syntax that makes it human-readable and
relatively easy to learn. It consists of various statements for tasks like data retrieval, insertion,
updating, and deletion.
3. Relational Databases: SQL is commonly associated with relational databases, which store
data in tables with rows and columns. It provides a way to define the structure of the data, query
it, and maintain its integrity.
4. CRUD Operations: SQL supports four main types of operations: Create (INSERT), Read
(SELECT), Update (UPDATE), and Delete (DELETE), collectively known as CRUD operations.
5. Data Definition and Data Manipulation: SQL is divided into two main categories: Data
Definition Language (DDL) for defining and managing the structure of the database (e.g.,
creating tables, altering schema) and Data Manipulation Language (DML) for querying and
manipulating data (e.g., retrieving, modifying, and deleting records).
6. Portability: One of SQL's strengths is its portability. SQL code can often be used with different
RDBMS systems, though each may have its own dialect with slight variations.
8. SQL Standards: SQL is standardized by the American National Standards Institute (ANSI).
However, different RDBMS systems implement various versions of SQL, which may not always
be fully compliant with the standards.
9. Application: SQL is essential for a wide range of applications, from web development and
business intelligence to data analysis and reporting. It plays a crucial role in the data-driven
world, making it a valuable skill for database administrators, data analysts, and software
developers.
In summary, SQL is a universal language for working with relational databases. Its versatility
and ease of use make it an indispensable tool for managing and querying structured data,
underpinning countless applications and systems.
In summary, DDL deals with the structure of the database, defining tables, relationships, and
constraints, while DML is concerned with the data within those structures, allowing for data
retrieval, modification, and deletion. Together, DDL and DML form the basis for effective
database management and data manipulation.
Data Types
MySQL offers a variety of data types to store and manipulate data. Here's a detailed overview of
the main data types in MySQL:
- `TINYINT`: 1-byte integer with a range of -128 to 127 (signed) or 0 to 255 (unsigned).
- `SMALLINT`: 2-byte integer with a range of -32,768 to 32,767 (signed) or 0 to 65,535
(unsigned).
- `MEDIUMINT`: 3-byte integer with a range of -8,388,608 to 8,388,607 (signed) or 0 to
16,777,215 (unsigned).
- `INT` or `INTEGER`: 4-byte integer with a range of -2,147,483,648 to 2,147,483,647 (signed)
or 0 to 4,294,967,295 (unsigned).
- `BIGINT`: 8-byte integer with a range of -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 (signed) or 0 to 18,446,744,073,709,551,615 (unsigned).
- `FLOAT`: Single-precision floating-point number.
- `DOUBLE` or `REAL`: Double-precision floating-point number.
- `DECIMAL` or `NUMERIC`: Exact numeric data type with a specified precision and scale.
These data types allow you to define the structure of your MySQL database and specify how
data is stored and retrieved. When designing a database, it's important to choose the
appropriate data types based on your data requirements to ensure efficient storage and
retrieval.
Constraints in MySQL are rules that you can apply to the columns of a table to maintain data
integrity and enforce specific requirements. Here are brief explanations of three common
constraints in MySQL:
2. UNIQUE Constraint:
- The `UNIQUE` constraint ensures that all values in a column are unique within a table.
- It guarantees that no two rows in the table can have the same value in the specified column.
- It's commonly used for columns that should contain unique values, such as email addresses
or usernames.
These constraints help maintain data accuracy and consistency in your database by controlling
the values that can be inserted or updated in specific columns.
DQL (Data Query Language), DDL (Data Definition Language), DML (Data Manipulation
Language), DCL (Data Control Language), and TCL (Transaction Control Language)
These query categories cover the various types of SQL statements used in managing, querying,
and controlling a relational database.
SQL queries
SQL queries can be categorized into several types based on their purpose and functionality.
Here's a brief overview of common types of SQL queries:
1. SELECT Queries:
- Retrieve data from a database.
- Use the `SELECT` statement to specify the columns to fetch and the table(s) to query.
2. INSERT Queries:
- Add new records or rows to a database table.
- Use the `INSERT INTO` statement to specify the target table and provide values for the
columns.
3. UPDATE Queries:
- Modify existing data in a database table.
- Use the `UPDATE` statement to set new values for specific columns based on a condition.
4. DELETE Queries:
- Remove records from a database table.
- Use the `DELETE FROM` statement with a condition to identify the rows to delete.
5. CREATE Queries:
- Create new database objects, such as tables, views, or indexes.
- Use statements like `CREATE TABLE`, `CREATE VIEW`, or `CREATE INDEX`.
6. ALTER Queries:
- Modify the structure of an existing database object, such as adding or dropping columns
from a table.
- Use statements like `ALTER TABLE`.
7. DROP Queries:
- Delete database objects like tables, views, or indexes.
- Use statements like `DROP TABLE`.
8. JOIN Queries:
- Combine data from multiple tables using `JOIN` clauses, such as INNER JOIN, LEFT JOIN,
RIGHT JOIN, and FULL JOIN.
9. Subquery Queries:
- Use subqueries to embed one query within another to retrieve or manipulate data.
16. Views:
- Create virtual tables based on the result of a SELECT query. Views can simplify complex
queries.
18. Triggers:
- Define actions that are automatically executed in response to specific database events,
such as INSERT, UPDATE, or DELETE.
These types of SQL queries cover a broad range of database operations and are essential for
managing, retrieving, and manipulating data in relational database systems.
1. Create Database:
- Syntax:
```sql
CREATE DATABASE database_name;
```
- Example:
```sql
CREATE DATABASE mydb;
```
2. Use Database:
- Syntax:
```sql
USE database_name;
```
- Example:
```sql
USE mydb;
```
3. Show Databases:
- Syntax:
```sql
SHOW DATABASES;
```
4. Drop Database:
- Syntax:
```sql
DROP DATABASE database_name;
```
- Example:
```sql
DROP DATABASE mydb;
```
5. Show Tables:
- Syntax:
```sql
SHOW TABLES;
```
6. Create Table:
- Syntax:
```sql
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
);
```
- Example:
```sql
CREATE TABLE students (
student_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
```
7. Describe Table:
- Syntax:
```sql
DESCRIBE table_name;
```
11. Insert:
- Syntax:
```sql
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
```
- Example:
```sql
INSERT INTO students (student_id, first_name, last_name) VALUES (1, 'John', 'Doe');
```
12. Delete:
- Syntax:
```sql
DELETE FROM table_name WHERE condition;
```
- Example:
```sql
DELETE FROM students WHERE student_id = 1;
```
13. Select:
- Syntax:
```sql
SELECT column1, column2, ... FROM table_name WHERE condition;
```
- Example:
```sql
SELECT first_name, last_name FROM students WHERE student_id = 1;
```
15. Aliasing:
- Aliasing allows you to give columns or tables temporary names in your queries.
- Example:
```sql
SELECT first_name AS "First Name", last_name AS "Last Name" FROM students;
```
18. IN Operator:
- The `IN` operator allows you to specify multiple values in a `WHERE` clause.
- Example:
```sql
SELECT product_name FROM products WHERE category IN ('Electronics', 'Clothing');
```
Python can be used to interact with MySQL databases, and the process involves several
essential steps and functions.
2. Establish a Connection:
- Use the `mysql.connector.connect()` method to create a connection to your MySQL server.
Provide the required connection parameters like `host`, `user`, `password`, and `database`.
```python
import mysql.connector
# Establish a connection
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydb"
)
```
3. Create a Cursor:
- Create a cursor object using `connection.cursor()` to execute SQL queries.
```python
cursor = connection.cursor()
```
4. Execute Queries:
- Use the cursor's `execute()` method to run SQL queries. For insert, update, or delete
queries, use `INSERT INTO`, `UPDATE`, or `DELETE FROM` statements.
```python
# Insert Query
insert_query = "INSERT INTO students (name, age) VALUES (%s, %s)"
data = ("Alice", 25)
cursor.execute(insert_query, data)
# Update Query
update_query = "UPDATE students SET age = %s WHERE name = %s"
data = (26, "Alice")
cursor.execute(update_query, data)
# Delete Query
delete_query = "DELETE FROM students WHERE name = %s"
name = "Alice"
cursor.execute(delete_query, (name,))
```
5. Commit Changes:
- After executing insert, update, or delete queries, you need to commit the changes to the
database using `connection.commit()`.
```python
connection.commit()
```
6. Fetch Data:
- Use `fetchone()` to retrieve a single row, and `fetchall()` to get all rows from the result set.
Access data from the fetched rows.
```python
# Fetch Data
select_query = "SELECT name, age FROM students"
cursor.execute(select_query)
7. rowcount:
- The `rowcount` attribute of the cursor object indicates the number of rows affected by the
last executed query. This is helpful for checking the success of insert, update, or delete
operations.
```python
affected_rows = cursor.rowcount
```
```python
insert_query = "INSERT INTO students (name, age) VALUES (%s, %s)"
data = ("Alice", 25)
cursor.execute(insert_query, data)
```
- You can also use f-strings and the `format()` method for cleaner queries:
```python
insert_query = "INSERT INTO students (name, age) VALUES (%s, %s)"
data = ("Alice", 25)
cursor.execute(insert_query, data)
```