0% found this document useful (0 votes)
10 views

Chapter 6 the SQL Language Part I

Chapter 6 provides an overview of SQL (Structured Query Language), a standard language for accessing and manipulating relational databases. It covers the different types of SQL statements, including Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL), as well as the capabilities of SQL in managing database objects and data. Additionally, it discusses variations of SQL such as T-SQL for Microsoft SQL Server and provides examples of creating databases and tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Chapter 6 the SQL Language Part I

Chapter 6 provides an overview of SQL (Structured Query Language), a standard language for accessing and manipulating relational databases. It covers the different types of SQL statements, including Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL), as well as the capabilities of SQL in managing database objects and data. Additionally, it discusses variations of SQL such as T-SQL for Microsoft SQL Server and provides examples of creating databases and tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Chapter 6: SQL Language

 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.

Notes about SQL


 SQL is the designated language for getting information from a relational database.
 SQL says what information to get, rather than how to get it.
 Basic SQL is easy to learn.
 SQL empowers people by giving them control over information.
 SQL allows people to handle information in new ways.
 SQL makes information powerful by bringing it to people when they need it.

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.

There are five types of SQL statements. They are:

1. Data Definition Language (DDL)

2. Data Manipulation Language (DML)

3. Data Query Language (DQL) or Data Retrieval Language (DRL)

4. Transaction Control Language (TCL)

5. Data Control Language (DCL)

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.

The most important DDL commands in SQL are:

 CREATE DATABASE - creates a new database


 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
 RENAME

SQL Data Manipulation Language (DML)

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

 Used to manage transactions and ensure data integrity.


Examples:

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

Data Query Language (DQL) (Often grouped under DML)

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

Data Control Language (DCL)

 Used to define access permissions and security levels for a database.

Examples:

o GRANT: Gives specific privileges to users (e.g., GRANT SELECT ON


employees TO user1;).
o REVOKE: Removes privileges from users (e.g., REVOKE SELECT ON
employees FROM user1;).

4
MS SQL Server - Create Database
Database is a collection of objects such as table, view, stored procedure, function, trigger, etc.

In MS SQL Server, two types of databases are available.

 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).

Creating Database using SQL Server Management Studio


1. In Object Explorer, connect to an instance of the SQL Server Database Engine and then
expand that instance.

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.

T-SQL vs. Standard SQL


 Standard SQL: Defined by ANSI/ISO standards, portable across database systems (e.g., MySQL,
PostgreSQL, Oracle), but limited to core data manipulation and definition commands.
 T-SQL: Extends standard SQL with Microsoft-specific features, making it more powerful for SQL
Server but less portable to other database systems.

7
Feature Standard SQL T-SQL

Basic Queries Yes Yes

Stored Procedures No Yes

Error Handling Limited TRY...CATCH

Variables No Yes

Functions Yes (newer) Yes (enhanced)

Triggers Limited Yes

Creating Database Using SQL or T-SQL

The CREATE DATABASE Statement

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

Create Database statement with arguments:

CREATE DATABASE database_name


[ON
[PRIMARY] (NAME = logical_file_name,
FILENAME = 'physical_file_path',
SIZE = initial_size,
MAXSIZE = maximum_size,
FILEGROWTH = growth_increment)
]
[LOG ON
(
NAME = logical_log_name,
FILENAME = 'physical_log_path',
SIZE = initial_log_size,
MAXSIZE = maximum_log_size,
FILEGROWTH = log_growth_increment)

]
[WITH options]

Description of the arguments

 ON: Specifies the data file properties

 NAME: Logical name for the file


 FILENAME: Physical path and filename
 SIZE: Initial size (KB, MB, GB, TB)
 MAXSIZE: Maximum allowed size
 FILEGROWTH: How much to grow when more space is needed

9
 LOG ON: Specifies the transaction log file properties

 Same parameters as data file but for the log

 WITH: Additional database options

 CATALOG_COLLATION: Sets collation for system metadata


 Other possible options: DB_CHAINING, TRUSTWORTHY, etc.

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:

 File paths must exist on the SQL Server machine


 Size units can be KB, MB (default), GB, or TB
 If no parameters are specified after the database name, SQL Server uses default values
 The logical file name is the name used within SQL Server to refer to the file internally.
It’s an identifier or alias that SQL Server uses in its system catalogs and commands to
manage the file. It provides a way to reference the file in T-SQL scripts or queries
without needing to know its exact location on disk.

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)

Listing all databases in the SQL Server:

The following statement lists all databases in the SQL Server

SELECT
name
FROM
master.sys.databases
ORDER BY
name;

DROP DATABASE statement to delete a database

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:

DROP DATABASE [ IF EXISTS ]


database_name
[,database_name2,...];

Example:
1. drop database if exists sampledb;

2. drop database 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.

SQL CREATE SCHEMA

CREATE SCHEMA statement used to create a new schema in the current database.

Syntax

CREATE SCHEMA syntax is:

CREATE SCHEMA schemaname


[AUTHORIZATION ownername] GO;

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.

Here's the basic syntax for the CREATE TABLE statement:

CREATE TABLE [database_name.][schema_name.]table_name

(
field1 datatype [constraint] ,
field2 datatype [constraint ],
field3 datatype [constraint ]...
)

In this syntax:

 table_name is the name of the table you want to create.


 field1, field2, … are the field (or column) names of the table.
 Each table column is associated with a data type it can store and an optional rule for data.
In the database, we call this rule a constraint.

IF NOT EXISTS option

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:

CREATE TABLE IF NOT EXIST table_name (


column1 datatype constraint,
column2 datatype constraint,
...);

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:

CREATE TABLE courses (


name VARCHAR(255) NOT NULL,
description TEXT,
duration DEC(4, 2) NOT NULL
);
2. Create a table called BILLS that stores name, amount and account_id.
CREATE TABLE BILLS (
NAME CHAR(30),
AMOUNT NUMBER,
ACCOUNT_ID NUMBER
);
3. Create a table called foods that stores menu_item,
supplier_id,product_ocde,description,price and price increase..

create table foods


(
menu_item byte,
supplier_id varchar(3),
product_code varchar(2),
description varchar(20),
price money,
price_increase money );

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

Character string data type

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.

Non-Unicode Character Data Types

 These store text using a single-byte character encoding (e.g., ASCII or extended ASCII)

Fixed-length character data type

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)

 Variable-length string with a very large capacity.


 Length: Up to 231-1 characters (approximately 2 billion).

Varying-length character or VARCHAR

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:

CHARACTER VARYING (n)

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.

Unicode Character Data Types

These store text using a two-byte Unicode encoding (UTF-16), supporting a wide range of
international characters, symbols, and languages.

NCHAR(n)

Fixed-length Unicode string.


Length: n is the number of characters (1 to 4,000).
Storage: Exactly n * 2 bytes, padded with spaces if needed.
Use: Fixed-length text requiring Unicode, like standardized codes or names in multiple
languages.

Example: NCHAR(5) with " café" stores " café" (5 characters, 10 bytes)

17
NVARCHAR(n)

 Variable-length Unicode string.


 Length: n is the maximum number of characters (1 to 4,000).

NVARCHAR(max)

Variable-length Unicode string with large capacity.


Length: Up to 230-1 characters (approximately 1 billion).

Example: Creating table using different character types.


CREATE TABLE Employees (

EmployeeID CHAR(6), -- Fixed-length ID (e.g., "EMP001")

FirstName NVARCHAR(50), -- Variable-length Unicode name

Notes NVARCHAR(max), -- Large Unicode text for notes

Status VARCHAR(10), -- Variable-length status (e.g., "Active")

CountryCode NCHAR(2) -- Fixed-length Unicode country code (e.g., "JP")

);

Numeric Types

The following are the SQL numeric data types:

Exact Numeric Data Types

These store precise values without approximation, meaning they maintain exact precision and
scale.

BIT Data Type


Stores a single bit, which can have one of three possible values:

 0 (false/off)
 1 (true/on)
 NULL (undefined, if the column allows nulls)

18
TINYINT

 Range: 0 to 255 (unsigned)


 Storage: 1 byte
 Use: Small positive integers, like counts or flags (e.g., status codes).

SMALLINT

 Range: -32,768 to 32,767 (signed)


 Storage: 2 bytes
 Use: Small whole numbers, such as quantities or minor measurements.

INT (or INTEGER)

 Range: -2,147,483,648 to 2,147,483,647 (signed)


 Storage: 4 bytes
 Use: Standard integer type for general-purpose whole numbers (e.g., IDs, counters).

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.

DECIMAL (or NUMERIC)

 Syntax: DECIMAL(p, s) or NUMERIC(p, s)


o p (precision): Total number of digits (1 to 38).
o s (scale): Number of digits to the right of the decimal point.
 Storage: 5–17 bytes, depending on precision.
 Range: Depends on precision and scale (e.g., DECIMAL (5, 2) stores values from -
999.99 to 999.99).
 Use: Precise decimal numbers, such as currency or measurements requiring exact values

MONEY

Range: -922,337,203,685,477.5808 to 922,337,203,685,477.5807


Storage: 8 bytes
Use: Monetary values with 4 decimal places of precision (e.g., $1234.5678).
Note: Includes currency formatting when displayed.

 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).

 n = 1 to 24: Uses 4 bytes (single-precision, equivalent to REAL).


 n = 25 to 53: Uses 8 bytes (double-precision).
 If no n is specified, the default is 53 (8 bytes).
 Range: Approximately -1.79E+308 to 1.79E+308 (for 8 bytes)

Example: Creating table using different numeric types.

CREATE TABLE Products (


ProductID INT, -- Standard integer for ID
Quantity SMALLINT, -- Small whole number for stock
Price MONEY, -- Currency value
Discount DECIMAL(5,2), -- Precise decimal (e.g., 123.45)
Weight FLOAT, -- Approximate value for scientific measures
MaxCapacity BIGINT -- Large integer for big counts
);

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

Purpose: Stores both date and time.

Format: YYYY-MM-DD hh:mm:ss[.nnn]

Example: 2025-03-20 14:30:45.123

21
SMALLDATETIME

Purpose: A compact version of DATETIME with less precision and a smaller range.

Format: YYYY-MM-DD hh:mm:ss

Example: 2025-03-20 14:30:00

TIMESTAMP data type

The TIMESTAMP data type represents timestamp values which include both DATE and TIME values.

The TIMESTAMP values are specified in the following form:

TIMESTAMP 'YYYY-MM-DD HH:MM:SS'

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:

CREATE TABLE dbo.CustomerAddress


(
CustomerAddressID int IDENTITY(1,1),
AddressType char(4) NOT NULL,
PrimaryAddressFlag bit NOT NULL,
AddressLine1 varchar(30) NOT NULL,
AddressLine2 varchar(30) NULL,
AddressLine3 varchar(30) NULL,
City varchar(50) NOT NULL,
StateProvinceID int NULL,
PostalCode char(10) NULL,
CountryID int NULL
)

22
Implementing Constraints

1. NOT NULL constraint


In SQL, NULL means unknown value or missing data. If you define a table column without using
any constraint, it will accept NULL by default.
To ensure that the column cannot have NULL, you can use the NOT NULL constraint.

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:

CREATE TABLE candidates (


first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(512) NOT NULL,
phone VARCHAR(25) NOT NULL
);
The candidates table includes four columns with NOT NULL constraints. It means you cannot insert NULL into any
of this column.

Adding NOT NULL Constraint to an Existing Column

 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:

Step 1: Ensure No NULL Values Exist

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:

alter table student


alter column Email char(20) not null

2. Primary Key Constraints


a. Adding a primary key when creating a table

CREATE TABLE dept


(
dno int IDENTITY(1,1) PRIMARY KEY,
dname varchar(50) NOT NULL
)

b. Adding a primary key after a table created

This section shows how to add a primary key to a table, even after the table contains many rows
of data. The syntax is:

ALTER TABLE table_name


ADD CONSTRAINT name_of_the_constraint
PRIMARY KEY (list_of_columns_in_the_primary_key);

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.

alter table department


add constraint pk
primary key (dno);

24
Dropping primary key constraint

Method 1: Using the name of the constraint

alter table department


drop pk;

Method 2: Without using the name of the constraint

alter table dept


drop primary key;

alter table dept


add constraint pk1
primary key (dno);

3. Foreign Key Constraints


o You use foreign key constraints to implement a concept called referential integrity
o Foreign keys ensure that the values that can be entered in a particular column exist in
a specified table. Users cannot enter values in this column that do not exist in the
specified table.
Example:

create table stud(


id int primary key,
name nvarchar(15),
dnumber int references dept(dno) on update cascade on
delete cascade )

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
)

SQL FOREIGN KEY Constraint on ALTER TABLE

ALTER TABLE stud


ADD FOREIGN KEY (dnumber)
REFERENCES dept(dno)
OR
ALTER TABLE stud
ADD CONSTRAINT fk
FOREIGN KEY (dnumber)
REFERENCES dept(dno)

To DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE stud


DROP CONSTRAINT fk

4. Default Constraints

SQL DEFAULT Constraint

The DEFAULT constraint is used to insert a default value into a column.


The default value will be added to all new records, if no other value is specified.

26
SQL DEFAULT Constraint on CREATE TABLE

The following SQL creates a DEFAULT constraint on the "City" column when the "Persons"
table is created:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)

SQL DEFAULT Constraint on ALTER TABLE

To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:

ALTER TABLE table_name


ADD DEFAULT 'column_value' FOR column_name

Example:
create table student(
idno int , fname char(20),
sex char
);
Add ‘F’ as default value for sex column

ALTER TABLE student


ADD DEFAULT 'F' FOR sex

5. SQL CHECK Constraint


A CHECK constraint is used to enforce a condition on the values in a column or set of
columns, ensuring that only valid data is inserted or updated.
If you define a CHECK constraint on a single column it allows only certain values for this
column.
If you define a CHECK constraint on a table it can limit the values in certain columns based
on values in other columns in the row.

27
Syntax

You can add a CHECK constraint either when creating a table or later using ALTER TABLE

a. SQL CHECK Constraint on CREATE 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.

CREATE TABLE Persons


(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)

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:

ALTER TABLE Persons


ADD CHECK (P_Id>0)

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:

ALTER TABLE Persons


ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To DROP a CHECK Constraint

To drop a CHECK constraint, use the following SQL:

ALTER TABLE Persons


DROP CONSTRAINT chk_Person

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.

Creating a UNIQUE constraint

To create a unique constraint for a column, you use the following syntax:

CREATE TABLE table_name (


column1 datatype UNIQUE,
...);
Example:
create table student(
id int primary key ,
fname varchar(20),
sex char,
username varchar(50) unique,
constraint ck_id check(id>0)
);

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:

CREATE TABLE users (


id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username VARCHAR(25) NOT NULL,
password TEXT NOT NULL,
phone VARCHAR(20),
CONSTRAINT unique_username UNIQUE (username)
);

DROP TABLE Statement

The DROP TABLE statement is used to delete a table.

Syntax:

DROP TABLE table_name

DROP DATABASE Statement

The DROP DATABASE statement is used to delete a database.

DROP DATABASE database_name

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:

TRUNCATE TABLE table_name

SQL ALTER 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.

SQL ALTER TABLE Syntax

ALTER TABLE table_name


action;

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.

SQL allows you to perform the following actions:


 Adding a Column
 Dropping a Column
 Modifying a Column
 Renaming a Column
 Adding a Constraint
 Dropping a Constraint
 Renaming the Table
 Adding a Primary Key
 Dropping a Primary Key
 Adding a Foreign Key
 Dropping a Foreign Key

Adding a column

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype

31
Example:
create table student(
id int primary key,
fname varchar(30)
)

The following statement adds the sex column to the student table:

alter table student


add sex char;
The following statement adds the birth_date column to the student table:

ALTER TABLE student


ADD birth_date DATE NOT NULL;

Dropping a column
To remove a column in a table, use the following syntax :

ALTER TABLE table_name


DROP COLUMN column_name

Example:
The following query drops the sex column from the student table:

alter table student


drop column sex;

Modifying a column

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


ALTER COLUMN column_name datatype
Example:
The following statement changes the data type of sex column to VARCHAR(10):

alter table student


alter column sex varchar(10)

32
Adding a constraint

To add a new constraint to a table, you use the ADD CONSTRAINT clause:

ALTER TABLE table_name


ADD CONSTRAINT constraint_name constraint;

a. Adding a primary key

ALTER TABLE table_name


ADD PRIMARY KEY (column_name);

b. Adding a foreign key

ALTER TABLE table1


ADD CONSTRAINT constraint_name
FOREIGN KEY (column1) REFERENCES table2(column2);

Dropping a constraint

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

Dropping a primary key

ALTER TABLE table_name


DROP PRIMARY KEY;

Dropping a foreign key

ALTER TABLE table_name


DROP CONSTRAINT fk_nam

33
SQL CREATE INDEX Statement

The CREATE INDEX statement is used to create indexes in tables.


Indexes allow the database application to find data fast; without reading the whole table.

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.

SQL CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:


CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)

Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the
syntax for creating indexes in your database.

CREATE INDEX Example

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)

SQL DROP INDEX, DROP TABLE, and DROP DATABASE

Indexes, tables, and databases can easily be deleted/removed with the DROP statement.

The DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a table.
DROP INDEX Syntax for MS Access:
DROP INDEX index_name ON table_name
DROP INDEX Syntax for MS SQL Server:
DROP INDEX table_name.index_name
DROP INDEX Syntax for DB2/Oracle:
DROP INDEX index_name
DROP INDEX Syntax for MySQL:
ALTER TABLE table_name DROP INDEX index_name

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)

4) Create Dept table : Dept (deptno, dname, loc)


Create Emp table : Emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)

35
LAB PRACTICE ASSIGNMENT:

1. Create a table EMPLOYEE with following schema:


(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)
2. Add a new column; HIREDATE to the existing relation.

3. Change the datatype of JOB_ID from char to varchar2.

4. Change the name of column/field Emp_no to E_no.

5. Modify the column width of the job field of emp table

36

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy