0% found this document useful (0 votes)
13 views13 pages

SQL Database Setup and Querying Guide

The document provides a comprehensive guide on Structured Query Language (SQL), covering database setup, table creation, data insertion, querying, filtering, and data analysis. It explains key SQL commands such as CREATE, SELECT, UPDATE, and DELETE, along with various operators and functions for data manipulation and retrieval. Additionally, it discusses advanced topics like INNER JOIN for connecting tables and aggregate functions for summarizing data.

Uploaded by

imaanahmad95
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)
13 views13 pages

SQL Database Setup and Querying Guide

The document provides a comprehensive guide on Structured Query Language (SQL), covering database setup, table creation, data insertion, querying, filtering, and data analysis. It explains key SQL commands such as CREATE, SELECT, UPDATE, and DELETE, along with various operators and functions for data manipulation and retrieval. Additionally, it discusses advanced topics like INNER JOIN for connecting tables and aggregate functions for summarizing data.

Uploaded by

imaanahmad95
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

Structured Query Language (SQL)

Part 1: Setting Up and Managing the Database


1. Creating the Container

Before we can work with data, we need a database and tables to hold it.

• CREATE DATABASE: This statement creates a new container for your data.
CREATE DATABASE CompanyDB;

• USE: Tells the system which database we want to operate inside.


USE CompanyDB;

2. Creating Tables (The Schema)

The CREATE TABLE statement defines the structure of your data. We need to define
columns and data types (like int for numbers or varchar for text).

Constraints:

• PRIMARY KEY: Uniquely identifies each record (e.g., no two employees can have the
same ID). It cannot be NULL.

• UNIQUE: Ensures all values in a specific column are different.

Referring to the csv file:

Table 1: Departments (from [Link])


CREATE TABLE Departments (
DepartmentID int NOT NULL,
DepartmentName varchar(255),
PRIMARY KEY (DepartmentID)
);
We made DepartmentID the Primary Key because it uniquely identifies the department
(e.g., 101 is Human Resources).

Table 2: Employees (from [Link])


CREATE TABLE Employees (
EmployeeID int NOT NULL,
FirstName varchar(255),
LastName varchar(255),
DepartmentID int,
Salary int,
JobTitle varchar(255),
PRIMARY KEY (EmployeeID)
);
EmployeeID is the Primary Key here. We use int for Salary and varchar for names.

3. Modifying Structure (Maintenance)

Sometimes the design needs to change after creation.

• ALTER TABLE: Used to add or delete columns.

Example:
ALTER TABLE Employees ADD Email varchar(255);

• DROP TABLE: Deletes an entire table and all its data permanently.

Example: DROP TABLE Employees;

4. Inserting Data

Now we use INSERT INTO to put your CSV data into the tables.

• Syntax: INSERT INTO table_name (columns) VALUES (values);

Insert the first row from [Link] and [Link]:


-- Inserting "Human Resources" department
INSERT INTO Departments (DepartmentID, DepartmentName)
VALUES (101, 'Human Resources');

-- Inserting employee "John Smith"


INSERT INTO Employees (EmployeeID, FirstName, LastName,
DepartmentID, Salary, JobTitle)
VALUES (1, 'John', 'Smith', 103, 75000, 'Developer');

Part 2: Querying and Filtering Data


1. The SELECT Statement

The SELECT statement is the most common command in SQL. It tells the database which
columns you want to view.

• Syntax: SELECT column1, column2, ... FROM table_name;


• Select All: To select all columns, use the asterisk * symbol.

For Example: You want to see a list of all employees and their salaries.
SELECT FirstName, LastName, Salary
FROM Employees;

Explanation: This query pulls only the first name, last name, and salary for every entry in the
Employees table.

Practice: How would you write a query to see everything (all columns) in the Departments
table?

2. The WHERE Clause

The WHERE clause is used to filter records. It extracts only those records that fulfill a
specified condition.

• Syntax: SELECT column1, ... FROM table_name WHERE condition;

Application to Data: Let's say we only want to find employees who work in the "IT"
department. Looking at your [Link], we know the ID for IT is 103.
SELECT *
FROM Employees
WHERE DepartmentID = 103;

Explanation: This checks every row. If DepartmentID is 103, it includes that row in the
result.

3. Operators

To build conditions in a WHERE clause, you need operators. Here are the standard ones
mentioned in your slides:

• Comparison Operators:

o = Equal

o > Greater than

o < Less than

o >= Greater than or equal

o <= Less than or equal


o <> or != Not equal

• Logical Operators:

o AND: Displays a record if all conditions are TRUE.

o OR: Displays a record if any of the conditions are TRUE.

o NOT: Displays a record if the condition is not TRUE.

Application to Data: Let's find highly paid Sales Representatives. We want employees with
the JobTitle 'Sales Rep' AND a Salary greater than 50000.
SELECT *
FROM Employees
WHERE JobTitle = 'Sales Rep' AND Salary > 50000;

Analysis of the CSV Data: Looking at [Link]:

• Sarah Connor: Sales Rep, 55000

• Mike Ross: Sales Rep, 52000

Both Sarah and Mike would appear in the results because they both match both conditions.
Practice: Write a query to find all employees who are NOT in Department 101.

Part 3: Advanced Filtering


1. The LIKE Operator (Pattern Matching)

The LIKE operator is used when you don't know the exact value you are looking for, or you
want to find a pattern (like all names starting with "S").

To use it, we use Wildcards:

• % (Percent Sign): Represents zero, one, or multiple characters.

• _ (Underscore): Represents exactly one single character.

Syntax:
SELECT columns FROM table_name WHERE column LIKE pattern;
Application to Data ([Link]): Let's find all employees who have "Developer" in their
job title (this should catch both "Developer" and "Senior Developer").
SELECT *
FROM Employees
WHERE JobTitle LIKE '%Developer%';

• How it works: The % at the start means "anything can be before this," and the % at
the end means "anything can be after this."

• Result: It would return John Smith (Developer) and David Kim (Senior Developer).

2. The IN Operator (Multiple Options)

The IN operator is a shorthand for multiple OR conditions. It allows you to specify a list of
values you want to include.

Syntax:
SELECT columns FROM table_name WHERE column IN (value1, value2,
...);
Application to Data ([Link]): Suppose you want to find employees in the Sales
(102) OR Marketing (104) departments.
SELECT *
FROM Employees
WHERE DepartmentID IN (102, 104);
• How it works: The database checks if the DepartmentID matches any value inside
the parentheses.

• Result: It finds Sarah Connor (102), Mike Ross (102), and Rachel Green (104).

3. The BETWEEN Operator (Ranges)

The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.

• Note: The BETWEEN operator is inclusive: begin and end values are included.

Syntax:
SELECT columns FROM table_name WHERE column BETWEEN value1 AND
value2;
Application to Data ([Link]): Let's find employees with a salary between 50,000
and 60,000.
SELECT *
FROM Employees
WHERE Salary BETWEEN 50000 AND 60000;

• How it works: It grabs any row where the Salary is greater than or equal to 50,000
AND less than or equal to 60,000.

• Result: Sarah Connor (55,000), Mike Ross (52,000), and Rachel Green (60,000).

Practice: Using the LIKE operator and your [Link] data, how would you write a query
to find all employees whose First Name starts with the letter 'S'?

Part 4: Analyzing Data (Aggregate Functions &


Grouping)
1. Aggregate Functions

These functions perform a calculation on a set of values and return a single value.

1. COUNT() This function returns the number of rows that match a specified criterion.

• Syntax: SELECT COUNT(column_name) FROM table_name;

• Application: How many employees do we have in total?


SELECT COUNT(EmployeeID) AS Total_Employees
FROM Employees;

o Result: 6 (Since there are 6 rows in your [Link]).

o Note: AS allows us to rename the result column to "Total_Employees" for


better readability.

2. SUM() This returns the total sum of a numeric column.

• Syntax: SELECT SUM(column_name) FROM table_name;

• Application: What is the total cost of all salaries?

SELECT SUM(Salary) AS Total_Payroll


FROM Employees;

o Result: 367000 (75k+55k+52k+60k+80k+45k).

3. AVG() This returns the average value of a numeric column.

• Syntax: SELECT AVG(column_name) FROM table_name;

• Application: What is the average salary at the company?

SELECT AVG(Salary) AS Average_Salary


FROM Employees;

o Result: 61166.66

4. MIN() and MAX() These return the smallest and largest value of the selected column,
respectively.

• Application: Who gets paid the least and the most?

SELECT MIN(Salary) AS Lowest_Salary, MAX(Salary) AS


Highest_Salary
FROM Employees;
o Result: Lowest: 45000, Highest: 80000.

2. The GROUP BY Statement

The GROUP BY statement is one of the most useful tools in SQL. It groups rows that have
the same values into summary rows. It is almost always used with the aggregate functions
above (COUNT, MAX, SUM, etc.).

• Syntax:

SELECT column_name, COUNT(*)


FROM table_name
GROUP BY column_name;

Application to Data: Suppose we want to know how many employees are in each
department.
SELECT DepartmentID, COUNT(EmployeeID) as Employee_Count
FROM Employees
GROUP BY DepartmentID;

How it works on [Link]:

1. The database looks at the DepartmentID column.

2. It groups all 102s together, all 103s together, etc.

3. It counts the employees in each group.

Result:

• 101: 1 (Emily)

• 102: 2 (Sarah, Mike)

• 103: 2 (John, David)

• 104: 1 (Rachel)

Practice: Using GROUP BY and AVG, how would you write a query to find the average
salary for each Job Title?
Part 5: Sorting and Connecting Data
1. The ORDER BY Keyword

Data in a database isn't stored in any specific order. If you want to see it organized (e.g.,
highest salary first), you must use ORDER BY.

• Default: Sorts in Ascending order (A-Z, 1-10).

• DESC: Sorts in Descending order (Z-A, 10-1).

Syntax:
SELECT columns FROM table_name ORDER BY column_name ASC|DESC;

Application to Data ([Link]): Let's list employees based on their Salary, from
highest to lowest.
SELECT FirstName, LastName, Salary
FROM Employees
ORDER BY Salary DESC;

Result Analysis: The database looks at the Salary column and reorders the output:

1. David Kim: 80,000

2. John Smith: 75,000

3. Rachel Green: 60,000

4. Sarah Connor: 55,000

5. Mike Ross: 52,000

6. Emily Blunt: 45,000

2. The INNER JOIN

This is one of the most critical concepts in SQL. Currently, your Employees table only has
DepartmentID (e.g., 101, 102). This isn't very readable for a human who wants to know the
Department Name. The DepartmentName lives in a separate table: Departments.

To see the Employee Name and Department Name in the same row, we "Join" the tables
using the column they share: DepartmentID.
• Concept: The INNER JOIN selects records that have matching values in both tables.

Syntax:
SELECT [Link], [Link]
FROM table1
INNER JOIN table2 ON table1.common_column =
table2.common_column;

Application to Data: Let's create a report showing every employee's full name and their
actual department name.
SELECT [Link], [Link],
[Link]
FROM Employees
INNER JOIN Departments ON [Link] =
[Link];

Details of the Function:

1. FROM Employees: SQL starts with the first row in Employees. Let's take Sarah
Connor (Row 2).

2. Look at the Link: Sarah has DepartmentID = 102.

3. INNER JOIN Departments: SQL hops over to the Departments table and looks for
102 in the DepartmentID column.

4. Match Found: It finds 102 corresponds to "Sales".

5. Result: It combines the data into one row: Sarah, Connor, Sales.

Final Output:

• John Smith -> IT

• Sarah Connor -> Sales

• Mike Ross -> Sales

• Rachel Green -> Marketing

• David Kim -> IT

• Emily Blunt -> Human Resources


Part 6: Managing Records (Update & Delete)
1. The UPDATE Statement

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

• Warning: If you omit the WHERE clause, ALL records in the table will be updated.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Application to Data ([Link]): Let’s say John Smith (EmployeeID 1) did a great job
and got a raise. We need to change his salary from 75000 to 78000.
UPDATE Employees
SET Salary = 78000
WHERE EmployeeID = 1;

Details:

1. UPDATE Employees: Tells the database which table to open.

2. WHERE EmployeeID = 1: It scans the table to find the specific row where the ID is 1
(John Smith).

3. SET Salary = 78000: It erases the old value (75000) in the Salary column for that
specific row and writes in the new value (78000).

2. The DELETE Statement

The DELETE statement is used to delete existing records in a table.

• Warning: If you omit the WHERE clause, ALL records in the table will be deleted.

Syntax:
DELETE FROM table_name
WHERE condition;

Application to Data ([Link]): Suppose Emily Blunt (EmployeeID 6) decides to leave


the company. We need to remove her record.
DELETE FROM Employees
WHERE EmployeeID = 6;

Details:

1. DELETE FROM Employees: Targets the Employees table.

2. WHERE EmployeeID = 6: Locates the row belonging to Emily Blunt.

3. Action: That entire row is removed from the storage.

3. DROP vs. DELETE

It is important to understand the difference between clearing data and destroying the
structure.

• DELETE: Removes specific rows of data. The table structure (columns like Name,
Salary) remains, and you can insert new data later.

• DROP TABLE: Deletes the entire table, including its structure and all data inside it. It
ceases to exist.
DROP TABLE Employees;

• DROP DATABASE: The most destructive command. It deletes the entire database
container and everything inside it.

Summary:

1. Creation: CREATE DATABASE, CREATE TABLE (setup).

2. Input: INSERT INTO (adding your CSV data).

3. Basic Queries: SELECT, WHERE (finding specific employees).

4. Filters: AND, OR, LIKE, IN, BETWEEN (complex searches).

5. Math: COUNT, SUM, AVG, MIN, MAX (payroll analysis).

6. Reporting: GROUP BY (department summaries), ORDER BY (ranking salaries).

7. Connections: INNER JOIN (linking Employees to Departments).


8. Maintenance: UPDATE, DELETE, DROP (managing changes).

You might also like