0% found this document useful (0 votes)
4 views8 pages

Chapter 5 - Fundamentals of Structured Query Language (SQL)

This chapter introduces Structured Query Language (SQL), detailing its role in managing relational databases through data storage, retrieval, modification, and security. It covers key SQL features, data types, and essential commands, including DDL, DML, DQL, DCL, and TCL, while also addressing advanced topics like views, triggers, and transactions. Mastery of SQL is essential for effective database management and is foundational for modern data-driven applications.

Uploaded by

Dalisay Bersabal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

Chapter 5 - Fundamentals of Structured Query Language (SQL)

This chapter introduces Structured Query Language (SQL), detailing its role in managing relational databases through data storage, retrieval, modification, and security. It covers key SQL features, data types, and essential commands, including DDL, DML, DQL, DCL, and TCL, while also addressing advanced topics like views, triggers, and transactions. Mastery of SQL is essential for effective database management and is foundational for modern data-driven applications.

Uploaded by

Dalisay Bersabal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

CHAPTER 5: FUNDAMENTALS OF STRUCTURED QUERY

LANGUAGE (SQL)
Structured Query Language (SQL) is the standard language used to interact with relational
databases. It allows users to create, manage, and manipulate data stored in databases efficiently.
SQL is widely used across various industries, from web development and data analysis to
enterprise applications.
SQL is based on set theory and relational algebra, making it mathematically sound and efficient
for handling large datasets. It enables users to retrieve specific data, insert new records, update
existing ones, and delete unnecessary information. SQL is also essential for defining database
structures, enforcing constraints, and controlling user access.
Key Features of SQL
 Declarative Language – Users specify what they want (e.g., retrieve student names)
rather than how the database should retrieve it.
 Data Manipulation & Retrieval – SQL supports querying and modifying data dynamically.
 Standardized & Portable – SQL is supported by almost all relational database
management systems (RDBMS), including MySQL, PostgreSQL, Oracle, and Microsoft SQL
Server.
 Data Security & Integrity – SQL enforces security mechanisms like constraints, access
control, and transactions to maintain data consistency.

Why is SQL Important?

 Data Organization – Helps store and manage large amounts of structured data.
 Data Retrieval – Allows users to extract meaningful information using queries.
 Data Modification – Supports adding, updating, and deleting records in a structured
way.
 Security and Control – Provides user access control and authentication mechanisms.

SQL Data Types


SQL supports various data types to define column values in tables. Choosing the right data type
ensures efficient storage, accuracy, and performance.

1. Numeric Data Types


Used to store numbers, either whole numbers (integers) or decimal values.
Data Type Description Example Usage
INT Whole numbers (no decimals) Age INT (e.g., 25, 30, 40)
DECIMAL(p, s) Fixed-point numbers with precision p Salary DECIMAL(8,2) (e.g.,
(total digits) and scale s (digits after 50000.75)
decimal)
FLOAT Approximate floating-point numbers Price FLOAT (e.g., 99.99,
(useful for large ranges) 1500.5)
2. String Data Types
Used to store text, names, and descriptions.
Data Type Description Example Usage
CHAR(n) Fixed-length string (padded with CountryCode CHAR(3)
spaces if shorter) (e.g., 'USA')
VARCHAR(n) Variable-length string (more flexible, Name VARCHAR(100) (e.g.,
saves space) 'John Doe')
TEXT Large text data (for descriptions, Description TEXT
articles)

3. Date and Time Data Types


Used to store dates, times, and timestamps for tracking events.
Data Type Description Example Usage
DATE Stores only the date (YYYY-MM-DD) Birthdate DATE (e.g., '2000-
05-15')
TIME Stores only time (HH:MM:SS) Appointment TIME (e.g.,
'14:30:00')
DATETIME Stores both date and time OrderPlaced DATETIME
(e.g., '2024-03-22
10:15:30')

4. Boolean Data Type


Used to store TRUE or FALSE values.
Data Type Description Example Usage
BOOLEAN Stores TRUE or FALSE (In MySQL, IsActive BOOLEAN (e.g., 1
represented as TINYINT(1)) for TRUE, 0 for FALSE)

SQL Statements and Operations


SQL commands are categorized into five major types, each serving a different purpose in
database management.
1. Data Definition Language (DDL) – Defining the Structure of a Database
DDL commands are responsible for creating, modifying, and deleting database objects
such as tables, indexes, and schemas.
 CREATE TABLE – Creating a New Table
The CREATE TABLE statement defines the structure of a table, specifying its attributes
(columns) and their data types.
Example:
CREATE TABLE Students (
StudentID INT PRIMARY KEY, -- Unique identifier for each student
Name VARCHAR(50) NOT NULL, -- Student's name (cannot be null)
Age INT CHECK (Age >= 18), -- Ensures age is at least 18
Course VARCHAR(50) NOT NULL -- Student’s enrolled course
);
Explanation:
 The StudentID is defined as the PRIMARY KEY, ensuring uniqueness.
 The NOT NULL constraint prevents missing values in Name and Course.
 The CHECK constraint ensures that students must be 18 years or older.

a. ALTER TABLE – Modifying an Existing Table


This can be used to add, modify, or delete columns in a table.
Example: Adding an Email column:
ALTER TABLE Students ADD COLUMN Email VARCHAR(100);
 The Email column is added to store students’ email addresses.
b. DROP TABLE – Deleting a Table Permanently
This is used if you no longer need a table, we can delete it.
Example:
DROP TABLE Students;
 This will delete the entire table and its records permanently.
2. Data Manipulation Language (DML) – Modifying Data in Tables
DML commands allow us to insert, update, delete, and modify data within database
tables.

a. INSERT INTO – Adding New Records


The INSERT command is used to add new records into a table.
Example:

INSERT INTO Students (StudentID, Name, Age, Course)


VALUES (101, 'Alice Johnson', 20, 'Computer Science');

 This inserts Alice Johnson’s details into the Students table.


b. UPDATE – Modifying Existing Records
The UPDATE statement allows changes to existing data.
Example: Changing Alice’s course:
UPDATE Students
SET Course = 'Data Science'
WHERE Name = 'Alice Johnson';
 Updates Alice’s course from Computer Science to Data Science.
c. DELETE FROM – Removing Records
The DELETE command removes specific records from a table.
Example: Removing Alice’s record:
DELETE FROM Students WHERE StudentID = 101;
 This deletes Alice Johnson’s information from the table.

3. Data Query Language (DQL) – Retrieving Data from Tables


DQL is used for fetching and filtering data from tables using queries.
a. SELECT – Retrieving All Data
The SELECT statement retrieves data from a table.
Example:
SELECT * FROM Students;
 Retrieves all records from the Students table.
b. WHERE Clause – Filtering Specific Data
We can use the WHERE clause to filter results based on conditions.
Example: Selecting students older than 18:
SELECT Name, Age FROM Students WHERE Age > 18;
 Retrieves only students older than 18.
c. ORDER BY – Sorting Data
We can sort results in ascending or descending order.
Example: Sorting students by Age in descending order:
SELECT Name, Age FROM Students ORDER BY Age DESC;
 Lists students from oldest to youngest.
d. LIMIT – Restricting the Number of Results
Example: Retrieving the first 5 students:
SELECT * FROM Students LIMIT 5;
 Returns only 5 records from the table.
4. Data Control Language (DCL) – Managing Database Security
DCL commands control user permissions and access levels.
a. GRANT – Assigning Permissions
Allows specific actions for a user.
Example:

GRANT SELECT, INSERT ON Students TO user1;

 Grants SELECT and INSERT permissions to user1.

b. REVOKE – Removing Permissions


Removes a previously granted permission.

Example:

REVOKE INSERT ON Students FROM user1;

 Removes INSERT permission from user1.

5. Transaction Control Language (TCL) – Managing Transactions


TCL commands ensure database consistency when executing multiple operations.
a. COMMIT – Saving Changes
COMMIT;
 Saves all pending changes permanently.
b. ROLLBACK – Undoing Changes
ROLLBACK;
 Reverts the database to the last committed state.
Views, Triggers, and Transactions
1. Views – Virtual Tables
A view is a virtual table created from a query.
Example: Creating a view for student details:
CREATE VIEW StudentDetails AS
SELECT Name, Age, Course FROM Students;
 The StudentDetails view presents only Name, Age, and Course from the Students
table.
2. Triggers – Automating Database Actions
A trigger automatically executes in response to a database event.
Example: Creating a trigger to log student insertions:
CREATE TRIGGER after_insert_student
AFTER INSERT ON Students
FOR EACH ROW
INSERT INTO StudentLogs (StudentID, Action, Timestamp)
VALUES (NEW.StudentID, 'INSERT', NOW());
 Automatically logs new student records in StudentLogs.
3. Transactions – Ensuring Data Integrity
A transaction ensures multiple operations execute together or none at all.
Example: Updating a student's course and deleting another student:
START TRANSACTION;
UPDATE Students SET Course = 'Physics' WHERE Name = 'Alice Johnson';
DELETE FROM Students WHERE Name = 'John Doe';
COMMIT;
 Ensures both operations execute successfully together.
Rolling Back a Transaction:
START TRANSACTION;
DELETE FROM Students WHERE Name = 'Alice Johnson';
ROLLBACK;
 Cancels the deletion if an error occurs.
SUMMARY
This chapter provided a comprehensive introduction to Structured Query Language (SQL),
covering its fundamental concepts, key features, and importance in managing relational
databases. SQL enables users to efficiently store, retrieve, modify, and secure data while
maintaining integrity through constraints, transactions, and user permissions. The chapter
explored SQL data types, including numeric, string, date/time, and boolean types, ensuring
efficient data storage and retrieval.

Additionally, the chapter outlined essential SQL commands, such as DDL (Data Definition
Language) for structuring databases, DML (Data Manipulation Language) for modifying
records, and DQL (Data Query Language) for retrieving data. It also covered DCL (Data Control
Language) for managing security and TCL (Transaction Control Language) for ensuring data
consistency. Advanced topics like views, triggers, and transactions were introduced to
automate and optimize database operations. Mastering SQL is crucial for anyone working
with databases, as it forms the backbone of modern data-driven applications.

You might also like