Professional Documents
Culture Documents
What is SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in a relational database. SQL is the standard language for Relational Database
System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle,
Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.
COMMAND DESCRIPTION
CREATE Creates a new table, a view of a table, or another object in the
database.
ALTER Modifies an existing database object, such as a table
Deletes an entire table, a view of a table or other objects in the
DROP
database.
2. Data Manipulation Language (DML)
SQL Commands that are used to retrieve, store, modify, delete, and update records in database.
COMMAND DESCRIPTION
SELECT Retrieves certain records from one or more tables.
INSERT Creates or insert a new record.
UPDATE Modifies records.
DELETE Deletes records.
3. Data Control Language (DCL)
SQL Commands that control the level of access that users have on database objects.
COMMAND DESCRIPTION
GRANT allows users to read/write on certain database objects
REVOKE keeps users from read/write permission on database objects
4. Transaction Control Language (TCL)
SQL Commands that control and manage transactions to maintain the integrity of data within
SQL statements.
COMMAND DESCRIPTION
BEGIN Transaction opens a transaction
COMMIT Transaction commits a transaction
ROLLBACK Transaction ROLLBACK a transaction in case of any error
What is RDBMS?
A Relational database management system (RDBMS) is a database management system (DBMS) that is
based on the relational model as introduced by E. F. Codd, such as MS SQL Server, IBM DB2, Oracle,
MySQL, Microsoft Access, and PostgreSQL
What is a Table?
The data in an RDBMS is stored in database objects which are called as tables. This table is basically a
collection of related data entries and it consists of numerous columns and rows.
Below is an example of EMPLOYEE table:
+------+-------------+--------+-------------------+---------------+
| ID | LNAME | AGE | CITY | SALARY |
+------+-------------+--------+-------------------+---------------+
| 1 | Go | 23 | Danao City | 2500.00 |
| 2 | Arante | 52 | Cebu City | 3500.00 |
| 3 | Caraan | 32 | Davao City | 4800.00 |
| 4 | Lasala | 28 | Manila | 8500.00 |
| 5 | Capoy | 26 | Butuan City | 6400.00 |
| 6 | Tui | 21 | Dumaguete | 4300.00 |
+-----+-------------+--------+--------------------+--------------+
What is a field?
Every table is broken up into smaller entities called fields. The fields in the EMPLOYEE table consist of
ID, LNAME, AGE, ADDRESS and SALARY. A field is a column in a table that is designed to maintain
specific information about every record in the table.
What is a Record or a Row?
A record is also called as a row of data is each individual entry that exists in a table. For example, there
are 7 records in the above CUSTOMERS table. Following is a single row of data or record in the
EMPLOYEE table:
What is a column?
A column is a vertical entity in a table that contains all information associated with a specific field in a
table. For example, a column in the EMPLOYEE table is SALARY, which represents the employees salary
and would be as shown below:
+---------------+
| SALARY |
+---------------+
| 2500.00 |
| 3500.00 |
| 4800.00 |
| 8500.00 |
| 6400.00 |
+---------------+
What is a NULL value?
A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL
value is a field with no value. It is very important to understand that a NULL value is different than a
zero value or a field that contains spaces. A field with a NULL value is the one that has been left blank
during a record creation.
SQL Constraints
Constraints are the rules enforced on data columns on a table. These are used to limit the type of data
that can go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints can either be column level or table level. Column level constraints are applied only to one
column whereas, table level constraints are applied to the entire table.
Following are some of the most commonly used constraints available in SQL:
NOT NULL Constraint: Ensures that a column cannot have a NULL value.
UNIQUE Constraint: Ensures that all the values in a column are different.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.
INDEX: Used to create and retrieve data from the database very quickly.
Data Integrity
The following categories of data integrity exist with each RDBMS:
Entity Integrity: There are no duplicate rows in a table.
Domain Integrity: Enforces valid entries for a given column by restricting the type, the format, or
the range of values.
Referential integrity: Rows cannot be deleted, which are used by other records.
User-Defined Integrity: Enforces some specific business rules that do not fall into entity, domain or
referential integrity.
Database Normalization
Database normalization is the process of efficiently organizing data in a database. There are two reasons
of this normalization process:
Eliminating redundant data. For example, storing the same data in more than one table.
Ensuring data dependencies make sense.
It is your choice to take it further and go to the fourth normal form, fifth normal form and so on, but in
general, the third normal form is more than enough.
Problem Without Normalization
Without Normalization, it becomes difficult to handle and update the database, without facing data
loss. Insertion, Updates and Deletion Anomalies are very frequent if Database is not Normalized. To
understand these anomalies let us take an example of Student table.
ID STUDNAME ADDRESS SUBJECTS
1 Adrian Cebu Biology, Physics
2 Dexter Iloilo Mathematics
3 Stanley Davao Mathematics
Update Anomaly: To update address of a student who occurs twice or more than twice in a table, we
should update Address column in all the rows, else data will become inconsistent.
Insertion Anomaly: Suppose for a new admission, we have a Student ID (ID), name (STUDNAME) and
address(ADDRESS) of a student but if student has not opted for any subjects yet then we must insert
NULL there, leading to Insertion Anomaly.
Deletion Anomaly: If Id 1 has only one subject and temporarily he drops it, when we delete that row,
entire student record will be deleted along with it.
Database First Normal Form (1NF)
The First normal form (1NF) sets basic rules for an organized database:
Define the data items required, because they become the columns in a table.
Place the related data items in a table.
Ensure that there are no repeating groups of data.
Ensure that there is a primary key.
First Rule of 1NF
You must define the data items. This means looking at the data to be stored, organizing the data into
columns, defining what type of data each column contains and then finally putting the related columns
into their own table.
For example, you put all the columns relating to locations of meetings in the Location table, those
relating to student in the Student table and so on. Defining Student Table shown below:
STUDENT TABLE
ID STUDNAME AGE ADDRESS SUBJECTS
1 Adrian 21 Cebu Biology
2 Dexter 20 Iloilo Mathematics
3 Stanley 19 Davao Mathematics
4 Adrian 21 Cebu Physics
But as per the 1NF, we need to ensure that there are no repeating groups of data. So, let us break the
above table into two parts and then join them using a key as shown in the following program:
Customer Table
CREATE TABLE STUDENT (
ID INT NOT NULL PRIMARY KEY,
STUDNAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL
ADDRESS VARCHAR (25)
);
STUDENT TABLE
ID STUDNAME AGE ADDRESS
1 Adrian 21 Cebu
2 Dexter 20 Iloilo
3 Stanley 19 Davao
Subject Table
This table is in the first normal form; in that it obeys all the rules of the first normal form. In this table,
the primary key consists of the STUDID and the SUBJECTID. Combined, they are unique assuming the
same customer would hardly order the same thing.
However, the table is not in the second normal form because there is partial dependencies of primary
keys and columns. STUDNAME is dependent on STUDID and there's no real link between a customer's
name and what he purchased. The SCHOOLYEAR is also dependent on the SUBJECTID, but they are not
dependent on the STUDID, because there is no link between a STUDID and an SCHOOLYEAR.
To make this table comply with the second normal form, you need to separate the columns into three
tables.
First, create a table to store the student details as shown in the code block below:
The next step is to create a table to store the details of each subject:
The dependency between the ZIPCODE and the ADDRESS is called as a transitive dependency. To
comply with the third normal form, all you need to do is to move the STREET, CITY and the STATE fields
into their own table, which you can call as the ADDRESS table.
The advantages of removing transitive dependencies are mainly two-fold. First, the amount of data
duplication is reduced and therefore your database becomes smaller. The second advantage is data
integrity. When duplicated data changes, there is a big risk of updating only some of the data, especially
if it is spread out in many different places in the database.
For example, if the address and the zip code data were stored in three or four different tables, then any
changes in the zip codes would need to ripple out to every record in those three or four tables.
4. The status of the connection was tested successfully. The connection was not saved however.
Click Save to save the connection, and then click Connect.
5. The connection was saved and you see the database in the list.
6. Expand HR_ORCL.
Note: When a connection is opened, a SQL Worksheet is opened automatically. The SQL
Worksheet allows you to execute SQL against the connection you just created.
7. Expand Tables.
8. Select the Table EMPLOYEES to view the table definition. Then click the Data tab.
SQL SYNTAX
CREATE DATABASE Statement
This is used to create a new SQL database.
Example:
TRUNCATE Statement
This is used to delete the data inside a table, but not the table itself.
Example:
Example:
Example:
DROP TABLE Statement
This is used to drop an existing table in a database.
Example:
Example:
ALTER TABLE Student MODIFY Year VARCHAR (6) DEFAULT 'FIRST' NOT NULL;
Example:
UPDATE Statement
This is used to modify the existing records in a table.
Example:
DELETE Statement
This is used to delete existing records in a table.
SELECT Statement
This is used to retrieve the all records of the columns specified from a table. It can also have WHERE
clause to filter the records to retrieve.
This is also used to retrieve the all records of the all columns from a table.
This also copies data some columns of a table into a new table.
It can also be used to create a new, empty table using the schema of another. Just add a WHERE clause
that causes the query to return no data:
WHERE Clause
This is used to extract only those records that fulfill a specified condition.
ROWNUM Clause
This is used to specify the number of records to return.
SELECT column1,, columnN FROM table_name WHERE CONDITION AND ROWNUM <= 3;
ORDER BY Clause
This is used to sort the result-set in ascending or descending order.
HAVING Clause
This was added to SQL because the WHERE keyword could not be used with aggregate functions.
SQL View
A view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns,
just like a real table. The fields in a view are fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data
were coming from one single table.
Creating View
Note: A view always shows up-to-date data! The database engine recreates the data, using the view's
Updating View
You can update a view by using the following syntax:
SQL Functions
COUNT / SUM / AVG Functions
The COUNT function returns the number of rows that matches a specified criterion.
The AVG function returns the average value of a numeric column.
NVL Function
This function is used to replace NULL value with another value. The function accepts 2 expressions
(parameters), and returns the first expression if it is not NULL, otherwise NVL returns the second
expression.
ROUND Function
ROUND function returns a number rounded to a certain number of decimal places.
SQL Operators
Arithmetic Operators
Operator Description
+ Addition Operator
- Subtraction Operator
* Multiplication Operator
/ Division Operator
% Modulo / Remainder Operator
Comparison Operator
Operator Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
Compound Operators
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
&= Bitwise AND equals
^-= Bitwise exclusive equals
|*= Bitwise OR equals
Logical Operators
IN Operator
SELECT column1, column2....columnN FROM table_name WHERE column_name IN (val-1, ..., val-N);
SELECT column_name(s) FROM table_name WHERE column_name IN (SELECT STATEMENT);
This allows you to specify multiple values in a WHERE clause.
BETWEEN Operator
ANY Operator
It returns true if any of the subquery values meet the condition.
ALL Operator
It returns true if any of the subquery values meet the condition.
AND/OR Clause
These are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND is TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.