Lab docment
Lab docment
SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in relational database.
SQL is the standard language for Relation Database System. All relational database management
systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL
as standard database language.
Also, they are using different dialects, such as:
Why SQL?
Allows users to access data in relational database management systems.
Allows users to define the data in database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries & pre-compilers.
SQL Commands:
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These commands can be classified into groups based
on their nature:
1|Page
DML -Data Manipulation Description
Language:Command
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Adugna | 32 | Wolkite| 2000.00 |
| 2 | Mebratu| 25 | Durame | 1500.00 |
| 3 | Leom |23 | Gubre | 2000.00 |
| 4 | Tsedeke |25 | Hossana| 6500.00 |
| 5 | Bogale |27 | Addis Abebe|8500.00 |
+----+----------+-----+-----------+----------+
What is field?
2|Page
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table
consist of ID, NAME, 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 column?
A column is a vertical entity in a table that contains all information associated with a specific
field in a table.
SQL Constraints:
Constraints are the rules enforced on data columns on 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 could be column level or table level. Column level constraints are applied only to
one column, whereas table level constraints are applied to the whole table.
Following are commonly used constraints available in SQL:
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.
INDEX: Use to create and retrieve data from the database very quickly.
Example:
3|Page
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns, three of which, ID and NAME and AGE, specify not to accept NULLs:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
DOB DATETIME NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18,2),
PRIMARY KEY (ID)
);
If CUSTOMERS table has already been created, then to add a NOT NULL constraint to
SALARY column in Oracle and MySQL, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) NOT NULL;
DEFAULT Constraint:
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO
statement does not provide a value for this column. Then by default this column would be set to
5000.00.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 5000.00,
PRIMARY KEY (ID)
);
If CUSTOMERS table has already been created, then to add a DFAULT constraint to SALARY
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;
4|Page
UNIQUE Constraint:
The UNIQUE Constraint prevents two records from having identical values in a particular
column. In the CUSTOMERS table, for example, you might want to prevent two or more people
from having identical DOB.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with same
age:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
DOB DATETIME NOT NULL UNIQUE,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL UNIQUE;
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);
FOREIGN Key:
A foreign key is a key used to link two tables together. This is sometimes called a referencing
key.
Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a
Foreign Key in the second table.
If a table has a primary key defined on any field(s), then you can not have two records having the
same value of that field(s).
Example:
Consider the structure of the two tables as follows:
CUSTOMERS table:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
6|Page
PRIMARY KEY (ID)
);
ORDERS table:
CREATE TABLE ORDERS (
ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID)
);
If ORDERS table has already been created, and the foreign key has not yet been set, use the
syntax for specifying a foreign key by altering a table.
ALTER TABLE ORDERS
ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
7|Page
INDEX:
The INDEX is used to create and retrieve data from the database very quickly. Index can be
created by using single or group of columns in a table. When index is created, it is assigned a
ROWID for each row before it sorts out the data.
Proper indexes are good for performance in large databases, but you need to be careful while
creating index. Selection of fields depends on what you are using in your SQL queries.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, you can create index on single or multiple columns using the following syntax:
CREATE INDEX index_name
ON table_name ( column1, column2.....);
To create an INDEX on AGE column, to optimize the search on customers for a particular age,
following is the SQL syntax:
CREATE INDEX idx_age
ON CUSTOMERS ( AGE );
DROP anINDEX Constraint:
To drop an INDEX constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP INDEX idx_age;
Data Integrity:
The following categories of the 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.
SQL Syntax
SQL is followed by unique set of rules and guidelines called Syntax. This tutorial gives you a
quick start with SQL by listing all the basic SQL Syntax:
All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE,
DELETE, ALTER, DROP, CREATE, USE, SHOW and all statements end with a semicolon (;).
8|Page
Important point to be noted is that SQL is case insensitive, which means SELECT and select
have same meaning in SQL statements, but MySQL makes difference in table names. So if you
are working with MySQL, then you need to give table names as they exist in the database.
SQL SELECT Statement:
SELECT column1, column2....columnN
FROM table_name;
SQL DISTINCT Clause:
SELECT DISTINCT column1, column2....columnN
FROM table_name;
SQL WHERE Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION;
SQL AND/OR Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
SQL IN Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SQL BETWEEN Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
SQL LIKEClause:
SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
SQL ORDER BY Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
SQL GROUP BY Clause:
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SQL COUNT Clause:
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
9|Page
SQL HAVING Clause:
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
SQL CREATE TABLE Statement:
CREATE TABLE table_name(column1 datatype,
column2 datatype,
column3 datatype, .....
columnN datatype,
PRIMARY KEY( one or more columns ) );
SQL DROP TABLE Statement:
DROP TABLE table_name;
SQL CREATE INDEX Statement:
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);
SQL DROP INDEX Statement:
ALTER TABLE table_name
DROP INDEX index_name;
SQL DESC Statement:
DESC table_name;
SQL TRUNCATE TABLE Statement:
TRUNCATE TABLE table_name;
SQL ALTER TABLE Statement:
ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};
SQL ALTER TABLE Statement (Rename):
ALTER TABLE table_name RENAME TO new_table_name;
SQL INSERT INTO Statement:
INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);
SQL UPDATE Statement:
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
SQL DELETE Statement:
DELETE FROM table_name
WHERE {CONDITION};
SQL CREATE DATABASE Statement:
CREATE DATABASE database_name;
SQL DROP DATABASE Statement:
DROP DATABASE database_name;
SQL USE Statement:
USE DATABASE database_name;
SQL COMMIT Statement:
COMMIT;
10 | P a g e
SQL ROLLBACK Statement:
ROLLBACK;
SQL Data Types
SQL data type is an attribute that specifies type of data of any object. Each column, variable and
expression has related data type in SQL.
You would use these data types while creating your tables. You would choose a particular data
type for a table column based on your requirement.
SQL Server offers six categories of data types for your use:
Tinyint 0 255
Bit 0 1
Money - +922,337,203,685,477.58
922,337,203,685,477.5808 07
Smallmoney -214,748.3648 +214,748.3647
11 | P a g e
Varbinary Maximum length of 8,000 bytes.(Variable length binary data)
varbinary(max) Maximum length of 231 bytes (SQL Server 2005 only). ( Variable
length Binary data)
DATA TYPE
Description
sql_variant Stores values of various SQL Server-supported data types, except text,
ntext, and timestamp.
timestamp Stores a database-wide unique number that gets updated every time a row
gets updated
uniqueidentifier Stores a globally unique identifier (GUID)
xml Stores XML data. You can store xml instances in a column or a variable
(SQL Server 2005 only).
cursor Reference to a cursor object
table Stores a result set for later processing
12 | P a g e