Chapter 6 the SQL Language Part I
Chapter 6 the SQL Language Part I
The name SQL stands for Structured Query Language. It is pronounced “S-Q-L” and can
also be pronounced “sequel.”
SQL is a standard language for accessing and manipulating databases.
SQL is a computer language designed to get information from data that is stored in a relational
database.
SQL is different from most other computer languages. With SQL, you describe the type of
information you want. The computer then determines the best procedure to use to obtain it and
runs that procedure. This is called a declarative computer language because the focus is on the
result:
You specify what the result should look like. The computer is allowed to use any method of
processing as long as it obtains the correct result.
Most other computer languages are procedural. These are languages like C, Cobol, Java,
Assembler, Fortran, Visual Basic, and others. In these languages, you describe the procedure
that will be applied to the data; you do not describe the result. The result is whatever emerges
from applying the procedure to the data.
SQL is a nonprocedural language, in contrast to the procedural or third generation languages
(3GLs) such as COBOL and C that had been created up to that time.
SQL describes what data to retrieve, delete, or insert, rather than how to perform the
operation.
Two standards organizations, the American National Standards Institute (ANSI) and the
International Standards Organization (ISO), currently promote SQL standards to industry.
1
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
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:
MS SQL Server using T-SQL,
Oracle using PL/SQL,
MS Access version of SQL is called JET SQL (native format) etc.
2
Data Definition Language (DDL)
The Data Definition Language (DDL) is used to create and destroy database objects. It also defines
indexes (keys), specifies links between tables, and imposes constraints between tables.
These commands will primarily be used by database administrators during the setup and removal
phases of a database project.
Used to manipulate the data within a database. The Data Manipulation Language (DML)
is used to retrieve, insert and modify database information. These commands will be used
by all database users during the routine operation of the database
Examples:
o SELECT: Retrieves data from one or more tables (e.g., SELECT * FROM
employees ;).
o INSERT: Adds new rows to a table (e.g., INSERT INTO employees (id, name)
VALUES (1, 'John');).
o UPDATE: Modifies existing data (e.g., UPDATE employees SET name = 'Jane'
WHERE id = 1;).
o DELETE: Removes rows from a table (e.g., DELETE FROM employees
WHERE id = 1;).
3
Transaction Control Language (TCL)
o COMMIT: Saves all changes made during a transaction (e.g., COMMIT ;).
o ROLLBACK: Undoes changes made during a transaction (e.g., ROLLBACK ;).
o SAVEPOINT: Sets a point within a transaction to roll back to (e.g., SAVEPOINT
savepoint1;).
o SET TRANSACTION: Defines properties of a transaction (e.g., SET
TRANSACTION READ ONLY ;).
Specifically refers to querying or retrieving data. While technically part of DML, it’s
sometimes separated for clarity.
Example:
o SELECT: The primary command for querying data (e.g., SELECT name, salary
FROM employees WHERE salary > 50000;).
Examples:
4
MS SQL Server - Create Database
Database is a collection of objects such as table, view, stored procedure, function, trigger, etc.
System databases
User Databases
System Databases
System databases are created automatically when we install MS SQL Server. Following is a list
of system databases −
Master
Model
MSDB
Tempdb
User Databases
User databases are created by users (Administrators, developers, and testers who have access to
create databases).
5
2. Right-click Databases, and then select New Database.
3. In New Database, enter the database name field with your database name (example: to
create database with the name ‘Testdb’) and click OK. Testdb database will be created as
shown in the following snapshot.
6
Transact-SQL (T-SQL)
Transact-SQL (T-SQL) is an enhanced version of SQL tailored for Microsoft SQL Server. It adds
procedural programming, error handling, triggers, and other features to the standard SQL
foundation, making it a robust tool for database development and administration. While it’s
specific to Microsoft’s platforms, it’s widely used in industries relying on SQL Server for data
management.
7
Feature Standard SQL T-SQL
Variables No Yes
The syntax for the typical CREATE DATABASE statement looks like this:
SYNTAX:
CREATE DATABASE database_name
Example: Use SQL Server to create a database called PAYROLL
SQL> CREATE DATABASE PAYROLL;
This statement creates a database called "PAYROLL". Because no arguments have been
specified, the database data files and transaction logs will be created automatically in the default
location.
Adding Arguments
There are a number of optional arguments that you can supply with the CREATE DATABASE
command. You should check your database system's documentation for the specific arguments
supported and their usage, but here's an example of supplying arguments when creating a
database using Microsoft's SQL Server.
8
In this example, we are supplying the name and location of the database's data file and
transaction log. We are also specifying the initial size of these files (with the SIZE argument),
]
[WITH options]
9
LOG ON: Specifies the transaction log file properties
Example:
CREATE DATABASE CustomerDB
ON
(
NAME = CustomerDB_Data,
FILENAME = 'C:\SQLData\CustomerDB.mdf',
SIZE = 50MB
)
LOG ON
(
NAME = CustomerDB_Log,
FILENAME = 'C:\SQLData\CustomerDB.ldf',
SIZE = 10MB
);
Notes:
10
The physical file name is the actual file name and full path on the operating system's file
system where the database file is stored. It specifies the exact location and name of the
file on disk (e.g., a .mdf file for data or .ldf file for logs)
SELECT
name
FROM
master.sys.databases
ORDER BY
name;
To remove an existing database from a SQL Server instance, you use the DROP DATABASE
statement.
The DROP DATABASE statement allows you to delete one or more databases with the
following syntax:
Example:
1. drop database if exists sampledb;
11
CREATE SCHEMA in SQL Server
A schema is a collection of database objects like tables, triggers, stored procedures, etc. A
schema is connected with a user which is known as the schema owner. The database may
have one or more schema.
An object within a schema is qualified using the schema_name.object_name format like
sales.orders
Two tables in two schemas can share the same name so you may have hr.employees and
sales.employees.
CREATE SCHEMA statement used to create a new schema in the current database.
Syntax
Note:
SQL Server has some built-in schema, for example, dbo, guest, sys, and
INFORMATION_SCHEMA.
dbo is the default schema for a new database, owned by dbo user. While creating a new
user with CREATE USER command, the user will take dbo as its default schema.
Example:
CREATE SCHEMA customer_services;
GO
Once you execute the statement, you can find the newly created schema under the
Security > Schemas of the database name.
12
13
The CREATE TABLE Statement
Tables are used to store data in the database. Tables are uniquely named within a database and
schema. Each table contains one or more columns. And each column has an associated data type
that defines the kind of data it can store e.g., numbers, strings, or temporal data.
(
field1 datatype [constraint] ,
field2 datatype [constraint ],
field3 datatype [constraint ]...
)
In this syntax:
The database system will issue an error if you attempt to create a table that already exists. To
avoid the error, you can use the IF EXISTS option in the CREATE TABLE statement:
The CREATE TABLE statement with the IF NOT EXISTS option creates a table only when the table
does not exist.
14
If the table already exists, the database system may issue a warning or notice and won’t do
anything else.
Examples
1. Create a table called courses that stores the course name, description, and duration:
15
Data Types
Data types limit the type of data that you can store in a column and, in some cases, even limit the
range of possible values in the column. A data type specifies the type of data that column can hold
such as character strings, numeric values, and date time values. In a database, each column of a
table has a specific data type.
SQL supplies a set of basic data types that you can use for defining columns of tables. Below we
will cover the most commonly used SQL data types
The character string data type represents the character data type including fixed-length and
varying-length character types, with support for both non-Unicode and Unicode characters.
These store text using a single-byte character encoding (e.g., ASCII or extended ASCII)
The fixed-length character data type stores fixed-length character strings. The following
illustrates the SQL fixed-length character data type:
CHARACTER (n)
In this syntax, n represents the number of characters that the column can store. The n parameter
is optional. If you skip it, the database system uses one by default. Most database systems use
CHAR instead of CHARACTER for representing the fixed-length character data type:
CHAR (n)
Example:
column_name CHARACTER(5)
16
If you store a string whose length is two in the column above, then the database system will pad
the three spaces to the string to ensure that each value in a column has a fixed length of five.
VARCHAR (max)
To store varying-length strings in a column, you use the varying-length character data type. The
following shows the syntax of SQL varying-length character:
In this syntax, n represents the maximum number of characters that the column can store.
Most database systems use VARCHAR for representing the varying-length character data.
The following example defines a column with the VARCHAR data type:
first_name VARCHAR(50)
If you store a value whose length is 20 in the first_name column, the database system stores
that value without padding any spaces.
However, if you store a value whose length is greater than 50, the database system may issue an
error.
These store text using a two-byte Unicode encoding (UTF-16), supporting a wide range of
international characters, symbols, and languages.
NCHAR(n)
Example: NCHAR(5) with " café" stores " café" (5 characters, 10 bytes)
17
NVARCHAR(n)
NVARCHAR(max)
);
Numeric Types
These store precise values without approximation, meaning they maintain exact precision and
scale.
0 (false/off)
1 (true/on)
NULL (undefined, if the column allows nulls)
18
TINYINT
SMALLINT
BIGINT
Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (signed)
Storage: 8 bytes
Use: Large whole numbers, like financial calculations or unique identifiers over a massive
range.
MONEY
BIT(n)
BIT VARYING (n)
DECIMAL (p,s)
INTEGER
SMALLINT
BIGINT
19
Approximate Numeric Data Types
FLOAT(p,s)
FLOAT numeric data type used to store approximate numeric values, meaning they
represent numbers with a fractional component and are not exact due to their floating-point
nature.
FLOAT(p,s)
A floating-point data type that stores approximate numeric values with a configurable
precision.
It uses 4 or 8 bytes depending on the precision specified (single-precision or double-
precision).
Stores large floating numbers that exceed the capacity of a decimal data type.
Precision: You can define the number of bits used for the mantissa (significant digits) by
specifying a value n (from 1 to 53).
20
Date and Time types
The date and time data types are used to store information related to dates and times. SQL
supports the following date and time data types:
DATE
TIME
TIMESTAMP
DATE
Stores only the date (year, month, and day).
Range: January 1, 0001 to December 31, 9999
Storage Size: 3 bytes
Format: YYYY-MM-DD
Ideal for scenarios where only the date is needed, such as birthdates or event dates,
without time information.
Example: 2025-03-20
TIME
Purpose: Stores only the time of day (hours, minutes, seconds, and fractional seconds).
Format: hh:mm:ss[.nnnnnnn] (up to 7 decimal places for fractional seconds)
Useful for recording specific times, such as meeting schedules or log entry times, without
date information.
Example: 14:30:45.123456
DATETIME
21
SMALLDATETIME
Purpose: A compact version of DATETIME with less precision and a smaller range.
The TIMESTAMP data type represents timestamp values which include both DATE and TIME values.
Notice that there is a space separator between the date and time parts.
Identity
When defining columns, you also have the ability to specify a special identify property for a single
column in a table. Defining a column with the identity property causes SQL Server to generate an
automatically incrementing number. The identity property takes two parameters: seed and
increment. The seed value designates the starting value that SQL Server uses. The increment value
specifies what number SQL Server adds to this starting value when generating each successive
value. This property is equivalent to autonumber or autoincrement values in other languages.
Example:
22
Implementing Constraints
The NOT NULL constraint prevents inserting or updating NULL into a specified column. It is
helpful for defining important columns that should never be NULL.
To apply a NOT NULL constraint to a column, you use the following syntax:
column_name datatype NOT NULL
Example: The following creates a table called candidates table to store candidates:
If the table already exists, you can modify a column to add a NOT NULL constraint using the
ALTER TABLE statement. However, the column must not contain any NULL values before
you can apply the constraint. Here’s the process:
If the column currently allows NULLs and has NULL values, you need to update those to a
default value first. For example:
UPDATE student
SET Email = 'unknown@example.com'
WHERE Email IS NULL;
23
Step 2: Alter the Column
Once there are no NULL values, you can add the NOT NULL constraint:
This section shows how to add a primary key to a table, even after the table contains many rows
of data. The syntax is:
Remark: In Sql Server, the column to be used as Pk should defined as NOT NULL
The preceding command adds a constraint to a table and the type of constraint it adds is a
primary key constraint.
Example: Adding a primary key to a table after the table without primary key is created.
24
Dropping primary key constraint
OR
create table stud(
id int primary key,
name nvarchar(15),
dnumber int null foreign key(dnumber) references dept(dno)
on update cascade on delete cascade
)
25
OR
create table stud(
id int not null primary key,
name nvarchar(15),
dnumber int null ,
primary key(id),
CONSTRAINT fk foreign key(dnumber) references dept(dno)
On update cascade
On delete cascade
)
4. Default Constraints
26
SQL DEFAULT Constraint on CREATE TABLE
The following SQL creates a DEFAULT constraint on the "City" column when the "Persons"
table is created:
To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:
Example:
create table student(
idno int , fname char(20),
sex char
);
Add ‘F’ as default value for sex column
27
Syntax
You can add a CHECK constraint either when creating a table or later using ALTER TABLE
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table
is created. The CHECK constraint specifies that the column "P_Id" must only include integers
greater than 0.
28
b. SQL CHECK Constraint on ALTER TABLE
To create a CHECK constraint on the "P_Id" column when the table is already created, use the
following SQL:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
6. UNIQUE Constraint
In SQL, a UNIQUE constraint ensures that all values in a column or set of columns are unique
within the same table. A UNIQUE constraint helps you maintain the data integrity by preventing
duplicate values in the specified columns.In practice, you’ll find UNIQUE constraints helpful for
defining columns that require unique values like username and email.
To create a unique constraint for a column, you use the following syntax:
29
If a UNIQUE constraint includes more than one column, you can define a UNIQUE constraint as a
table constraint:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
UNIQUE (column1, column2)
);
Example:
create table student(
id int primary key ,
fname varchar(20),
sex char,
username varchar(50),
phone_number int,
constraint ck_id check(id>0),
unique(username,phone_number));
UNIQUE constraint name
When defining a unique constraint, you can optionally assign it a name using the CONSTRAINT
clause:
CONSTRAINT constraint_name
UNIQUE (column1, column2, ...);
Example:
Syntax:
30
TRUNCATE TABLE Statement
What if we only want to delete the data inside the table, and not the table itself?
Then, use the TRUNCATE TABLE statement:
The ALTER TABLE statement changes the structure of an existing table. It is used to add, delete, or
modify columns in an existing table.
In this syntax:
First, provide the name of the table you want to change in the ALTER TABLE clause.
Second, specify an action you want to perform.
Adding a column
31
Example:
create table student(
id int primary key,
fname varchar(30)
)
The following statement adds the sex column to the student table:
Dropping a column
To remove a column in a table, use the following syntax :
Example:
The following query drops the sex column from the student table:
Modifying a column
To change the data type of a column in a table, use the following syntax:
32
Adding a constraint
To add a new constraint to a table, you use the ADD CONSTRAINT clause:
Dropping a constraint
33
SQL CREATE INDEX Statement
Indexes
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So you should only create indexes on columns (and tables) that will
be frequently searched against.
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the
syntax for creating indexes in your database.
The SQL statement below creates an index named "PIndex" on the "LastName" column in the
"Persons" table:
CREATE INDEX PIndex
ON Persons (LastName)
If you want to create an index on a combination of columns, you can list the column names
within the parentheses, separated by commas:
34
CREATE INDEX PIndex
ON Persons (LastName, FirstName)
Indexes, tables, and databases can easily be deleted/removed with the DROP statement.
Exercise
1) Create an employee’s table with the following fields:
(Emp_id,First_name,Last_name,Phone_No,Hire_date,Job_id,Emp_Salary,Comission_Pct,manag
er_id,Department_id)
2) Create Teacher table with the following fields(Id,Name, DeptNo, Date of joining, DeptName,
Location, Salary)
3) Create a Sales Table with the following fields
(Sales_No,Sales_Name,Branch,Sales_Amount,DOB)
35
LAB PRACTICE ASSIGNMENT:
36