2. SQL and DATABASE Page 2 of 11
A databaseis anorganized collectionofdatathatis storedand managedon a computer system.
It is astructured wayto store,manage, andretrievedatafor various purposes, such as running
applications, generating reports,or analyzingdata.
Commondatabase management systemsinclude MySQL,Oracle, Microsoft SQLServer, and
PostgreSQL.
3. SQL and DATABASE Page 3 of 11
What is Table?
Inthe contextofdatabases, atable isa collection ofdataorganized into rowsand columns.Each
tablerepresents a setofrelateddata, andeach row representsa singlerecord orinstance ofthat
data.Eachcolumnrepresentsa fieldor attribute ofthe data.
Tables areusedtostoreand managedatain a structured and organizedway,and they provide a
way toefficientlyretrieve and manipulatedata using SQL queries. Tablescan be created,
modified,and deleted usingSQL commands.
Tables can berelatedtoeachother usingforeign keys, which are usedtoestablish relationships
betweentables.Forexample, a customer table might have aforeign keythat refers to an order
table, indicating thateachcustomer can have multiple orders.
Tables area fundamental componentof relational databases, andtheyprovideaflexible and
scalable waytomanage largeamountsofdata.
Databasesareimportant forseveral reasons, including:
• Efficientdatamanagement: Databasesprovide a structured and organizedwayto store
and manage large amounts of data. With awell-designed database, it is much easierand
more efficientto retrieve, update, anddeletedatathan with other data storage methods.
• Data consistency:Databasesensure dataconsistency by enforcing rules and constraints
that mustbefollowed whendata isadded,updated,or deleted. Thishelpstoprevent
errors and inconsistencies thatcan arise when datais stored in multiplelocations.
• Scalability: Databases aredesigned to be scalable, meaning thatthey can handle large
amounts ofdata andmultiple users withoutperformance degradation. Thisis important
for applications that needto handle alarge numberof usersor a high volume of data.
• Data security: Databasesprovide securityfeatures such as user authentication,access
control, andencryptiontoprotectdatafrom unauthorized access andensure data
privacy.
• Data analysis: Databasesprovide a rich setoftoolsfor analyzing and reportingon data,
allowing userstoextract insights and makeinformed decisions based onthedatathey
have collected.
4. SQL and DATABASE Page 4 of 11
Overall,databasesare a critical componentof modernsoftwaresystems andare essentialfor
managing data in asecure, efficient, andscalableway.
5. SQL and DATABASE Page 5 of 11
Entity Diagram
Anentity diagramis atype ofdata modelthat is used torepresentthe entitiesand relationships
betweenthem in adatabase. Entitiesarethings thatare represented inthedatabase,such as
people,places,or things. Relationships arethe connections betweenentities.
Entity diagrams aretypically representedusing a graphical notation that includes symbolsfor
entities, relationships, andattributes. Entities are representedby rectangles, relationships are
represented bylines,and attributes arerepresentedby ovals.
For example,the followingentity diagram represents a databaseof students and courses:
[Student]
- id
- name
- email
- courses
[Course]
6. SQL and DATABASE Page 6 of 11
- id
- name
- instructor
- students
The entitydiagramshowsthatthe Studententity has attributesforthe student'sid, name,and
email address.The Studententity also has arelationship withthe Course entity, which is
represented bytheline betweenthetwoentities. The relationship between theStudent and
Course entities isa one-to-many relationship, which means thatone studentcan take many
courses, buteachcourse can only betakenby onestudent.
Entity diagrams are ausefultool for designing and understanding databases.They can beused
to visualizethedatathat isstored in adatabaseandto identifythe relationshipsbetween
differentpiecesofdata.
Here are someotherexamplesof entitydiagrams:
• A customer entitydiagram might showthe attributes ofa customer,such as their name,
address,and phonenumber. It mightalsoshow therelationships betweenthe customer
entityand other entities, suchas theordersentityorthe product entity.
• A product entitydiagram mightshow theattributesof aproduct,such as itsname,
description, andprice. It mightalsoshowthe relationships between theproduct entity
and otherentities,suchas the category entityorthesupplier entity.
Entity diagrams are avaluabletoolfordatabasedesigners and developers. They can help to
ensure thatthe database isdesigned in a way that islogical and easy to understand.They can
also helpto identify potentialproblemswiththedatabase, such as missing data or incorrect
relationships.
7. SQL and DATABASE Page 7 of 11
Main typesofrelationsina database:
• One-to-one: Aone-to-one relationshipis a relationship betweentwotables in which
eachrow in thefirsttable is relatedtoexactlyone row in the second table,and vice
versa. For example, apersoncan have onlyonepassport,and apassport can onlybelong
to oneperson.
• One-to-many: Aone-to-many relationshipis arelationship betweentwotables in which
eachrow in thefirsttable can be relatedtozero,one, or many rows inthe secondtable,
but eachrow inthe second table can onlyberelatedtoone rowin thefirst table. For
example, acustomer can have manyorders,buteach order can onlybe placedby one
customer.
• Many-to-many: A many-to-many relationship isa relationshipbetweentwotables in
whicheachrow in the firsttable can be relatedto zero, one,or many rows inthe second
table, and vice versa.For example,a student can take many courses, anda course can be
takenby manystudents.
Here are someexamplesof eachtypeof relationship:
• One-to-one:
o A personand their passport
o A bookand its ISBN number
• One-to-many:
o A customer andtheirorders
o A product and its reviews
• Many-to-many:
o A student andtheir courses
8. SQL and DATABASE Page 8 of 11
SQL (Structured QueryLanguage)
SQL(StructuredQuery Language)isa programminglanguage usedto manageand manipulate
relationaldatabases. Itis used to perform various operationson databases, such as creating,
modifying, anddeleting tables, inserting, updating, and deleting datafromtables, andretrieving
datafromtables basedonvarious conditions.
SQLis used bydatabaseadministrators, software developers,and data analyststomanage large
amounts ofdata efficiently andeffectively. It isa powerful toolfor managingdatabases,and its
syntax is easy to learnand understand.
Some commonSQL commandsinclude SELECT, INSERT, UPDATE, DELETE,CREATE,ALTER, and
DROP. SQLis used witha variety of relational database management systems, including
MySQL,Oracle,MicrosoftSQL Server, andPostgreSQL.
A primary keyis acolumnor a setofcolumns in a tablethat uniquelyidentifies each rowin the
table. Hereis an example:
Consider atablecalled"Employees"that containsinformation aboutemployeesin a company.
One waytodesignthistableisto include thefollowing columns:
• EmployeeID:A uniqueidentifierforeach employee
• FirstName:The employee'sfirst name
• LastName: The employee's last name
• Email: The employee's email address
• Phone: Theemployee'sphone number
• HireDate: Thedatethe employee was hired
Inthis case,the primarykey for the"Employees"table wouldbethe "EmployeeID" column. This
columncontains a unique identifier for each employee, which means that notwoemployees
can have the same EmployeeID.The primarykey ensures thateach row in thetable can be
uniquely identified andis usedas areference inother tables when creating relationships.For
9. SQL and DATABASE Page 9 of 11
example, ifthere wasa secondtablethat contained information abouteach employee's
department,the "EmployeeID" columnin the"Employees"table wouldbe usedas aforeign key
in the department tabletolinkthetwotablestogether.
EmployeeID FirstName LastName Department
1 John Smith Sales
10. SQL and DATABASE Page 10 of 11
DELETE FROM Employees
WHERE HireDate < '2020-01-01';
EmployeeID FirstName LastName Department
3 Lisa Jones Marketing
4 David Lee Sales
11. SQL and DATABASE Page 11 of 11
Here are some common SQL commands examples:
1. SELECT: Used to retrieve data from one or more tables in a database. Syntax:
sqlCopy code
SELECT column1, column2, ... FROM table_name WHERE condition;
2. INSERT: Used to insert data into a table. Syntax:
sqlCopy code
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
3. UPDATE: Used to modify existing data in a table. Syntax:
sqlCopy code
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
4. DELETE: Used to delete data from a table. Syntax:
sqlCopy code
DELETE FROM table_name WHERE condition;
5. CREATE: Used to create a new table in a database. Syntax:
sqlCopy code
CREATE TABLE table_name (column1 datatype, column2 datatype, ...);
6. ALTER: Used to modify the structure of an existing table. Syntax:
sqlCopy code
ALTER TABLE table_name ADD column_name datatype;
7. DROP: Used to delete an entire table from a database. Syntax:
sqlCopy code
DROP TABLE table_name;