0% found this document useful (0 votes)
3 views64 pages

Chapter+2+ +Database+Query+Languages

The document provides a comprehensive overview of SQL, detailing its structure, including Data Definition Language (DDL) and Data Manipulation Language (DML) statements. It explains how to create, alter, and delete tables, as well as how to perform queries to retrieve, insert, update, and delete data. Additionally, it covers aggregate functions, performance optimization strategies, and the use of XML for data transport.

Uploaded by

Jade Malit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views64 pages

Chapter+2+ +Database+Query+Languages

The document provides a comprehensive overview of SQL, detailing its structure, including Data Definition Language (DDL) and Data Manipulation Language (DML) statements. It explains how to create, alter, and delete tables, as well as how to perform queries to retrieve, insert, update, and delete data. Additionally, it covers aggregate functions, performance optimization strategies, and the use of XML for data transport.

Uploaded by

Jade Malit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 64

Database Query Languages

SQL
A relational database model contains tables, and the records in those tables
are accessed using Structured Query Language (SQL). SQL is used to create
the database access sections of applications.

IBM created the original relational database technology. SQL was initially
called SEQUEL.

• Query Language – a language used to query a database


• Query - a request or question put to the database

SQL statements are divided into these categories:


• SQL Data Definition
• SQL Data Manipulation
SQL Data Definition
Data Definition Language (DDL) statements let you to create, alter, and
drop schema objects. The CREATE, ALTER, and DROP commands require
exclusive access to the specified object. For example, an ALTER TABLE
statement fails if another user has an open transaction on the specified
table.

The DDL statements are:


• ALTER
• CREATE
• DROP
CREATE TABLE Persons
(
CREATE TABLE
P_Id int,
CREATE TABLE table_name LastName varchar(255),
( FirstName varchar(255)
field_name1 datatype, )
field_name2 datatype,
field_name3 datatype
)
ALTER TABLE
ALTER TABLE table_name ALTER TABLE Student
ADD field_name data_type ADD Color varchar(255)

ALTER TABLE table_name


DROP COLUMN field_name
DROP TABLE
DROP TABLE table_name

DROP DATABASE database_name

TRUNCATE table_name
* Removes All Rows
Deletes all rows in the table instantly, without logging each row
deletion individually (unlike DELETE).
SQL Data Manipulation
Data Manipulation Language (DML) statements access and manipulate
data in existing schema objects.

The data manipulation language statements are:


• SELECT
• INSERT
• UPDATE
• DELETE
Select Statements
Queries are used to retrieve data from tables in a database. The SELECT
command creates queries, and has various optional clauses that
include performing functions such as filtering and sorting.

Basic Query — The most simple of queries retrieves all records from a
single table.

Select Statement – is the list of fields retrieved from the table


From Clause – specifies from which to retrieve data
Select Statements - Basic Query
Select [FieldName] from [TableName]

Select * from Students

The * character tells the query to retrieve all fields from the table

Select LastName from Students


Select Statements - Sorted Query
Sorting uses the ORDER BY clause to retrieve records in a specific sorted
order.

Select [FieldName] from [TableName] ORDER BY [FieldName]

Select * from Students ORDER BY LastName


Select * from Students ORDER BY LastName, GWA
Select * from Students ORDER BY LastName ASC
Select * from Students ORDER BY LastName DESC
INSERT Statement
The INSERT command is used to add new records to a table.

INSERT INTO Persons (P_ID, LastName, FirstName)


Values (5, ‘Nakamura’, ‘Hero’)
UPDATE Statement
The UPDATE command allows changes to one or more records in a
table, at once.

UPDATE Persons
SET LastName=’Edogawa’, FirstName=’Conan’
WHERE P_ID=5
DELETE Statement
The DELETE command allows deletion of one or more records from a
table, at once.

DELETE from Persons


WHERE P_ID=5
Select Statements - Filtered Query
Filtered Query — A filtered query uses a WHERE clause to include or
exclude specific records.

Select [FieldName] from [TableName] where [FieldName] [SQL Operator] [Value]

Select * from STUDENTS where LastName=’Makiling’ AND FirstName=’Maria’


Select * from STUDENTS where Course=’BSIT’ OR Instructor=’Dela Cruz’

Logical Precedence: NOT, AND, OR


Select Statements - Filtered Query
Operator Type Condition is met when
AND Logical Both expressions are true
OR Logical Either expression is true
NOT Logical The expression is false
< Comparison value1 less than value2
<= Comparison value1 less than or equal to value2
> Comparison value1 greater than value2
>= Comparison value1 greater than or equal to value2
= Comparison value1 is equal to value2
<> Comparison value1 not equal to value2
BETWEEN Comparison sets a range of values
LIKE Comparison value matches the pattern specified
IN Comparison record belongs to particular group
Select Statements - Filtered Query
Select * from STUDENTS where LastName=’Manuel’
Select * from STUDENTS where GWA<75
Select * from STUDENTS where GWA<=75
Select * from STUDENTS where GWA>75
Select * from STUDENTS where GWA>=75
Select * from STUDENTS where GWA=75
Select * from STUDENTS where GWA<>75
Select * from STUDENTS where LastName BETWEEN ‘Diaz’ AND ‘Ferrer’
Select * from STUDENTS where LastName LIKE ‘D%’
Select GWA from STUDENTS where Lastname IN (‘Diaz’, ‘Manuel’)
The SQL CREATE TABLE Statement
• The CREATE TABLE statement is used to create a new table in a database.
Syntax

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
column3 datatype,
....
);
Syntax

CREATE TABLE products (


Id INT,
name STRING,
Price MONEY
)
SQL PRIMARY KEY Constraint
• The PRIMARY KEY constraint uniquely identifies
each record in a table.
• Primary keys must contain UNIQUE values, and
cannot contain NULL values.
• A table can have only ONE primary key; and in
the table, this primary key can consist of single
or multiple columns (fields).
SQL PRIMARY KEY on CREATE TABLE
CREATE TABLE products (
id INT NOT NULL,
name STRING,
Price MONEY,
PRIMARY KEY (id)
)
Let’s add data on our table

We need SQL INSERT INTO Statement

INSERT INTO Syntax


It is possible to write the INSERT INTO
statement in two ways:
1. Specify both the column names and the values to be
inserted:

INSERT INTO table_name (


column1,
column2,
column3, ...)
VALUES (
value1,
value2,
value3, ...);
2. If you are adding values for all the columns of
the table, you do not need to specify the column
names in the SQL query. However, make sure the
order of the values is in the same order as the
columns in the table. Here, the INSERT INTO
syntax would be as follows:
INSERT INTO table_name
VALUES (
value1,
value2,
value3,
...);
Code:

INSERT INTO products


VALUES (1, ‘Pen’, 1.20)
Syntax:

INSERT INTO products (id, name)


VALUES (2, ‘Pencil’)
READ DATA

SQL SELECT Statement is used to


select data from a database.
It allows you to READ the data from
your Database.
Syntax

SELECT column1, column2, ...


FROM table_name;
Syntax

SELECT * FROM products;

-- THE * MEANS EVERYTHING


Syntax for specific column

SELECT name, price FROM ‘products’;


SQL WHERE Clause

•The WHERE clause is used to filter records.


•It is used to extract only those records that
fulfill a specified condition
Syntax
SELECT * FROM products WHERE id=1
UPDATE RECORDS
SQL UPDATE Statement
The UPDATE statement is used to modify the existing
records in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
What if we want to add another column?
SQL ALTER TABLE Statement
• 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.
ALTER TABLE - ADD Column

To add a column in a table, use the


following syntax:
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE - DROP COLUMN

• To delete a column in a table, use the following syntax


(notice that some database systems don't allow
deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;
ALTER TABLE - RENAME COLUMN

•To rename a column in a table, use the


following syntax:
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;
What if we want to add another column?
Syntax:

ALTER TABLE products


ADD stock INT
After adding the column.
You need to add value to the new column
Syntax

UPDATE products
SET stock = 32
WHERE id = 1
Destroy/ Delete

SQL DELETE Statement - is used to delete


existing records in a table.
Syntax:
DELETE FROM table_name
WHERE condition;
Syntax in our Records
DELETE FROM products
WHERE id = 2
What if we to delete column?
ALTER TABLE table_name
DROP COLUMN column_name;
Aggregated Queries and SQL
Aggregate Functions
What is an Aggregated Query?
• Definition: Aggregated queries summarize, group, or
aggregate records into summarized record sets.
• Key Features:
• Typically contain fewer records compared to non-
aggregated queries.
• Used for deriving meaningful summaries from large
datasets.
GROUP BY Clause VS HAVING Clause
• Definition: GROUP BY groups • Definition: Filters the
records by one or more columns aggregated results produced by
and summarizes data. GROUP BY.
• Purpose: Enables aggregation of • Key Difference from WHERE:
data into summarized record • WHERE filters records before
sets. aggregation.
• HAVING filters records after
aggregation.
Why HAVING Clause is Necessary
• Reason:
• WHERE cannot be used with aggregate functions like SUM, AVG,
COUNT, etc.
• HAVING allows conditions to be applied to aggregated data.
SQL Aggregate Functions
Overview: Perform calculations on sets of values and return a single value.
Common Functions:
1. AVG: Returns the average value of a specified field.
Example: SELECT AVG(OrderPrice) FROM Orders;

2. COUNT: Returns the number of records.


Example: SELECT COUNT(Customer) FROM Orders;

3. SUM: Returns the sum of values in a specified field.


Example: SELECT SUM(OrderPrice) FROM Orders;

4. MAX: Returns the largest value in a specified field.


Example: SELECT MAX(OrderPrice) FROM Orders;
Example Table: Orders
O_Id OrderDate Customer OrderPrice

1 2008/11/12 Nilsen 700

2 2008/10/23 Hansen 1600

3 2008/09/02 Nilsen 700

4 2008/09/03 Hansen 300

5 2008/08/30 Hansen 2000

6 2008/10/04 Jensen 100


CREATE TABLE Orders (
O_Id INT PRIMARY KEY,
OrderDate DATE,
Customer VARCHAR(50),
OrderPrice INT
);

INSERT INTO Orders (O_Id, OrderDate, Customer, OrderPrice) VALUES


(1, '2008-11-12', 'Nilsen', 700),
(2, '2008-10-23', 'Hansen', 1600),
(3, '2008-09-02', 'Nilsen', 700),
(4, '2008-09-03', 'Hansen', 300),
(5, '2008-08-30', 'Hansen', 2000),
(6, '2008-10-04', 'Jensen', 100);
Calculate Total Sales Per Customer:
SELECT Customer, SUM(OrderPrice)
FROM Orders
GROUP BY Customer;
Filter Customers with High Purchases:
SELECT Customer, SUM(OrderPrice)
FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice) > 2000;
• Count Orders Per Customer:
SELECT Customer, COUNT(O_Id)
FROM Orders
GROUP BY Customer;
SQL Performance Tuning and Optimization
• Becoming a database expert requires experience and training.
• Key Tips for Performance Optimization:
• Use 3NF database design (Normalization).
• Avoid number-to-character conversions for better comparison.
• Fetch only required data; avoid SELECT *.
• Create indexes on frequently searched columns, but avoid
indexing columns with high update/insert activity.
• Prevent full-table scans by indexing columns used in WHERE
clauses.
SQL Query Optimization Best Practice
1. Understand query execution using database-specific tools
2. Retrieve minimal data (SELECT specific columns).
3. Store intermediate results in temporary tables to simplify complex
queries.
4. Avoid using the OR operator in queries to improve speed.
5. Batch transactions with periodic COMMITs for efficiency.
Additional Optimization Strategies
• Aggregate Tables: Pre-populate summarized data for faster queries.
• Regular database defragmentation/reorganizing to maintain
performance.
• Server Tuning: Optimize server parameters to utilize hardware fully.
XML, XQuery, and XPath
• XML Overview: A self-descriptive language for data storage and
transport, independent of software/hardware.
• Simplifies data sharing, transport, and platform upgrades.
• XQuery: Query language for XML, like SQL for databases.
• Used for web services, reports, and data transformation.
• XPath: Syntax for navigating XML documents.
Key Takeaways
• Optimize queries by understanding execution plans and limiting
returned data.
• Use indexing and partitioning wisely to enhance performance.
• Explore XML for data transport for intuitive querying.
• Always plan for maintenance and server tuning for sustained
efficiency.

You might also like