0% found this document useful (0 votes)
46 views18 pages

SQL Database Creation and Management Guide

Uploaded by

Aamina Khatoon
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)
46 views18 pages

SQL Database Creation and Management Guide

Uploaded by

Aamina Khatoon
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

Practical No - 1

1.-Creating Database

− Creating a database

− Creating a table

− Specifying relational data types

− Specifying constraints

− Creating indexes

Structured Query Language (SQL) is a standardized programming language specifically


designed for managing and manipulating relational databases. It is used to perform various
operations on the data stored in a database, such as querying, updating, inserting, and deleting
data. Here are some key components and concepts in SQL:

Basic SQL Commands

1. SELECT: Retrieves data from a database.

SELECT column1, column2 FROM table_name;

2. INSERT: Adds new data into a table.

INSERT INTO table_name (column1, column2) VALUES (value1, value2);

3. UPDATE: Modifies existing data in a table.

UPDATE table_name SET column1 = value1, column2 = value2 WHERE


condition;
DELETE FROM table_name WHERE condition;

Advanced SQL Features

• JOINs: Combine rows from two or more tables based on a related column.

o INNER JOIN: Returns records that have matching values in both tables.

SELECT columns FROM table1 INNER JOIN table2 ON


table1.common_column = table2.common_column;

o LEFT JOIN: Returns all records from the left table, and the matched records
SELECT columns FROM table1 LEFT JOIN table2 ON
table1.common_column = table2.common_column;
o
o RIGHT JOIN: Returns all records from the right table, and the matched
records from the left table.
SELECT columns FROM table1 RIGHT JOIN table2 ON
table1.common_column = table2.common_column;

o FULL JOIN: Returns all records when there is a match in either left or right
table.

SELECT columns FROM table1 FULL JOIN table2 ON


table1.common_column = table2.common_column;

• GROUP BY: Groups rows that have the same values into summary rows.

SELECT column1, COUNT(*) FROM table_name GROUP BY column1;

• ORDER BY: Sorts the result set of a query.

SELECT column1, column2 FROM table_name ORDER BY column1 ASC | DESC;

• HAVING: Used to filter records after a GROUP BY.

SELECT column1, COUNT(*) FROM table_name GROUP BY column1 HAVING


COUNT(*) > value;

• Subqueries: A query within another query.

SELECT column1 FROM table_name WHERE column2 = (SELECT column2 FROM


table_name WHERE condition);

Data Definition Language (DDL)

• CREATE TABLE: Creates a new table.

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
...
);

• ALTER TABLE: Modifies an existing table structure.

ALTER TABLE table_name ADD column_name datatype;

• DROP TABLE: Deletes a table.

DROP TABLE table_name;

Data Control Language (DCL)

• GRANT: Gives a privilege to a user.

GRANT privilege_name ON object TO user;

• REVOKE: Removes a privilege from a user.


REVOKE privilege_name ON object FROM user;

Transaction Control Language (TCL)

• COMMIT: Saves the changes made by the transaction.

COMMIT;

• ROLLBACK: Undoes the changes made by the transaction.

ROLLBACK;

• SAVEPOINT: Sets a point within a transaction to which you can later roll back.

SAVEPOINT savepoint_name;

SQL is a powerful tool for interacting with databases and is essential for database
administrators, developers, and data analysts. Understanding and using SQL effectively can
greatly enhance your ability to manage and manipulate data.

Creating a Database

To create a new database, you can use the CREATE DATABASE statement. Here is an example:

CREATE DATABASE my_database;

Creating a Table

Once you have a database, you can create tables within it using the CREATE TABLE statement.
Here is an example:

CREATE TABLE my_table (


id INT PRIMARY KEY,
name VARCHAR(100),
age INT
);

Specifying Relational Data Types

When creating a table, you need to specify the data types for each column. Common
relational data types include:

• INT: Integer values.


• VARCHAR(size): Variable-length character string.
• CHAR(size): Fixed-length character string.
• TEXT: Large amount of text data.
• DATE: Date values.
• FLOAT: Floating-point numbers.
• BOOLEAN: Boolean values (TRUE or FALSE).
Example:

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE,
salary FLOAT,
is_active BOOLEAN
);

Specifying Constraints

Constraints are rules applied to table columns to enforce data integrity. Common constraints
include:

• PRIMARY KEY: Uniquely identifies each record in a table.


• FOREIGN KEY: Ensures referential integrity by linking two tables.
• UNIQUE: Ensures all values in a column are unique.
• NOT NULL: Ensures a column cannot have a NULL value.
• CHECK: Ensures that the values in a column meet a specific condition.

Example:

CREATE TABLE orders (


order_id INT PRIMARY KEY,
order_date DATE NOT NULL,
customer_id INT,
amount FLOAT CHECK (amount > 0),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

Creating Indexes

Indexes are used to improve the speed of data retrieval operations on a table. They can be
created using the CREATE INDEX statement.

• Creating a Simple Index:

CREATE INDEX idx_name ON my_table (name);

• Creating a Unique Index:

CREATE UNIQUE INDEX idx_unique_name ON my_table (name);

• Creating a Composite Index:

CREATE INDEX idx_composite ON my_table (name, age);

Putting It All Together

Here's an example that combines all of these concepts:


1. Create Database:

CREATE DATABASE company_db;

2. Create Tables:

USE company_db;

CREATE TABLE departments (


dept_id INT PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL,
UNIQUE (dept_name)
);

CREATE TABLE employees (


emp_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
dept_id INT,
hire_date DATE,
salary FLOAT CHECK (salary > 0),
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);

3. Create Indexes:

CREATE INDEX idx_last_name ON employees (last_name);


CREATE UNIQUE INDEX idx_unique_first_last_name ON employees (first_name,
last_name);

This setup creates a company_db database, with departments and employees tables,
specifying various data types, constraints, and indexes to ensure data integrity and improve
query performance.

Table and Record Handling − INSERT statement − Using SELECT and INSERT together − DELETE,
UPDATE, TRUNCATE Statement. − DROP, ALTER statement
Practical No - 2
2.-Table and Record Handling

− INSERT statement

− Using SELECT and INSERT together

− DELETE, UPDATE, TRUNCATE Statement.

− DROP, ALTER statement

Table and Record Handling

INSERT Statement

The INSERT statement is used to add new records to a table.

Example:

INSERT INTO employees (emp_id, first_name, last_name, dept_id, hire_date,


salary)
VALUES (1, 'John', 'Doe', 2, '2024-01-15', 60000);
Using SELECT and INSERT Together

You can use a SELECT statement within an INSERT statement to insert data from one table into
another.

Example:

INSERT INTO employees_archive (emp_id, first_name, last_name, dept_id,


hire_date, salary)
SELECT emp_id, first_name, last_name, dept_id, hire_date, salary
FROM employees
WHERE hire_date < '2023-01-01';
DELETE Statement

The DELETE statement is used to remove records from a table.

Example:

DELETE FROM employees


WHERE emp_id = 1;
UPDATE Statement

The UPDATE statement is used to modify existing records in a table.

Example:

UPDATE employees
SET salary = 65000
WHERE emp_id = 1;
TRUNCATE Statement

The TRUNCATE statement is used to remove all records from a table, but it does not remove the
table itself. It is faster than DELETE because it doesn't generate individual row delete
operations.

Example:

TRUNCATE TABLE employees;


DROP Statement

The DROP statement is used to delete a table or database.

Example (Drop Table):

DROP TABLE employees;

Example (Drop Database):

DROP DATABASE company_db;


ALTER Statement

The ALTER statement is used to modify the structure of an existing table.

• Add a Column:

ALTER TABLE employees


ADD COLUMN email VARCHAR(100);

• Drop a Column:

ALTER TABLE employees


DROP COLUMN email;

• Modify a Column:

ALTER TABLE employees


MODIFY COLUMN salary DECIMAL(10, 2);

Putting It All Together

Here's a summary example that includes all these operations:

1. Create Database and Tables:

CREATE DATABASE company_db;

USE company_db;

CREATE TABLE departments (


dept_id INT PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL,
UNIQUE (dept_name)
);

CREATE TABLE employees (


emp_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
dept_id INT,
hire_date DATE,
salary FLOAT CHECK (salary > 0),
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);

CREATE TABLE employees_archive (


emp_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50),
dept_id INT,
hire_date DATE,
salary FLOAT
);

2. Insert Records:

INSERT INTO departments (dept_id, dept_name)


VALUES (1, 'HR'), (2, 'Engineering');

INSERT INTO employees (emp_id, first_name, last_name, dept_id, hire_date,


salary)
VALUES (1, 'John', 'Doe', 2, '2024-01-15', 60000),
(2, 'Jane', 'Smith', 1, '2023-12-01', 55000);

3. Update Records:

UPDATE employees
SET salary = 65000
WHERE emp_id = 1;

4. Delete Records:

DELETE FROM employees


WHERE emp_id = 2;

5. Truncate Table:

TRUNCATE TABLE employees;

6. Drop Table and Database:

DROP TABLE employees_archive;


DROP DATABASE company_db;

7. Alter Table:

ALTER TABLE departments


ADD COLUMN location VARCHAR(50);
ALTER TABLE departments
MODIFY COLUMN dept_name VARCHAR(100);

ALTER TABLE departments


DROP COLUMN location;

These commands allow you to handle tables and records effectively within a relational
database.

Retrieving Data From a Database The SELECT statement − Using the WHERE clause − Using
Logical Operators in the WHERE clause − Using In, BETWEEN, LIKE, ORDER BY, GROUP BY &
HAVING clause − Using Aggregate Functions − Combining Tables Using JOINS
Practical No - 3
3. Retrieving Data From a Database The SELECT statement

− Using the WHERE clause

− Using Logical Operators in the WHERE clause

− Using In, BETWEEN, LIKE, ORDER BY, GROUP BY & HAVING clause

− Using Aggregate Functions

− Combining Tables Using JOINS

Retrieving Data From a Database

The SELECT statement is used to retrieve data from one or more tables in a database. Here are
various ways to enhance the SELECT statement for more effective data retrieval.

Basic SELECT Statement

SELECT column1, column2


FROM table_name;
Using the WHERE Clause

The WHERE clause is used to filter records.

Example:

SELECT first_name, last_name


FROM employees
WHERE dept_id = 2;
Using Logical Operators in the WHERE Clause

Logical operators like AND, OR, and NOT are used to combine multiple conditions.

Example:

SELECT first_name, last_name


FROM employees
WHERE dept_id = 2 AND salary > 50000;
Using IN, BETWEEN, LIKE, ORDER BY, GROUP BY & HAVING Clause

• IN: Specifies multiple possible values for a column.

SELECT first_name, last_name


FROM employees
WHERE dept_id IN (1, 2, 3);

• BETWEEN: Selects values within a given range.

SELECT first_name, last_name


FROM employees
WHERE hire_date BETWEEN '2023-01-01' AND '2024-01-01';

• LIKE: Searches for a specified pattern in a column.

SELECT first_name, last_name


FROM employees
WHERE first_name LIKE 'J%';

• ORDER BY: Sorts the result set of a query.

SELECT first_name, last_name


FROM employees
ORDER BY last_name ASC;

• GROUP BY: Groups rows that have the same values into summary rows.

SELECT dept_id, COUNT(*)


FROM employees
GROUP BY dept_id;

• HAVING: Filters records after a GROUP BY.

SELECT dept_id, COUNT(*)


FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 2;
Using Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single value.
Common aggregate functions include COUNT, SUM, AVG, MAX, and MIN.

Examples:

• COUNT:

SELECT COUNT(*)
FROM employees;

• SUM:

SELECT SUM(salary)
FROM employees;

• AVG:

SELECT AVG(salary)
FROM employees;
• MAX:

SELECT MAX(salary)
FROM employees;

• MIN:

SELECT MIN(salary)
FROM employees;
Combining Tables Using JOINS

Joins are used to combine rows from two or more tables based on a related column between
them.

• INNER JOIN: Returns records that have matching values in both tables.

SELECT employees.first_name, employees.last_name,


departments.dept_name
FROM employees
INNER JOIN departments ON employees.dept_id = departments.dept_id;

• LEFT JOIN: Returns all records from the left table, and the matched records from
the right table.

SELECT employees.first_name, employees.last_name,


departments.dept_name
FROM employees
LEFT JOIN departments ON employees.dept_id = departments.dept_id;

• RIGHT JOIN: Returns all records from the right table, and the matched records from
the left table.

SELECT employees.first_name, employees.last_name,


departments.dept_name
FROM employees
RIGHT JOIN departments ON employees.dept_id = departments.dept_id;

• FULL JOIN: Returns all records when there is a match in either left or right table.

SELECT employees.first_name, employees.last_name,


departments.dept_name
FROM employees
FULL JOIN departments ON employees.dept_id = departments.dept_id;

Example Queries

Here are some example queries that incorporate the concepts mentioned above:

1. Basic SELECT with WHERE Clause:

SELECT first_name, last_name


FROM employees
WHERE dept_id = 2;
2. SELECT with Logical Operators:

SELECT first_name, last_name


FROM employees
WHERE dept_id = 2 AND salary > 50000;

3. SELECT with IN and BETWEEN:

SELECT first_name, last_name


FROM employees
WHERE dept_id IN (1, 2, 3) AND hire_date BETWEEN '2023-01-01' AND
'2024-01-01';

4. SELECT with LIKE and ORDER BY:

SELECT first_name, last_name


FROM employees
WHERE first_name LIKE 'J%'
ORDER BY last_name ASC;

5. SELECT with GROUP BY and HAVING:

SELECT dept_id, COUNT(*)


FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 2;

6. SELECT with Aggregate Functions:

SELECT dept_id, AVG(salary) as avg_salary


FROM employees
GROUP BY dept_id;

7. SELECT with JOIN:

SELECT employees.first_name, employees.last_name,


departments.dept_name
FROM employees
INNER JOIN departments ON employees.dept_id = departments.dept_id;
Practical No - 4
4. Designing a Database for an Application

Designing a database involves several steps, from understanding the requirements to creating
the actual database schema. Below is a step-by-step guide to designing a database,
accompanied by real-time examples, diagrams, and practical exercises.

Step 1: Requirements Analysis

Concept: Understand the application's requirements and the data it needs to store.

Example: Designing a database for a library management system.

Activity: List the entities and their attributes that the library system will need, such as books,
members, loans, etc.

Step 2: Entity-Relationship (ER) Diagram

Concept: Create an ER diagram to visually represent the entities, attributes, and


relationships.

Example: An ER diagram for a library system might include entities like Book, Member, and
Loan, with relationships such as a Member can borrow multiple Books.

Diagram:

plaintext
[Book] ---- (borrowed by) ---- [Loan] ---- (belongs to) ---- [Member]

Activity: Draw an ER diagram for a simple e-commerce system with entities such as Product,
Customer, and Order.

Step 3: Define Tables and Relationships

Concept: Convert the ER diagram into tables with primary and foreign keys.

Example:

• Book table: book_id (PK), title, author, publisher


• Member table: member_id (PK), name, membership_date
• Loan table: loan_id (PK), book_id (FK), member_id (FK), loan_date, return_date

Activity: Define tables for the e-commerce system based on your ER diagram.

Step 4: Specify Data Types and Constraints

Concept: Choose appropriate data types for each column and specify constraints like NOT
NULL, UNIQUE, and CHECK.
Example:

• Book table: title VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL
• Member table: name VARCHAR(255) NOT NULL
• Loan table: loan_date DATE NOT NULL, return_date DATE

Activity: Define data types and constraints for your e-commerce system tables.

Step 5: Create the Database Schema

Concept: Write SQL statements to create the database schema.

Example:

CREATE TABLE Book (


book_id INT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
publisher VARCHAR(255)
);

CREATE TABLE Member (


member_id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
membership_date DATE
);

CREATE TABLE Loan (


loan_id INT PRIMARY KEY,
book_id INT,
member_id INT,
loan_date DATE NOT NULL,
return_date DATE,
FOREIGN KEY (book_id) REFERENCES Book(book_id),
FOREIGN KEY (member_id) REFERENCES Member(member_id)
);

Activity: Write SQL statements to create the tables for your e-commerce system.

Step 6: Insert Sample Data

Concept: Populate the tables with sample data for testing.

Example:

INSERT INTO Book (book_id, title, author, publisher) VALUES (1, '1984',
'George Orwell', 'Secker & Warburg');
INSERT INTO Member (member_id, name, membership_date) VALUES (1, 'John
Doe', '2024-01-01');
INSERT INTO Loan (loan_id, book_id, member_id, loan_date, return_date)
VALUES (1, 1, 1, '2024-01-15', NULL);

Activity: Insert sample data into your e-commerce system tables.

Step 7: Query the Database


Concept: Write SQL queries to retrieve data from the database.

Example:

SELECT * FROM Book WHERE author = 'George Orwell';


SELECT * FROM Loan WHERE return_date IS NULL;

Activity: Write SQL queries to retrieve data from your e-commerce system tables, such as
finding all orders by a specific customer.

Instructional Strategy

Explanation of Concepts:

• Use real-time examples like a library management system or an e-commerce platform to


explain database concepts.
• Draw diagrams such as ER diagrams to visually represent the database design.

Practical Sessions:

• Provide books and CDs or online learning materials with specified activities and exercises.
• Assign small projects or applications to reinforce theoretical concepts.

Exercises and Applications:

• Design a database for a simple application like a student management system.


• Create ER diagrams, define tables, and write SQL queries to manipulate the data.

Example Exercises

Write SQL statements to create the tables for the school management system. Insert
sample data and write queries to retrieve information such as all students enrolled in a
particular course.

SQL Statements to Create Tables for the School Management System

Creating the Tables

1. Student Table

CREATE TABLE Student (


student_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
birth_date DATE,
gender CHAR(1)
);
2. Teacher Table

CREATE TABLE Teacher (


teacher_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
hire_date DATE
);

3. Course Table

CREATE TABLE Course (


course_id INT PRIMARY KEY,
course_name VARCHAR(100) NOT NULL,
teacher_id INT,
FOREIGN KEY (teacher_id) REFERENCES Teacher(teacher_id)
);

4. Enrollment Table

CREATE TABLE Enrollment (


enrollment_id INT PRIMARY KEY,
student_id INT,
course_id INT,
enrollment_date DATE,
FOREIGN KEY (student_id) REFERENCES Student(student_id),
FOREIGN KEY (course_id) REFERENCES Course(course_id)
);
Inserting Sample Data

1. Insert Data into Student Table

INSERT INTO Student (student_id, first_name, last_name, birth_date, gender)


VALUES
(1, 'Alice', 'Johnson', '2005-04-23', 'F'),
(2, 'Bob', 'Smith', '2006-08-17', 'M'),
(3, 'Charlie', 'Brown', '2005-11-02', 'M');

2. Insert Data into Teacher Table

INSERT INTO Teacher (teacher_id, first_name, last_name, hire_date)


VALUES
(1, 'David', 'Wilson', '2010-05-12'),
(2, 'Eva', 'Williams', '2012-09-25');

3. Insert Data into Course Table

INSERT INTO Course (course_id, course_name, teacher_id)


VALUES
(1, 'Mathematics', 1),
(2, 'Science', 2),
(3, 'History', 1);

4. Insert Data into Enrollment Table

INSERT INTO Enrollment (enrollment_id, student_id, course_id,


enrollment_date)
VALUES
(1, 1, 1, '2024-01-10'),
(2, 1, 2, '2024-01-11'),
(3, 2, 1, '2024-01-12'),
(4, 3, 3, '2024-01-13');
Writing Queries to Retrieve Information

1. Query to Retrieve All Students Enrolled in a Particular Course (e.g., Mathematics)

SELECT Student.student_id, Student.first_name, Student.last_name


FROM Student
JOIN Enrollment ON Student.student_id = Enrollment.student_id
JOIN Course ON Enrollment.course_id = Course.course_id
WHERE Course.course_name = 'Mathematics';

2. Query to Retrieve All Courses a Particular Student is Enrolled In (e.g., Alice Johnson)

SELECT Course.course_id, Course.course_name


FROM Course
JOIN Enrollment ON Course.course_id = Enrollment.course_id
JOIN Student ON Enrollment.student_id = Student.student_id
WHERE Student.first_name = 'Alice' AND Student.last_name = 'Johnson';

3. Query to Retrieve the Number of Students Enrolled in Each Course

SELECT Course.course_name, COUNT(Enrollment.student_id) AS student_count


FROM Course
LEFT JOIN Enrollment ON Course.course_id = Enrollment.course_id
GROUP BY Course.course_name;

4. Query to Retrieve the Details of All Teachers and the Courses They Teach

SELECT Teacher.teacher_id, Teacher.first_name, Teacher.last_name,


Course.course_name
FROM Teacher
LEFT JOIN Course ON Teacher.teacher_id = Course.teacher_id;

Summary

These SQL statements create the necessary tables for a school management system, insert
sample data, and include queries to retrieve specific

You might also like