Database and SQL
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.
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.
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.
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>
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
Result Set:
Lastname Firstname Project ID Project Description
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
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]
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.
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