Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Database and SQL

A database is an integrated collection of data; an electronic method for storing customer information,
invoices, mailing lists and more. A database management system (DBMS) provides mechanisms for
storing and organizing data in a manner that is consistent with the database’s format. Database
management systems enable programmers to access and store data without worrying about the internal
representation of databases using SQL commands.

In this lesson, you will be able to:


 Understand database and its models.
 Using SQL commands to manipulate records
 Modify the database by adding and deleting records.


Database
Various models of database exist, two of which are flat-file and relational databases. The relational
model of databases is the most commonly used for desktop and Web development.

Flat-File Database Model


Flat-file model (Figure 15.1) databases store information in single tables, including repeated data. For
example, if a store was selling different kinds of products and wanted to track customers, orders,
products, and suppliers, the database would look like:
Customer Order Order Product1 Product Product1 Product2 Product Product2
Date No Supplier1 Cost Supplier2 Cost
Miguel Alejandro 12/08/2009 231 Pencil Emily’s Store 25.00 Sharpener Lilibeth Mall 5.00
George Andrew 6/12/2008 333 Barney Emily’s Store 100.00 Spelling Lonel’s Educ. 12.00
CD Booklet Suply
Ric Ryan Jay 5/31/2007 123 Thomas Stephanie 320.99 Bogo Mc Mac 45.50
and Toy Shop Bond Merchandise
Friends Paper
Train
Figure 15.1 Flat-File model.
Here are just few of the issues with the flat-file database model.
 Reduntant data. Entries often get repeated taking up more space than necessary. Example,
there is no reason to spell out the names o the suppliers each time.
 Error prone. When data has to be repeated, more chances to enter erroneous data into the
table.
 Limited columns. Currently, only two products and their information can be entered using
the table structure displayed.
 Extra work to update. With the redundant data issue, if you want to make any updates, you
will have to make sure you parse through the order fields and update those values to match.

Relational Database Model


A relational database organizes your data into tables. Some popular relational database management
systems (RDBMS) are Microsoft SQL Server, Oracle, Sybase, IBM DB2 and PostgreSQL.

Relational database (Figure 15.2) models use tables that are related to one another to store information.
For example, instead of having your orders all stored in a single table called Orders, the information
would be stored in related tables, with customer information being stored in one table, order information
stored in another, product information in yet another, and so on. The flat-file table above could be
structured into a relational model.

Some benefits of using relational databases.


 Nonredundant data. Because entries are entered once, and other tables point to the data,
there is less redundant data.
 Less error prone. When data is entered once in lookup tables, data is then picked from lists.
This lends greater control and prevents input errors.
 Unlimited data. Because data is stored in rows versus fields, the data is not limited to
predefined structures. For example, when you want to add another product to an invoice, you
simply add another record to InvoiceDetailsFile table. In the flat file, you would have had to add
a third or fourth product column.
Figure 15.2 .The Northwind.mdb database
The figure shows the database diagram of the tables--the data is now separated out, as compared to the single table.

Tables: Where Data Are Stored


Tables have specific elements: fields, primary keys, and indexes. Every table has a primary key- a column (or
group of columns) in a table that requires a unique value that cannot be duplicated in other rows. This guarantees
that a primary key value can be used to uniquely identify a row. A primary key that is composed of two or more
columns is known as a composite key.

Every table in a relational database is organized into rows, where each row represents a single record. The rows
are organized into columns. All the rows in a table have the same column structure. For example, the Orders table
has these columns: OrderID, CustomerID, EmployeeID, OrderDate, etc.

For any given order, you need to know the customer's name, address, contact name, and so forth. You could store
that information with each order, but that would be very inefficient. Instead, you use a second table called Customers,
in which each row represents a single customer. In the Customers table is a column for the CustomerID. Each
customer has a unique ID, and that field is marked as the primary key for that table.

The Orders table uses the CustomerID as a foreign key. A foreign key is a column (or combination of columns) that
is a primary key from a different table. The Orders table uses the CustomerID (the primary key used in the Customers
table) to identify which customer has placed the order. To determine the address for the order, you can use the
CustomerID to look up the customer record in the Customers table.

This use of foreign keys is particularly helpful in representing relationships between tables. By separating
information into tables that are linked by foreign keys, you avoid having to repeat information in records. A single
customer, for example, can have multiple orders, but it is inefficient to place the same customer information (name,
phone number, credit limit, and so on) in every order record. The process of removing redundant information from
your records and shifting it to separate tables is called normalization.

Normalization
Normalization split related data into separate tables to ensure that a database does not store redundant data. It
makes use of the database more efficient and reduces the likelihood of data corruption. If you kept the customer's
name in both the Customers table and the Orders table, you would run the risk that a change in one table might
not be reflected in the other. Thus, if you changed the customer's address in the Customers table, that change might
not be reflected in every row in the Orders table (and a lot of work would be necessary to make sure that it was
reflected). By keeping only the CustomerID in Orders, you are free to change the address in Customers, and the
change is automatically reflected for each order.

Database programmers want the database to help them avoid data corruption. SQL Server and other modern
relational databases avoid bugs by enforcing constraints that you request. For example, the Customers table marks
the CustomerID as a primary key. This creates a primary key constraint in the database, which ensures that each
CustomerID is unique.
Declarative Referential Integrity
Relational databases use Declarative Referential Integrity (DRI) to establish constraints on the
relationships among the various tables. For example, you might declare a constraint on the Orders table
that dictates that no order can have a CustomerID unless that CustomerID represents a valid record in
Customers. This helps avoid two types of mistakes. First, you can't enter a record with an invalid
CustomerID. Second, you can't delete a Customer record if that CustomerID is used in any order. The
integrity of your data and its relationships is thus protected.

Structured Query Language


The most popular declarative language for querying and manipulating databases is SQL. The heart of
SQL is the query. A query is a statement that returns a set of records (result set) from the database. In
this topic, the following database tables are used to manipulate and modify the data stored.

Table Name: EMPLOYEEFILE


EMPIDNO EMPFIRSTNAME EMPLASTNAME EMPSALARY EMPDATEHIRED EMPADDRESS
100 Victoria Malihim 30000 04/10/2017 Cebu City
200 Topacio Mamaril 35000 08/20/2016 Cebu City
300 Demetria Dagdag 43000 02/7/2015 Liloan, Cebu
400 Ligaya Almundo 23000 10/25/2017 Mandaue City

Table Name: PROJECTFILE


PROJTID PROJDESCRIPTION PROJCOST PROJLOCATION
47Y16 Bikang Homes $123,000,000,000 Cebu City
56T20 Vertical Horizon $456,000,000,000 Mandaue City
59R13 Banana Towers $789,000,000,000 Cebu City

Table Name: ASSIGNMENTFILE


ASSIGNEMPIDNO ASSIGNMPROJID ASSIGNPERCENT
100 47Y16 50
100 56T20 50
200 47Y16 25
200 56T20 25
200 59R13 50
300 56T20 100
400 56T20 50
400 59R13 50

Common SQL Keywords Used

SELECT Query. Retrieves or "selects" rows and columns from one or more tables in a database. Such
selections are performed by queries with the SELECT keyword. The the rows returned from the query
are in any order. FROM statement specifies the tables involved in a query and is required in every query.
You can specify criteria for sorting rows.
Basic form 1: SELECT * FROM <tableName>
Basic form 2: SELECT columnName1, columnName2, ... FROM <tableName>

Example 1: Retrieve all data columns in the Customers table.


SELECT * FROM EMPLOYEEFILE
Example 2: Retrieve only specific data for all rows in the Customers table.
SELECT EMPIDNO, EMPFIRSTNAME, EMPLASTNAME FROM EMPLOYEEFILE

WHERE Clause. An optional clause used in a query to specify the selection criteria (formally called
predicates) that determine the rows to be retrieved, deleted or updated for the query .
Form: SELECT columnName1, columnName2, ... FROM <tableName> FROM [WHERE <criteria>]

Example 1: Retrieve only specific data for all rows in the Emloyees table that satisfy the selection criteria
SELECT EMPIDNO, EMPFIRSTNAME, EMPLASTNAME FROM EMPLOYEEFILE WHERE EMPSALARY > 30000

The WHERE clause criteria can contain the relational operators <, >, <=, >=, = (equality), <>
(inequality) and LIKE and BETWEEN, as well as the logical operators AND, OR and NOT. Operator LIKE
is used for pattern matching with wildcard characters percent (%) and underscore (_).
Pattern matching allows SQL to search for strings that match a given pattern.
 The percent character (%) searches for strings that have zero or more characters at the percent
character's position. Note that the pattern string is surrounded by single-quote character.
Example 1: Query locates the rows of all the employees whose last names start with the letter D.
SELECT EMPIDNO, EMPFIRSTNAME, EMPLASTNAME FROM EMPLOYEEFILE WHERE EMPLASTNAME LIKE
'D%'
 A question mark (?) for MS Access only or an underscore (_) indicates a single wildcard character
at that position in the pattern.
Example 2: To locate the rows of all the employees whose last names start with any character (specified by _), followed by the letter h, followed by any
number of additional characters (specified by %):
SELECT EMPIDNO, EMPFIRSTNAME FROM EMPLOYEEFILE WHERE EMPFIRSTNAME LIKE '_h%'

ORDER BY Clause. An optional clause used for sorting the rows in the query result.
SELECT columnName1, columnName2, ... FROM <tableName> ORDER BY column [ASC|DESC]

where ASC specifies ascending order (lowest to highest), DESC specifies descending order and column
specifies the column on which the sort is based. The default sorting order is ascending.

Example 1: to obtain the list of employees in ascending order by last name, use the query.
SELECT EMPIDNO, EMPFIRSTNAME, EMPLASTNAME FROM EMPLOYEEFILE ORDER BY
EMPLASTNAME ASC

Example 2: the query returns the rows in descending order according to PROJDESCRIPTION, and any rows that have the same values are sorted in
ascending order by PROJID.
SELECT PROJID, PROJDESCRIPTION FROM PROJECTFILE ORDER BY PROJDESCRIPTION DESC,
PROJID ASC

Note that the sorting order does not have to be identical for each column. The WHERE and ORDER BY
clauses can be combined in one query.
Example 3: To query the ProjectIDNo, ProjectDescription and ProjectPrice of each item in the ProjectFile table that has a description beginning with "Ama"
and sorts them in ascending order by ProjectID.
SELECT PROJID, PROJDESCRIPTION, PROJPRICE FROM PROJECTFILE WHERE
PROJDESCRIPTION LIKE ‘Ama%‘ ORDER BY PROJID ASC

Merging Data from Multiple Tables: INNER JOIN


Oftentimes, data are merged from multiple tables into a single result. An INNER JOIN merges rows from
two tables by testing for matching values in a column that is common to the tables. The ON clause of
the INNER JOIN specifies the columns from each table that are compared to determine which rows are
merged.
SELECT columnName1, columnName2,... FROM table1 INNER JOIN table2 ON table1.columnName
= table2.columnName[ORDER BY columnName]

Example: Query to produce a combination of the records


SELECT EMPLASTNAME, EMPFIRSTNAME, ASSIGNMENTFILE.ASSIGNPROJID,
ASSIGNMENTFILE.PROJDESCRIPTION
FROM EMPLOYEEFILE INNER JOIN ASSIGNMENTFILE
ON EMPLOYEEFILE.EMPIDNO = ASSIGNMENTFILE.ASSIGNEMPIDNO
ORDER BY EMPLASTNAME ASC, EMPFIRSTNAME;

Result Set:
Lastname Firstname Project ID Project Description

Almundo Ligaya 59R13 Banana Towers


Almundo Ligaya 56T20 Vertical Horizon
Dagdag Demetria 56T20 Vertical Horizon
Malihim Victoria 56T20 Vertical Horizon
Malihim Victoria 47Y16 Bikang Homes
Mamaril Topacio 59R13 Banana Towers
Mamaril Topacio 47Y16 Bikang Homes
Mamaril Topacio 56T20 Vertical Horizon
The query combines the FirstName and LastName columns from table EMPLOYEE and the PROJID
column from table ASSIGNMENTFILE, sorting the results in ascending order by LastName and
FirstName. Note the use of the syntax tableName.columnName in the ON clause. This syntax (called a
qualified name) specifies the columns from each table that should be compared to join the tables. The
"tableName." syntax is required if the columns have the same name in both tables. The same syntax
can be used in any query to distinguish columns that have the same name in different tables. In a SQL
query, failure to qualify names for columns that have the same name in two or more tables is an error.
As always, the query can contain an ORDER BY clause.
AGGREGATE FUNCTIONS
 SUM. The SUM() function returns the total sum of a numeric column.
Example: SELECT SUM(EMPSALARY)FROM EMPLOYEEFILE WHERE EMPADDRESS =’Cebu City’

 MIN. The MIN() function returns the smallest value of the selected column.
Example: SELECT MIN(EMPSALARY)FROM EMPLOYEEFILE

 MAX. The MAX() function returns the largest value of the selected column.
Example: SELECT MAX(EMPSALARY)FROM EMPLOYEEFILE

 AVERAGE. The AVG() function returns the average value of a numeric column.
Example: SELECT AVG(PROJCOST)FROM EMPLOYEEFILE WHERE EMPLASTNAME LIKE ‘?M%’

 COUNT. The COUNT() function returns the number of rows that matches a specified criteria.
Example: SELECT COUNT(PROJID)FROM PROJECTFILE WHERE PROJDESCRIPTION LIKE ‘A%’

GROUP BY. The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM,
AVG) to group the result-set by one or more columns.
Basic Form: SELECT <columnName1, columnName2, . ., columnNamen> FROM <tablename>
WHERE <criteria> GROUP BY <columnName1,columnName2,. ., columnNamen>
[ORDER BY <columnName1,columnName2,. . , columnNamen>]

// Returns the number of projects according to location (from highest to lowest, default sort)
Example 1: SELECT COUNT(PROJID)AS [COUNT], PROJLOCATION FROM PROJECTFILE GROUP BY
PROJLOCATION

// Returns the number of projects according to location from lowest to highest


Example 2: SELECT COUNT(PROJID), PROJLOCATION FROM PROJECTFILE GROUP BY PROJLOCATION
ORDER BY COUNT(PROJID)ASC

// Returns the number of projects an employee handles sorted by lastname


Example 3: SELECT EMPLASTNAME AS [LASTNAME],COUNT(ASSIGNMENTFILE.ASSIGNPROJECTID) AS
[NUMBER OF PROJECTS]
FROM ASSIGNMENTFILE INNER JOIN EMPLOYEEFILE ON ASSIGNMENTFILE.ASSIGNEMPIDNO =
EMPLOYEEFILE.EMPIDNO GROUP BY EMPLASTNAME

HAVING. The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
Form: SELECT columnName1, columnName2, ... FROM <tableName>
WHERE <criteria>
GROUP BY columnName1, columnName2, columnNameN
HAVING <condition>
[ORDER BY columnName1, columnName2, columnNamen]

// Returns the number of projects that are greater than 1.


Example 1: SELECT COUNT(PROJID), PROJLOCATION FROM PROJECTFILE
GROUP BY PROJLOCATION
HAVING COUNT(PROJID)>1
ORDER BY COUNT(PROJID)ASC

// Returns certain employees handling more than a single project.


Example 2: SELECT EMPLASTName, COUNT(ASSIGNMENTFILE.PROJID) AS NumberOfPROJECTS
FROM ASSIGNMENTFILE INNER JOIN EmployeeFILE ON ASSIGNMENTFILE.ASSIGNEMPIDNO =
EMPLOYEEFILE.EMPIDNO
WHERE EMPLASTNAME = 'MALIHIM' OR EMPLASTNAME = 'DAGDAG'
GROUP BY EMPLASTNAME HAVING COUNT(PROJECTID) > 1;
DATABASE MODIFICATION STATEMENTS
The following commonly used data manipulation statements modifies a data in the database.

INSERT Statement. The INSERT statement inserts a row into a table.


INSERT INTO <tableName>(columnName1, columnName2 .., columnNamen ) VALUES (value1,
value2,.., valuen )

The tableName is followed by a comma-separated list of column names in parentheses. The list of
column names is followed by the SQL keyword VALUES and a comma-separated list of values in
parentheses. The values specified here must match up with the columns specified after the table name
in both order and type (e.g., if columnName1 is supposed to be the FirstName column, then value1 should
be a string in single quotes representing the first name). Always explicitly list the columnswhen
inserting rows if the order of the columns in the table changes, using only VALUES may cause anerror.
Example: inserts a row into the Employee table the values 'Wenie' and 'Sollano' for the FirstName and LastName columns, respectively.
INSERT INTO EMPLOYEEFILE (EMPFIRSTNAME, EMPLASTNAME) VALUES ('Wenie', 'Sollano' )

Note. SQL uses the single-quote (') character to delimit strings. To specify a string containing a single quote (e.g.,
O'Malley) in a SQL statement, there must be two single quotes in the position where the single-quote character
appears in the string (e.g., 'O''Malley'). The first of the two single-quote characters acts as an escape character for
the second. Not escaping single-quote characters in a string that is part of a SQL statement is a syntax error.

UPDATE Statement. An UPDATE statement modifies data in a table.


UPDATE <tableName> SET <columnName1 = value1, columnName2 = value2, ..,columnNamen =
valuen> [WHERE <criteria>]

The tableName is followed by keyword SET and a comma-separated list of column name-value pairs in
the format columnName = value. The optional WHERE clause provides criteria that determine which
rows to update.

Example: Update the EmployeeFile table’s EMPFIRSTNAME to “William” for all rows in which EMPADDRESS is equal to Cebu City and EMPIDNO is equal
to 123.
UPDATE EMPLOYEEFILE SET EMPFIRSTName = 'William' WHERE EMPAddress = 'Cebu City' AND
EMPIDNO = '123'

DELETE Statement. Remove rows from a specified table. Multiple rows will be deleted if all the rows meet
the criteria in the WHERE clause.
DELETE FROM <tableName> [WHERE <criteria>]
Example: To delete the row for Sample Inc. Cebu City in the Customers table
DELETE FROM EMPLOYEEFILE WHERE EMPFIRSTName = 'Diosdado' AND EMPAddress ='Cebu
City

References:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/
www.articles.com
www.akadia.com
www.blackwasp.co.uk
www.bogotobogo.com
www.c-sharpcorner.com
www.codeproject.com
www.completechsarptutorial.com
www.csharp-sation.com
www.chsarp.net-tutorials.com
www.develop.com
www.geom.ulcc.edu
www.Indiabix.com
www.tutorialspoint.com
www.w3schools.com

You might also like