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

XAMPP SQL Database Management Guide

Uploaded by

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

XAMPP SQL Database Management Guide

Uploaded by

mikesimba59
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

XAMPP SQL

Open Xampp
Open Web Browser
Connect to localhost OR Click Apache Admin
Database location is c:\xampp\mysql\data
Connect to xamp dbase OOP
SQL Statements are terminated with a semi colon (;)
DDL STATEMENTS

Create a database (CREATE DATABASE)


Create a table definition (CREATE TABLE), including the creation of attributes with appropriate data
types:

change a table definition (ALTER TABLE)add a primary key to a table (PRIMARY KEY (field))
add a foreign key to a table (FOREIGN KEY (field) REFERENCES Table (Field))
ALTER TABLE (Alter works with Add, Drop, Modify Table or TableColumn)

DML STATEMENTS (At most 2 tables)

Queries including SELECT... FROM, WHERE, ORDER BY, GROUP BY, INNER JOIN, SUM, COUNT, AVG
Data maintenance including. INSERT INTO, DELETE FROM, UPDATE

DDL STATEMENTS
CREATE (Creates table or Database)
Syntax
Create Table TableName(

<table definition - FieldName Datatype (FieldSizes)


validation>,

Primary Key (FieldName)

);
CREATE TABLE buddies(

B_number INT,

email TEXT( 15 ) Not Null , use Varchar instead of Text

PRIMARY KEY ( B_number )

);

CREATE TABLE details(

name varchar(15), CREATE TABLE Student( StudentID text(20), FirstName var


CHAR(20), SecondName varCHAR(20), DateOfBirth DATE, Cla
gender boolean, ssID varCHAR(20), PRIMARY KEY (StudentID(20)));

B_number INT, CREATE TABLE Class( ClassID CHARACTER, Location CHARACT


ER, LicenceNumber CHARACTER);
DOB date,

PRIMARY KEY (name(15)));


ALTER TABLE (Alter works with Add, Drop, Modify Table or TableColumn)
Foreign Key Syntax

FOREIGN KEY tableName (foreignKeyField) REFERENCES blocked (foreignKeyField)

E.G - ALTER TABLE contact ADD FOREIGN KEY (Name) REFERENCES blocked (Name)

ALTER TABLE tableName ADD fieldName DATATYPE(SIZE)


ALTER TABLE `addresses` ADD `town` VARCHAR( 10 ) NOT NULL ;

alter table `blocked` add (Name text(10));

ALTER TABLE tableName DROP fieldName;


ALTER TABLE addresses DROP Name;

ALTER TABLE tableName DROP fieldName;


ALTER TABLE buddies DROP TABLE buddies

ALTER TABLE tableName MODIFY fieldName newDATATYPE(SIZE)


ALTER TABLE `buddies` CHANGE `B_number` `B_number` INT( 11 ) NOT NULL AUTO_INCREMENT

Data manipulation language (DML)


Part of SQL is a data manipulation language (DML). The database designer can use it to write SQL scripts that:

 insert, amend and delete data records

 retrieve data from database tables based on search criteria specified by the user.

DML STATEMENTS

INSERT

INSERT INTO tableName(FieldName1,FieldName2,…)

VALUES (‘value1’, ‘value2’, …)

OR IN SHORT

INSERT INTO tableName

VALUES (‘value1’, ‘value2’, …)


INSERT INTO buddies( B_number, email )

VALUES ('02', 'g@[Link]');

INSERT INTO CONTACT

VALUES ('TATTY', '0772737234', 'M'), ('VICKY','0716576330','F');

INSERT INTO friends database into buddies table

INSERT INTO `friends`.`buddies` (

`B_number` ,`email`)

VALUES (NULL , 'f@[Link]');

SELECT - Most widely used SQL statement to view and query the database

SELECT<fieldList>
FROM<tableList>

WHERE<searchCondition>

FieldList are the fields you want to appear in the search-results

Tablelist - list of tables to be used in the search

Search-condition - is the search criteria

E.g1 SELECT * FROM contact


E.g 2

SELECT *
FROM `contact`
WHERE Name = 'Joe'

SELECT *
FROM `buddies`
WHERE B_number LIKE '2'

SELECT *
FROM `buddies`
WHERE email LIKE 'f%'
OR B_number =3

SELECT * FROM `buddies`,`contact` where Gender = 'F' and B_Number =2

DELETE FROM `contact` WHERE Name = 'Tim'


Example

UPDATE contact

SET Name = 'Gina'

WHERE Name = 'Grace'


UPDATE `friends`.`contact` SET `Phone` = '' WHERE CONVERT( `contact`.`Name` USING utf8 ) = 'Tim' LIMIT
1

SELECT statements using JOIN

A join is a table operation that uses related columns to combine rows from two input tables to form one output (result) table.
Often the most interesting database information is stored across multiple tables and requires joining to retrieve it. In SQL,
joins are performed by using a JOIN clause (combined with an ON clause) in a SELECT statement.
SELECT * FROM `ward` JOIN`patient` ON [Link] = [Link] WHERE
[Link] = 'Ward 1'

More than two tables may be joined in a single select statement, using multiple JOIN clauses in the SELECT statement. A
select statement joining three tables would take the following form:

SELECT [columns] FROM [table1] JOIN [table2] ON [join_condition_A] JOIN [table3] ON [join_condition_B];
SQL EXERCISE

1. Create the database HOSPITAL.

2. Create the table PATIENT.

3. Create the table WARD.

4. Create the one-to-many relationship.

CREATE DATABASE 'HOSPITAL'


CREATE TABLE PATIENT ( PatientIDNumber INT NOT NULL , PatientName VARCHAR(30) NOT NUL
L , PatientAddress VARCHAR(50) NOT NULL , NextOfKin VARCHAR(30) NOT NULL , DateOfBirt
h DATE NOT NULL, WardName VARCHAR(20) NOT NULL, PRIMARY KEY(PatientIDNumber))

ALTER TABLE PATIENT ADD PRIMARY KEY(PatientIDNumber)

CREATE TABLE WARD ( WardName VARCHAR(20) NOT NULL , NoOfBeds INT NOT NULL , NurseInCh
arge VARCHAR(30) NOT NULL )

ALTER TABLE ward ADD PRIMARY KEY(WardName);

alter table patient add FOREIGN key (WardName) REFERENCES ward(WardName)

INSERT INTO WARD (WardName, NoOfBeds, NurseInCharge)

VALUES ('Ward 1',10, 'Sellick') ;

INSERT INTO WARD (WardName, NoOfBeds, NurseInCharge)

VALUES ('Ward 2', 20, 'Jones') ;

INSERT INTO WARD (WardName, NoOfBeds, NurseInCharge)

VALUES ('Ward 3',15, 'Papandreou') ;

INSERT INTO WARD (WardName, NoOfBeds, NurseInCharge)

VALUES('Ward 4',11, 'Mellas') ;

INSERT INTO WARD (WardName, NoOfBeds, NurseInCharge)

VALUES ('Ward 5',32, 'Comodi') ;

INSERT INTO WARD (WardName, NoOfBeds, NurseInCharge)

VALUES ('Ward 6',11, 'Mignini') ;

Populate the Patient table with any 4 records of your choice


INSERT INTO `patient` (`PatientIDNumber`, `PatientName`, `PatientAddress`, `NextOfKin
`, `DateOfBirth`, `WardName`) VALUES ('1200000063', 'Gore Nox', '21
Biedale', 'Fox', '2018-06-23', 'Ward 1');

INSERT INTO `patient` (`PatientIDNumber`, `PatientName`, `PatientAddress`, `NextOfKin


`, `DateOfBirth`, `WardName`) VALUES ('120002378', 'Chips', '300
Springs', 'Nox', '2011-01-13', 'Ward 2'),('111202378', 'Cain Alice', '30
Southlea', 'Rudo', '2005-04-25', 'Ward 3')

Run queries to

Show all wards whose Nurse in charge’s name starts M or ends with s
SELECT `WardName`, `NoOfBeds`, `NurseInCharge` FROM `WARD` WHERE `NurseInCharge` LIKE
'M%' OR `NurseInCharge` LIKE '%s'

Display a list of patient names, Date of birth and WardName for patients admitted in Ward 1 sorted by name in descending
order
SELECT `PatientName`, `DateOfBirth`, `WardName` FROM `patient` WHERE `WardName`='Ward
1' ORDER BY PatientName DESC

DML statements to return the WardName and number of patients in each ward
SELECT WardName, count(`PatientIDNumber`) FROM `patient` GROUP BY `WardName`

DML statements to return average number of beds


SELECT AVG(`NoOfBeds`) FROM `ward` WHERE 1

Display a list of patient names, Date of birth and WardName for patients admitted in Ward 1 or 2 and whose whose
Nurse in charge’s name starts M or J
SELECT `PatientName`,`DateOfBirth`, [Link], `NurseInCharge` FROM `ward` JOI
N`patient` ON [Link] = [Link] WHERE [Link] = 'Ward 1'

SELECT `PatientName`,`DateOfBirth`, [Link], `NurseInCharge` FROM `ward`,`pa


tient` where [Link] = [Link] and [Link] = 'Ward 1';

SELECT PatientName, DateOfBirth, [Link], Nurseincharge FROM `ward` JOIN`patien


t` ON [Link] = [Link] WHERE [Link] = 'Ward
1' OR [Link] = 'Ward 2' AND Nurseincharge LIKE 'M
%' OR Nurseincharge LIKE 'J%'

Run the following Query

SELECT WardName, NurseInCharge

FROM WARD

WHERE NoOfBeds >= 10;

1. Create the Database Cinema with the following tables and state Primary Keys

2. Alter table by adding Foreign keys

3. Populate all the 4 tables


4. Run the following queries

i. All the records in all four tables


ii. All cinemas managed by Allen or Jones

iii. All movie titles whose takings are between 200 and 300

iv. All cinemas located in Croyden

Common questions

Powered by AI

Foreign key constraints support database normalization by enforcing referential integrity, which prevents data anomalies and redundancy by ensuring that references between tables are valid and consistent. They enable implementing normal forms by precisely defining relationships within a database, facilitating structured storage and retrieval of data. However, foreign key constraints can limit flexibility, as strict relational dependencies may complicate updates, deletes, and require comprehensive planning to avoid cascading deletions or updates that inadvertently affect large data sets, thus requiring careful design to balance integrity with operational requirements .

Optimizing SQL statements for performance involves several techniques. Indexing columns that are frequently used in WHERE clauses or JOIN conditions can drastically reduce query execution time. Query optimization might include rewriting queries to avoid unnecessary joins or subqueries. Utilizing appropriate indexing, avoiding full table scans, and preferring JOINs over subqueries where applicable can yield performance gains. Caching frequently accessed queries and using tools for query analysis such as EXPLAIN can help identify bottlenecks. Maintaining updated statistics on data distribution allows the query optimizer to make better execution plan decisions .

Using proper syntax in SQL is crucial for ensuring the correct execution of queries and data integrity. SQL statements, like those for Data Definition Language (DDL) and Data Manipulation Language (DML), must be correctly structured to perform tasks such as creating databases, tables, and relationships (e.g., primary and foreign keys), and for querying data. Incorrect syntax can lead to errors, unexpected behaviors, or inefficient performance. Key constructs such as JOIN clauses in SELECT statements enable combining data across multiple tables, which is essential for retrieving comprehensive information stored in a relational database .

The ALTER TABLE statement in SQL is a versatile command used to modify an existing table's schema. It allows for adding, deleting, or modifying columns. For instance, a new column can be introduced using ALTER TABLE with ADD syntax, and unnecessary columns can be removed using DROP. Modifications like changing a column's data type or constraints can be done with the MODIFY or CHANGE options. Using ALTER TABLE to add foreign keys ensures referential integrity by establishing relationships between tables. These operations help keep the database schema up to date with changing requirements .

JOIN clauses in SQL enhance data retrieval by allowing the combination of rows from two or more tables based on related columns between them. This capability is essential for assembling comprehensive datasets from normalized tables in relational databases. For instance, to fetch patient information along with ward details, a JOIN operation on the patient and ward tables using a common attribute like WardName is employed. This method allows for efficient queries that can pull together disparate but related data without redundancy .

Maintaining data integrity during table alterations involves several strategies. Firstly, employing transactions can provide a rollback mechanism if an alteration fails. Secondly, the use of constraints (like primary and foreign keys) helps preserve referential integrity by enforcing proper linkage and data consistency across tables. Additionally, validating data types and sizes can prevent invalid data entries. While altering tables to add or modify columns, it is crucial to consider existing data dependencies and effects on application logic or reporting that utilize these tables .

Primary keys and foreign keys are fundamental to establishing relationships in relational databases. A primary key uniquely identifies each record in a table, ensuring data integrity within that table. A foreign key, on the other hand, is a field (or collection of fields) in one table that uniquely identifies a row of another table. This relationship facilitates linking tables together, enabling JOIN operations for composite queries. The foreign key constraint enforces referential integrity by ensuring that a foreign key value in one table matches a primary key in another, thus preventing orphaned records .

INT and VARCHAR data types serve different purposes in SQL databases and impact design through storage efficiency and indexing. INT is used for storing numerical values without decimal points, optimizing storage and indexing, contributing to faster access and comparison operations. VARCHAR is suitable for variable-length string storage, providing flexibility but potentially requiring more storage space and posing challenges in indexing efficiency. The choice between these types impacts database normalization levels, indexing strategies, and performance metrics in query execution .

The GROUP BY clause is used in SQL to organize identical data into groups. It is often used in conjunction with aggregate functions like COUNT, AVG, SUM, etc., to perform calculations on each group. Scenarios involving statistical reports, such as finding the number of patients per ward or calculating average values, use GROUP BY to aggregate data meaningful to the analysis. It serves to simplify the processing of datasets and aids in generating grouped outputs from raw data scattered across rows .

Inserting multiple records simultaneously might lead to several challenges, such as violating uniqueness constraints, encountering locked resources, or duplicated efforts in maintaining data integrity. Batch inserts can risk partial updates if a single record fails; using transactions mitigates this by ensuring atomicity—either all records succeed or none do. Proper error handling entails detecting and resolving violations before executing bulk inserts. Additionally, optimizing bulk inserts by minimizing triggers, careful indexing, and ensuring the availability of resources can prevent performance pitfalls .

You might also like