0% found this document useful (0 votes)
1 views

Introduction to SQL

The document provides a comprehensive introduction to SQL, detailing its purpose, key concepts, and various types of SQL statements such as DQL, DML, DDL, DCL, and TCL. It includes practical instructions on creating and managing databases and tables in MySQL, along with examples of SQL queries for data manipulation. Additionally, it explains the Entity-Relationship Model (ER Model) for database design, highlighting entities, attributes, relationships, and how to visualize them using MySQL Workbench.

Uploaded by

behanik449
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Introduction to SQL

The document provides a comprehensive introduction to SQL, detailing its purpose, key concepts, and various types of SQL statements such as DQL, DML, DDL, DCL, and TCL. It includes practical instructions on creating and managing databases and tables in MySQL, along with examples of SQL queries for data manipulation. Additionally, it explains the Entity-Relationship Model (ER Model) for database design, highlighting entities, attributes, relationships, and how to visualize them using MySQL Workbench.

Uploaded by

behanik449
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Introduction to SQL

Structured Query Language (SQL) is the standard language used to manage and manipulate
databases. It is used to interact with relational database management systems (RDBMS),
allowing users to perform various operations like querying data, updating records, managing
schema (structure of the database), and controlling access to data. SQL works by executing
commands, known as SQL statements, which can retrieve, insert, update, delete, or define data
within a database.

Key Concepts of SQL:

Relational Databases: SQL primarily operates on relational databases, where data is organized
into tables with rows and columns.

Tables: A table is a collection of related data entries and consists of columns and rows.

Rows and Columns: Rows represent records, and columns represent attributes or fields of data.

Queries: SQL is often used to query a database, meaning to request specific information from it.

SQL statements are organized into categories based on the kind of operations they perform. The
main types of SQL statements include:

Types of SQL Statements

1. Data Query Language (DQL):

This category primarily deals with querying data from the database. It allows users to retrieve
information stored in a table. The most common DQL statement is:

SELECT: Used to retrieve data from a database. It can filter, sort, and manipulate data based on
conditions.

2. Data Manipulation Language (DML):

DML is used to manipulate data stored in the tables. It involves inserting, updating, and deleting
data.

INSERT: Adds new records to a table.

UPDATE: Modifies existing records in a table.

DELETE: Removes records from a table.

3. Data Definition Language (DDL):


DDL commands are used to define or modify the structure of the database, such as creating,
altering, and dropping tables.

CREATE: Used to create new tables or databases.

ALTER: Modifies an existing table by adding, deleting, or modifying columns.

DROP: Deletes a table or database.

4. Data Control Language (DCL):

DCL statements manage access to data within the database, such as granting or revoking user
privileges.

GRANT: Gives a user access to certain database privileges.

REVOKE: Removes access rights or privileges from a user.

5. Transaction Control Language (TCL):

TCL manages the changes made by DML statements. It allows users to control transactions to
ensure the integrity of data.

COMMIT: Saves all changes made during the current transaction.

ROLLBACK: Undoes changes made during the current transaction.

SAVEPOINT: Sets a save point within a transaction, allowing partial rollback.


How To Create a Database in MYSQl ?
Creating a database in MySQL involves using the CREATE DATABASE statement, similar to
other SQL databases. Below is a step-by-step guide on how to create a MySQL database

Steps:
1. Open the MySQL Command-Line

To begin, open the terminal (on Linux/Mac) or Command Prompt (on Windows) and connect to
your MySQL server.

Replace username with your MySQL username (e.g., Tyagi or another user with database
creation privileges). You'll be prompted to enter your password.

2. Create a New Database

After connecting, create a new database using the CREATE DATABASE statement:
(In this I have already connected my SQL so I created a new database within mysql directly)

3.) To view if Databases are created or not use the command Show Databases;
How to create a table, Alter table?

The CREATE TABLE statement is used to create a new table in a database.

The following example creates a table called "Workers" that contains five columns: WID,
LastName, FirstName and Place:

(Remember Varchar is used for Strings like Ansh tyagi , Umang here these both are in string
format to enter the number or digit we use Int function after using Varchar we can add word limit
like for a column how many words could be entered)
How to Alter a table ?
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.

Steps to Alter a table:

1.) Use the command Alter


2.) Then select the table in which you want to add the column
3.) Use Add function then name the column you want to add

The above one is for adding a column in the table.

Steps to delete a column using Alter function:

1.) Use the command alter


2.) Then select the table in which you want to delete the column
3.) Use the drop function then name the column you want to delete

The above one is for deleting a column.

Steps to rename a table name using alter function:

1.) Use the command alter


2.) Then select the table name which you want to change
3.) Use the rename function then write the old name and then write the new name

The above one is for changing the name of the table directly.
How to Insert Query and Update Query in MySQL ?
Inserting and updating data in a MySQL database is done using the INSERT INTO and UPDATE
SQL statements, respectively.

1. INSERT Query in MySQL

The INSERT INTO statement is used to add new records (rows) to a table.

2. UPDATE Query in MySQL

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


How to use Delete Query?
The DELETE statement is used to delete existing records in a table.

Below we deleted a row using the Delete function

Steps:

1.) Use delete command then name the table


2.) After writing the name of the table choose a unique constraint.
3.) In this case we choose Customer_id as unique constraint and deleted the no.2
4.) Execute the script

In the above table you can see that 2 is missing but from the images above you can see that there
was a row in which the first name of the person was Robert. So here delete function deleted the
whole row and its entries and thus we can see 3 directly after 1.

The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:

This will delete all the rows in the table without impact the column

Use command Delete From Customers;


In this we used the delete command and named the table whose entries we want to delete without
deleting the table itself.
How to use Select query ?
The SELECT statement is used to select data from a database.

Select is the query, Customers is the name of the table in the above script.

How to use Where Clause?


The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition

In the above script Select is the query to choose the column , from directs to table_name and
where is also the query after that you write the condition like the name , no. etc.

In this above table the entry 5 fulfilled the condition of the resident of UAE.
How to use Order By Clause?
The ORDER BY keyword is used to sort the result-set in ascending or descending order.

By default, it uses Ascending order only but you can change that by using ASC AND DESC.

In this above figure I used both ASC and DESC command at the same time to get the output you
can use them separately as well as your needs.
How to use Drop Table and Truncate Table?
The DROP TABLE statement is used to drop an existing table in a database.

By using the above script, we deleted the whole table.

The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself.

The truncate deleted the data inside the table not the table itself that’s the difference between
Drop table and Truncate table. All the properties of the table remain safe except the data inside it.

Truncate won’t work in the online compiler it will only work in the MySQL app only.
SQL Questions
Question: Create the Students table with column ID INT PRIMARY KEY, Name VARCHAR
(50), Subject VARCHAR (50), Marks DECIMAL (5, 2).

The above script will be used to create the Students table.

Question: Alter Students table to add a column for Enrollment Date

To add the column, we will be using the alter function and adding the Enrollment date column.

We will use the Rename function in order to change the name of the table directly.

Q: Insert 5 rows into College Students table:-


(1, 'Amit', 'Maths', 85.50, '2023-01-01'),

(2, 'Sara', 'English', 90.00, '2023-02-15'),

(3, 'Raj', 'Science', 75.75, '2023-03-10'),

(4, 'Neha', 'Maths', 82.00, '2023-04-12'),

(5, 'Karan', 'English', 88.50, '2023-05-20')

In the above code we Inserted the entries using Insert query then entering the column names in
which we entered the values then executed the script.

Q: Update marks to 92.00 of the student with ID 2


Q: Delete the student with ID 3

Q: Select all records from College Students table


Q: Find the total number of students

Q: Calculate the average marks of students


Q: Get the highest marks

Q: Get the lowest marks


Q: Get the sum of total marks
ENTITY RELATIONSHIP MODEL

Entity-Relationship Model (ER Model)

The Entity-Relationship Model (ER Model) is a conceptual framework used in database design
to visually represent the structure of a database. It provides a high-level view of how different
data elements (entities) relate to one another, making it easier to organize and plan a relational
database before its implementation.

An ER Model is typically depicted using Entity-Relationship Diagrams (ER Diagrams),


which include symbols that represent entities, attributes, and relationships between the entities.

Key Concepts of the ER Model:

1. Entity: An entity represents a real-world object or concept that has a distinct existence in
the domain being modeled. Each entity is typically a table in the database.

o Entity Type: A collection of similar entities, such as students, employees, or


products. This corresponds to a table in the database.

o Entity Instance: A single occurrence of an entity type, such as a specific student


or employee. This corresponds to a row in the table.

Example: In a student management system, "Student" is an entity type.

2. Attribute: An attribute is a property or characteristic of an entity. Attributes represent


data that is stored in the entity.

o Simple Attribute: Cannot be divided into smaller parts (e.g., Age, ID).

o Composite Attribute: Can be subdivided into smaller parts (e.g., Full Name can
be divided into First Name and Last Name).

o Derived Attribute: Can be calculated from other attributes (e.g., Age can be
derived from Date of Birth).

o Key Attribute: Uniquely identifies an entity (e.g., ID in the Student entity).

Example: A "Student" entity might have attributes such as StudentID, Name, Age, and
EnrollmentDate.

3. Relationship: A relationship describes how two or more entities are associated with
each other. It defines the logical connection between entities and can be of various types:
o One-to-One (1:1): One entity is associated with exactly one instance of another
entity.

 Example: Each student has one student ID card, and each student ID card
belongs to only one student.

o One-to-Many (1): One entity is associated with multiple instances of another


entity.

 Example: A professor teaches many courses, but each course is taught by


only one professor.

o Many-to-Many (M): Multiple instances of one entity are associated with multiple
instances of another entity.

 Example: Students enroll in many courses, and courses can have many
students.

4. Cardinality: Cardinality defines the number of instances of one entity that can or must
be associated with each instance of another entity. The common types of cardinality are:

o One-to-One (1:1): One entity corresponds to exactly one other entity.

o One-to-Many (1): One entity corresponds to multiple instances of another entity.

o Many-to-Many (M): Multiple instances of one entity correspond to multiple


instances of another entity.

5. Primary Key: A primary key is an attribute (or set of attributes) that uniquely identifies
each entity in a table. Every entity instance must have a unique value for its primary key.

Example: In a Student entity, the primary key might be StudentID, as it uniquely identifies each
student.

6. Foreign Key: A foreign key is an attribute in one entity that refers to the primary key of
another entity. It is used to represent relationships between entities in a database.

Example: In a Course table, the ProfessorID could be a foreign key referring to the Professor
table's ProfessorID.

ER Diagram Symbols:

 Entities: Represented by rectangles.

 Attributes: Represented by ovals connected to the entity.

 Relationships: Represented by diamonds, connecting related entities.


 Primary Key: Underlined in the diagram.

 Foreign Key: Often represented by a line connecting two entities with cardinality
indications (1, M).

Step-by-Step Guide to Display an ER Diagram in MySQL


Workbench

Step 1: Open MySQL Workbench


 Launch MySQL Workbench.
 Connect to your MySQL database server using your connection credentials (host,
username, password).

Step 2: Reverse Engineer Your Database


If you already have your database with the tables (Customer, Product, Order,
Order_Product), follow these steps to generate an ER diagram by reverse engineering
your existing database.

1. Click on "Database" in the Top Menu:


o Select Reverse Engineer from the drop-down menu.

2. Choose Your Database Connection:


o A window will pop up. Select the connection that you use for your database (the
one where you have created the Customer, Product, Order, and Order_Product
tables).
o If you don’t have a connection yet, click on New Connection and provide the
necessary details (hostname, username, password, etc.).

3. Select the Database to Reverse Engineer:


o In the next window, you’ll see a list of databases on your MySQL server. Select
the database where your tables reside.

4. Retrieve Schema Objects:


o MySQL Workbench will now retrieve all tables and objects from the selected
database. After it finishes, click Next.

5. Select Objects for the ER Diagram:


o You’ll now see a list of tables in the database.
o Select the tables you want to include in your ER diagram (in this case, you can
select Customer, Product, Order, Order_Product).
o Click Next, and then click Execute to generate the ER diagram.

Step 3: Visualize the ER Diagram


 Once the reverse engineering is done, the ER diagram will be displayed on the canvas
within MySQL Workbench.
 You can rearrange the tables and entities to make the diagram clearer.
 The relationships (foreign keys) between tables will be automatically displayed as lines
connecting them.

Step 4: Customize the ER Diagram


 Modify Layout: Drag the tables around the canvas to arrange them in a more readable
format. MySQL Workbench will automatically position tables, but you can customize the
layout to your liking.
 Zoom and Pan: Use the zoom features to get a better view of your diagram if needed.

ER MODEL FOR

1. Customer Order System

Use this code to create the tables then we will build the relation between them using the
keys.
Entities:

1. Customer:

o Stores customer information.

o Attributes: Customer_ID (Primary Key), Name, Email, Phone, Address.

2. Product:

o Stores product details.

o Attributes: Product_ID (Primary Key), Product_Name, Price, Stock_Level.

3. Order:

o Represents a customer’s order.


o Attributes: Order_ID (Primary Key), Order_Date, Customer_ID (Foreign Key).

4. Order_Item:

o Represents the individual products included in an order.

o Attributes: Order_ID (Composite Primary Key with Product_ID, Foreign Key),


Product_ID (Foreign Key), Quantity.

2.) Sales and Inventory System

First, we created the list of tables which we need to establish the connection then Inserted the
data in each table.
Entities:

 Customer: Each customer can place multiple orders.

 Product: Each product can be included in multiple orders, and it is tracked in the
inventory.

 Supplier: Provides products that are tracked in inventory.

 Order: Represents a purchase order made by a customer.

 Order_Product: Links Order and Product to represent the many-to-many relationship


(one order can include multiple products, and one product can be in multiple orders).

 Inventory: Tracks the stock of each product and its supplier.

The above shows the role of each element and below shows the relation between each element
using a common key.
C. Student Enrollment System:
ER Diagram Overview

Entities:

 Student: Each student can enroll in multiple courses.

 Course: Each course can have multiple students and is assigned to a specific department.

 Instructor: Each instructor can teach multiple courses.

 Department: Departments manage multiple courses.

 Enrollment: Junction table to manage the many-to-many relationship between Student


and Course.

 Course_Instructor: Links each course to an instructor.

How to Use:

 First, create the tables using the SQL provided.

 Then, insert the sample data to populate the tables.


 The Enrollment table handles the relationship between students and courses.

 The Course_Instructor table manages which instructor teaches which course.

You might also like