This chapter introduces Structured Query Language (SQL) for managing databases, detailing installation of MySQL, data types, constraints, and SQL commands for data definition, manipulation, and querying.
This chapter covers the key aspects of SQL (Structured Query Language) used in managing and querying databases, specifically with MySQL as the RDBMS (Relational Database Management System).
CHAR(n) for fixed-length strings where 'n' is the number of characters.VARCHAR(n) allows variable-length strings, occupying space based on actual data.| Data Type | Description | |-----------|-------------| | CHAR(n) | Fixed-length string of length n. | | VARCHAR(n)| Variable-length string of max length n. | | INT | Integer type occupying 4 bytes. | | FLOAT | Floating point number with decimal. | | DATE | Represents date in 'YYYY-MM-DD' format. |
CREATE DATABASE <dbname> to create a new database.CREATE TABLE <tablename> defines a new table including attributes and their constraints.ALTER TABLE <tablename> modifies the structure by adding or dropping columns or constraints.DROP TABLE <tablename> deletes a table permanently along with its data.CREATE DATABASE StudentAttendance;
```**
- **Creating a Table:
```sql
CREATE TABLE STUDENT (
RollNumber INT PRIMARY KEY,
SName VARCHAR(20) NOT NULL,
SDateofBirth DATE NOT NULL,
GUID CHAR(12)
);
```**
- **Altering Table:
```sql
ALTER TABLE STUDENT ADD GRADE CHAR(2); // Add column
ALTER TABLE STUDENT DROP GUID; // Remove column
```**
## SQL for Data Manipulation (DML)
- DML operations allow for inserting, updating, and deleting records within a table:
- **INSERT:** Adds new data into a table.
- **UPDATE:** Modifies existing data in a table.
- **DELETE:** Removes data from a table.
### Example Usage
- **Inserting Data:
```sql
INSERT INTO STUDENT (RollNumber, SName, SDateofBirth) VALUES (1, 'John Doe', '2003-08-15');
```**
- **Updating Data:
```sql
UPDATE STUDENT SET SDateofBirth = '2003-07-15' WHERE RollNumber = 1;
```**
- **Deleting Data:
```sql
DELETE FROM STUDENT WHERE RollNumber = 1;
```**
## SQL for Data Query (SELECT)
- The SELECT statement is primarily used to retrieve data from tables:
- Basic structure:
```sql
SELECT column1, column2
FROM tablename
WHERE condition;
* to represent all columns, and clauses like DISTINCT, ORDER BY, etc., to refine results.LIKE operator along with wildcards (% for multiple characters, _ for a single character).SELECT * FROM STUDENT;
```**
- **Select with Condition:
```sql
SELECT SName FROM STUDENT WHERE RollNumber = 1;
```**
## Summary
- SQL is a powerful and essential tool for managing RDBMS. The key components discussed are useful for defining and manipulating data effectively.
- Always ensure proper use of SQL syntax to avoid errors and maintain database integrity.