You are on page 1of 11

SQL

Introduction SQL Components


- Structured Query Language (SQL) is a special – - Database
purpose programming language designed for “A database is a collection of information
managing data held in a relational database (tables in SQL) that is organized so that it can
management system (RDBMS), or for stream easily be accessed, managed, and updated”
processing in a relational data stream management - Table
system (RDSMS) a. The data in RDBMS is stored in database
- SQL consists of a data definition language (DDL), objects called tables.
data manipulation language (DML), and a data b. A table is a collection of related data entries
control language (DCL) and it consists of columns and rows
- SQL syntax - Index
a. SQL query consists of different clauses, a. Indexes help us retrieve data from tables
expressions which together form a statement quicker
b. Insignificant whitespace is generally ignored in b. With the proper index in place, the database
SQL statements and queries, making it easier to system can then first go through the index to
format SQL code for readability find out where to retrieve the data, and then
c. SQL is NOT case sensitive: select is the same as go to these locations directly to get the
SELECT needed data
d. SQL statements also include the semicolon (;) - DDL (Data Definition / Description Language)
statement terminator. Though not required on a. Is a syntax similar to a computer
every platform, it is defined as a standard part of programming language for defining data
the SQL grammar. structures, database schemas.
- Example b. It includes :
Db: Employee 1) CREATE – creates a new database /
ID Name Desgn City Dept table
101 Nigel Manager Hyderaba Operations
d
2) ALTER – modifies a database / table
102 Yogesh Developer New York IT 3) DROP – deletes a database / table
103 Timir Marketing London Marketing - DML (Data Manipulation Language)
Lead a. Is the subset of SQL used to add, update and
104 Avinash Developer Mumbai IT
delete data
SELECT ID, Name FROM Employee; b. It includes :
1) SELECT – extracts data from a database
Output : 2) UPDATE – updates data in a database
3) DELETE – deletes data from a database
ID Name 4) INSERT – inserts new data into a
101 Nigel database
102 Yogesh - DCL (Data Control Language)
103 Timir a. Is a syntax similar to a computer
104 Avinash programming language used to control
access to data stored in a database
(authorization).
b. The operations for which privileges may be
granted to or revoked from a user or role
may include CONNECT, SELECT,
INSERT, UPDATE, DELETE, EXECUTE,
and USAGE.
c. Examples of DCL commands include :
1) GRANT – allow specified users to
perform specified tasks
2) REVOKE – cancel previously granted or
denied permissions.
Data Definition Language (DDL) Data Manipulation Language (DML)
- Create - Select Clause
a. Create database - Where Clause
Stx : - Order By Clause
- Alias Name
CREATE DATABASE dbname; - Column Function
- Group By Clause
Note: - Having Clause
Dbname can have alphanumeric values, can have - Joins
underscore. Whitespace are not allowed - Union
- Subqueries
Example - Insert
CREATE DATABASE ProgrammingHub; - Delete
CREATE DATABASE Programming_Hub; - Update
b. Create table
Stx :

CREATE TABLE table_name


(
column_name1 data_type(size) [contrain_type],
column_name2 data_type(size) [contrain_type],
column_name3 data_type(size) [contrain_type],
);

Example
1. Simple statement without any constraint

CREATE TABLE Employee(


ID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

2. Statement with constraint

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)
);

c. Create index
Note* :
1. a column which is set as Primary Key is
already indexed by default
2. index should be used on column which he
frequently queried on
3. avoid using index on columns which have
large amount of null values
4. index should be avoided on small tables
Stx :
1) To create an index which will have duplicate
values in the column_name

CREATE INDEX index_name


ON table_name(column_name1,
column_name2)

2) To create a unique index on a table. Duplicate


values are not allowed

CREATE UNIQUE INDEX index_name


ON table_name(column_name)

Example
1. Index on one column

CREATE INDEX EIndex


ON Employee(ID);

2. Index on multiple column

CREATE INDEX EIndex


ON Employee(LastName, FirstName);

- Alter
a. ALTER TABLE statement is used to add, delete,
or modify columns in an existing table
b. ALTER TABLE is also used to add and drop
various constraints on an existing table
c. Syntax
1. Add column

ALTER TABLE table_name


ADD column_name datatype;

2. Drop column

ALTER TABLE table_name


DROP COLUMN column_name;

3. Alter / modify column

a) SQL server / MS access

ALTER TABLE table_name


ALTER COLUMN column_name
datatype;
b) MySQL / Oracle (prior version 10G)

ALTER TABLE table_name


MODIFY COLUMN column_name
datatype;

c) Oracle 10G and later

ALTER TABLE table_name


MODIFY column_name datatype;

d. Example

Db : Persons
ID LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Add column
Now we want to add a column named “DateOfBirth” in
the “Persons” table

ALTER TABLE Persons


ADD DateOfBirth date;

Db : Persons
ID LastName FirstName Address City DateOfBirth
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Note* notice that the new column, “DateOfBirth” is of


type date and is going to hold a date. The data type
specifies what type of data the column can hold.

Change data type


Now we want to change the data type of the column
named “DateOfBirth” in the “Persons” table

ALTER TABLE Persons


ALTER COLUMN DateOfBirth year;

Db : Persons
ID LastName FirstName Address City DateOfBirth
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Note* notice that the, “DateOfBirth” column is now of


type year and is going to hold a year in a two – or four –
digit format
Drop column
Next, we want to delete the column name “DateOfBirth"
in the “Persons” table.

ALTER TABLE Persons


DROP COLUMN DateOfBirth;

Db : Persons
ID LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

- Drop
1. Drop database
a. Drop database will delete the complete
database along with its components
b. You need to have admin privilege to perform
this action
c. To verify if the database is deleted you can
run the command SHOW DATABASE
d. Syntax :

DROP DATABASE database_name;

e. Example

DROP DATABASE Programming_Hub;

2. Drop table
1) Remove the table from the database
a. Drop table is used when we want to
remove the table from the database
b. All the table’s rows, indexes and
privileges will also be removed
c. No DML (Data Manipulation Language)
triggers will be fired
d. The operation cannont be rolled back
e. Syntax

DROP TABLE table_name;

2) Delete the data inside the table, and not the


table itself
a. When we only want to delete the data
inside the table, and not the table itself, we
use truncate statement
b. The operation cannot be rolled back and
no triggers will be fired
c. Is faster and free up space
d. Syntax

TRUNCATE TABLE table_name


Example

DROP TABLE Employee;


TRUNCATE TABLE Employee;

3. Drop index
a. Index can also be dropped using alter table
statement
b. Syntax

DROP INDEX index_name;

c. Example

DROP INDEX EIndex;

- Miscellaneous
1. Table constraints
a. To preserve the consistency and correctness
of the stored data, a relational DBMS imposes
one or more data integrity constraints. These
constraints restrict the data values that can be
inserted into the database or created by a
database update. Different types of data
integrity constraints are:
1) NOT NULL – implies that the column
cannot store null values
 Adding NOT NULL using create table
statement
 Syntax

CREATE TABLE table_name


(
column_name datatype NOT NULL,
.
.
);

 Example

CREATE TABLE Employee


(
ID INT NOT NULL,
.
.
);

2) UNIQUE – ensures that each row for a


column must have a unique value
 Adding UNIQUE using create table
statement
CREATE TABLE Employee
(
P_Id int NOT NULL UNIQUE,
.
.
.
);

CREATE TABLE Employee


(
Id int NOT NULL,
LastName varchar(255) NOT NULL,
.
.
.
CONSTRAINT un_EmpID UNIQUE
(Id, LastName)
);

Note : All UNIQUE constraint must


be NOT NULL

 Adding UNIQUE using alter statement

ALTER TABLE Employee


ADD CONSTRAINT un_EmpID
UNIQUE (Id);

ALTER TABLE Employee


ADD CONSTRAINT un_EmpID
UNIQUE (Id, Name);

 Droping a UNIQUE Constrain

ALTER TABLE Employee


DROP CONSTRAINT un_EmpID;

3) PRIMARY KEY – the primary key has a


different unique value for each row in a
table, so no two rows of a table with a
primary key are exact duplicates of one
another
 Adding PRIMARY KEY using create
table statement

CREATE TABLE Employee


(
P_Id int PRIMARY KEY,
.
.
.
);
CREATE TABLE Employee
(
Id int NOT NULL,
LastName varchar(255) NOT NULL,
.
.
.
CONSTRAINT pk_EmpID
PRIMARY KEY (Id, LastName)
);

 Adding PRIMARY KEY using alter


statement

ALTER TABLE Employee


ADD CONSTRAINT pk_EmpID
PRIMARY KEY (Id);

ALTER TABLE Employee


ADD CONSTRAINT pk_EmpID
PRIMARY KEY (Id, Name);

 Droping a PRIMARY KEY constrain

ALTER TABLE Employee


DROP CONSTRAINT pk_EmpID;

4) FOREIGN KEY – it takes care of the


referential integrity of the data in one table
to match values in another table
 Together, a primary key and a foreign
key create a parent / child relationship
between the tables that contain them,
just like the parent / child relationships
in a hierarchical
 A table can contain more than one
foreign key if it is related to more than
one other table
 For example, in the sample database,
each salesperson is assigned to a
particular sales office, so there is an
obvious relationship between the rows
of the OFFICES table and the rows of
the SALESREPS table
 The REP_OFFICE column is a foreign
key for the OFFICES table
 Although REP_OFFICE is a column
in the SALESREPS table, the values
that this column contains are office
numbers. They match values in the
OFFICE column, which is the primary
key for the OFFICES table
 Adding FOREIGN KEY using create
table statement

(checkpoint)2

 Adding FOREIGN KEY using alter


statement

 Droping a FOREIGN KEY constrain

5) CHECK – ensures that the value in a


column meets a specific condition

6) DEFAULT – specifies a default value


when specified none for this column

2. Data types in SQL

https://www.w3schools.com/sql/sql_datatypes.asp
No DataType Description
Fixed – length character
1 CHAR(len)
strings
2 CHARACTER(len)
Variable – length
3 VARCHAR(len)
character strings
4 CHAR VARYING(len)
CHARACTER
5
VARYING(len)
Fixed – length national
6 NCHAR(len)
character strings
7 NATIONAL CHAR(len)
NATIONAL
8
CHARACTER(len)
Variable – length
9 NCHAR VARYING(len)
national character strings
NATIONAL CHAR
10
VARYING(len)
NATIONAL
11 CHARACTER
VARYING(len)
12 INTEGER INT Integer numbers
13 SMALL INT Small integer numbers
14 BIT(len) Fixed – length bit strings
Variable – length bit
15 BIT VARYING(len)
strings
NUMERIC(precision,
16 Decimal numbers
scale)
17 DECIMAL(precision, scale)
18 DEC(precision, scale)
19 FLOAT(precision) Floating point numbers
Low – precision floating
20 REAL
point numbers
High – precision floating
21 DOUBLE PRECISION
point numbers
22 DATE Calendar dates
23 TIME(precision) Clock times
24 TIMESTAMP(precision) Dates and times
25 INTERVAL Time intervals

Example
CREATE TABLE Employee(
ID INT,
NAME VARCHAR(20),
AGE INT,
ADDRESS CHAR(25),
SALARY DECIMAL(18, 2),
date_of_birth DATE
);

Output :
Db : Employee
ID NAME AGE ADDRESS SALARY date_of_birth
1 Achmad 25 Taman 27.000.000 1997-04-05
ubud
2 Nafisah 23 Bogor 6.500.000 1998-12-13
3. Views

You might also like