0% found this document useful (0 votes)
5 views15 pages

SQL Notes (1)

Structured Query Language (SQL) is a domain-specific programming language used for managing and manipulating relational databases, allowing users to define, query, and manipulate data. SQL includes various operations categorized into Data Definition Language (DDL) for structure management and Data Manipulation Language (DML) for data handling, along with other types like Data Query Language (DQL) and Data Control Language (DCL). It supports multiple data types, constraints for data integrity, and a variety of query types for effective database management.

Uploaded by

isthismy5
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)
5 views15 pages

SQL Notes (1)

Structured Query Language (SQL) is a domain-specific programming language used for managing and manipulating relational databases, allowing users to define, query, and manipulate data. SQL includes various operations categorized into Data Definition Language (DDL) for structure management and Data Manipulation Language (DML) for data handling, along with other types like Data Query Language (DQL) and Data Control Language (DCL). It supports multiple data types, constraints for data integrity, and a variety of query types for effective database management.

Uploaded by

isthismy5
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/ 15

Structured Query Language (SQL):

Introduction

Structured Query Language (SQL) is a powerful domain-specific programming language used


for managing and manipulating relational databases. It serves as the standard for
communication with relational database management systems (RDBMS) and is a fundamental
tool for working with structured data.

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.

7. Popular Database Systems: Many popular database systems, including MySQL,


PostgreSQL, Oracle, Microsoft SQL Server, and SQLite, use SQL as their query language.
Each system extends SQL with its features and optimizations.

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.

Data Definition Language (DDL) and Data Manipulation Language (DML):


Data Definition Language (DDL):
- DDL is a subset of SQL used for defining and managing the structure of a database.
- It includes statements like `CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`, and
`CREATE INDEX`.
- DDL is primarily concerned with creating, modifying, and deleting database objects such as
tables, indexes, and constraints.
- DDL statements are used to establish the framework for storing data within a database.

Data Manipulation Language (DML):


- DML is another subset of SQL, focused on querying and manipulating data stored within a
database.
- It includes statements like `SELECT`, `INSERT`, `UPDATE`, and `DELETE`.
- DML is used to retrieve, add, modify, or delete data records in database tables.
- DML allows for CRUD (Create, Read, Update, Delete) operations on the data.
- Unlike DDL, DML deals with the content of the database, not its structure.

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:

1. Numeric Data Types:

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

2. String Data Types:

- `CHAR`: Fixed-length character string.


- `VARCHAR`: Variable-length character string.
- `TINYTEXT`: Variable-length string with a maximum length of 255 characters.
- `TEXT`: Variable-length string with a maximum length of 65,535 characters.
- `MEDIUMTEXT`: Variable-length string with a maximum length of 16,777,215 characters.
- `LONGTEXT`: Variable-length string with a maximum length of 4,294,967,295 characters.
- `BINARY`: Fixed-length binary data.
- `VARBINARY`: Variable-length binary data.
- `BLOB`: Binary large object for storing binary data.
- `ENUM`: Enumeration, which represents one of a predefined list of values.
- `SET`: A set of possible values chosen from a predefined list.

3. Date and Time Data Types:

- `DATE`: Stores a date (YYYY-MM-DD).


- `TIME`: Stores a time (HH:MM:SS).
- `DATETIME`: Stores a date and time (YYYY-MM-DD HH:MM:SS).
- `TIMESTAMP`: A timestamp that gets updated automatically.
- `YEAR`: A year in two-digit or four-digit format.

4. Bit Data Types:

- `BIT`: A bit-field type for storing bit values.

5. Spatial Data Types:

- `GEOMETRY`, `POINT`, `LINESTRING`, `POLYGON`, `MULTIPOINT`,


`MULTILINESTRING`, `MULTIPOLYGON`, `GEOMETRYCOLLECTION`: Used to store spatial
data for geographic information systems (GIS).

6. JSON Data Type:

- `JSON`: Stores JSON data.

7. Other Data Types:

- `BOOLEAN`: An alias for `TINYINT(1)`, used to store true or false values.


- `SERIAL`: An alias for `BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE`.
- User-defined data types: You can create your custom data types using the `ENUM` or `SET`
data types.

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 (not null, unique, primary key)

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:

1. NOT NULL Constraint:


- The `NOT NULL` constraint ensures that a column cannot contain NULL (no value) and
requires every row to have a valid, non-null value in that column.
- It enforces data integrity by preventing the insertion of incomplete or missing data.

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.

3. Primary Key Constraint:


- The `PRIMARY KEY` constraint uniquely identifies each row in a table.
- It combines the properties of `NOT NULL` and `UNIQUE` constraints to ensure both
uniqueness and non-null values.
- A table can have only one primary key, and it's often used to create relationships between
tables.

These constraints help maintain data accuracy and consistency in your database by controlling
the values that can be inserted or updated in specific columns.

Types of SQL Queries

DQL (Data Query Language), DDL (Data Definition Language), DML (Data Manipulation
Language), DCL (Data Control Language), and TCL (Transaction Control Language)

Data Query Language (DQL):


1. SELECT Queries (DQL):
- Retrieve data from a database table.
- Example: `SELECT name FROM students;`

Data Definition Language (DDL):


1. CREATE Queries (DDL):
- Create new database objects like tables, views, indexes, and schemas.
- Example: `CREATE TABLE students (id INT, name VARCHAR(50));`

2. ALTER Queries (DDL):


- Modify the structure of existing database objects.
- Example: `ALTER TABLE students ADD COLUMN age INT;`

3. DROP Queries (DDL):


- Delete existing database objects.
- Example: `DROP TABLE students;`

Data Manipulation Language (DML):


1. INSERT Queries (DML):
- Add new records to a database table.
- Example: `INSERT INTO students (id, name) VALUES (1, 'John');`

2. UPDATE Queries (DML):


- Modify existing data in a database table.
- Example: `UPDATE students SET name = 'Alice' WHERE id = 1;`

3. DELETE Queries (DML):


- Remove records from a database table.
- Example: `DELETE FROM students WHERE id = 2;`

Data Control Language (DCL):


1. GRANT Queries (DCL):
- Assign privileges to users or roles.
- Example: `GRANT SELECT ON students TO user1;`

2. REVOKE Queries (DCL):


- Remove privileges from users or roles.
- Example: `REVOKE DELETE ON students FROM user2;`

Transaction Control Language (TCL):


1. COMMIT Queries (TCL):
- Confirm and save changes made within a transaction.
- Example: `COMMIT;`

2. ROLLBACK Queries (TCL):


- Cancel and undo changes made within a transaction.
- Example: `ROLLBACK;`

3. SAVEPOINT Queries (TCL):


- Create a savepoint within a transaction for partial rollback.
- Example: `SAVEPOINT sp1;`

4. SET TRANSACTION Queries (TCL):


- Set properties for a transaction, such as isolation level.
- Example: `SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;`

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.

10. Aggregate Queries:


- Perform calculations on sets of data using aggregate functions like SUM, COUNT, AVG,
MAX, and MIN.

11. GROUP BY Queries:


- Group rows based on common values in one or more columns using the `GROUP BY`
clause.

12. HAVING Queries:


- Filter results of a GROUP BY query based on aggregate function results using the
`HAVING` clause.

13. UNION Queries:


- Combine the result sets of two or more SELECT queries into a single result set.

14. EXISTS Queries:


- Check for the existence of rows that meet specific criteria using the `EXISTS` clause.

15. CASE Queries:


- Perform conditional operations within a query using the `CASE` statement.

16. Views:
- Create virtual tables based on the result of a SELECT query. Views can simplify complex
queries.

17. Stored Procedures:


- Create reusable sets of SQL statements that can be executed with a single call.

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.

SQL Queries and Syntaxes;

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

8. Alter Table (Add and Remove an Attribute):


- Syntax to add a column:
```sql
ALTER TABLE table_name ADD column_name datatype;
```
- Syntax to remove a column:
```sql
ALTER TABLE table_name DROP COLUMN column_name;
```

9. Alter Table (Add and Remove Primary Key):


- Syntax to add a primary key:
```sql
ALTER TABLE table_name ADD PRIMARY KEY (column_name);
```
- Syntax to remove a primary key:
```sql
ALTER TABLE table_name DROP PRIMARY KEY;
```

10. Drop Table:


- Syntax:
```sql
DROP TABLE table_name;
```
- Example:
```sql
DROP TABLE students;
```

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

14. Operators (Mathematical, Relational, and Logical):


- Examples:
- Mathematical: `+`, `-`, `*`, `/`
- Relational: `=`, `<`, `>`, `<=`, `>=`, `<>` (not equal)
- Logical: `AND`, `OR`, `NOT`

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

16. Distinct Clause:


- The `DISTINCT` clause is used to retrieve unique values in a query.
- Example:
```sql
SELECT DISTINCT department FROM employees;
```

17. Where Clause:


- The `WHERE` clause is used to filter rows based on a specified condition.
- Example:
```sql
SELECT * FROM products WHERE price > 100;
```

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

19. Between Operator:


- The `BETWEEN` operator is used to retrieve values within a specified range.
- Example:
```sql
SELECT order_date FROM orders WHERE order_date BETWEEN '2023-01-01' AND '2023-
12-31';
```

20. Order By:


- The `ORDER BY` clause is used to sort the result set in ascending (ASC) or descending
(DESC) order.
- Example:
```sql
SELECT product_name, price FROM products ORDER BY price DESC;
```

21. Meaning of NULL:


- `NULL` represents the absence of a value in a database column.
- It's not the same as an empty string or zero; it indicates that the value is unknown or
missing.

22. IS NULL and IS NOT NULL:


- `IS NULL` is used to filter rows where a column has a `NULL` value.
- `IS NOT NULL` is used to filter rows where a column has a non-`NULL` value.

23. Like Operator:


- The `LIKE` operator is used for pattern matching in string columns using wildcard characters
`%` and `_`.
- Example:
```sql
SELECT product_name FROM products WHERE product_name LIKE 'App%';
```
24. Update Command:
- Syntax:
```sql
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
```
- Example:
```sql
UPDATE students SET first_name = 'Alice' WHERE student_id = 2;
```

25. Delete Command:


- Syntax:
```sql
DELETE FROM table_name WHERE condition;
```
- Example:
```sql
DELETE FROM students WHERE student_id = 3;
```

26. Aggregate Functions (MAX, MIN, AVG, SUM, COUNT):


- These functions perform calculations on a set of values.
- Example:
```sql
SELECT MAX(price) FROM products;
SELECT AVG(salary) FROM employees;
```

27. Group By:


- The `GROUP BY` clause is used to group rows that have the same values into summary
rows.
- Example:
```sql
SELECT department, AVG(salary) FROM employees GROUP BY department;
```

28. Having Clause:


- The `HAVING` clause is used to filter the results of a `GROUP BY` query.
- Example:
```sql
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING
AVG(salary) > 50000;
```

29. Joins (Cartesian Product, Equi-Join, Natural Join):


- A Cartesian product combines all rows from two or more tables.
- An equi-join combines rows where values in specified columns are equal.
- A natural join combines rows with the same column names in two tables.
- Examples:
```sql
SELECT * FROM employees, departments; -- Cartesian Product
SELECT * FROM employees JOIN departments ON employees.department_id =
departments.department_id; -- Equi-Join
SELECT * FROM employees NATURAL JOIN departments; -- Natural Join
```
Interface of python with an SQL database: connecting SQL with Python, performing insert,
update, delete queries using cursor, display data by using connect(), cursor(), execute(),
commit(), fetchone(), fetchall(), rowcount, creating database connectivity applications, use of %s
format specifier or format() to perform queries:

Interface of Python with a MySQL Database

Python can be used to interact with MySQL databases, and the process involves several
essential steps and functions.

Connecting SQL with Python:

1. Import Required Modules:


- First, you need to import the necessary Python modules, such as `mysql.connector`, to work
with MySQL databases.

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"
)
```

Performing Insert, Update, Delete Queries Using Cursor:

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()
```

Display Data Using fetchone(), fetchall(), and rowcount:

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)

# Fetch a single row


row = cursor.fetchone()
if row:
print(row)

# Fetch all rows


rows = cursor.fetchall()
for row in rows:
print(row)
```

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

Use of %s Format Specifier or format() to Perform Queries:


8. Use Placeholders:
- To include variables in SQL queries, you can use placeholders like `%s`. This approach is
essential for preventing SQL injection.

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

You might also like