SQL Part1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

STRUCTURED QUERY LANGUAGE

(SQL)

PART - 1

www.linkedin.com/in/sushmithadogga
1. SQL INTRODUCTION

● SQL is one of the most important programming languages to know if you work with data.
● SQL stands for Structured Query Language .
● It is a standard language for storing, accessing and manipulating data in a relational database
management system (RDMS).
● SQL allows you to query the database in a variety of ways, using English-like statements.
● It is used on websites for back-end data storage and data processing solutions.
● SQL provides CRUD functionality for databases. CRUD stands for
Create, Read, Update, Delete.

SQL comprises 4 major sub-languages:

Data Definition Language(DDL): to create, alter, and drop database objects.

Data Manipulation Language(DML): to insert, update and delete the existing records
from the database.

Data Query Language(DQL): to fetch the data from the database.

Data Control Language(DCL): to grant or revoke user access privileges to a database.

www.linkedin.com/in/sushmithadogga
2. DATA DEFINITION LANGUAGE

Data definition language (DDL) is a set of SQL commands used to create, modify, and delete
the structure of database objects but not data. These database objects include schemas, tables,
views, sequences, catalogs, indexes, variables, masks, permissions, and aliases.

The DDL commands include:

create, alter, drop, truncate, comment, rename

2.1 Create a Database:

CREATE DATABASE db1;

The CREATE DATABASE statement is used to create a new SQL database named db1.

2.2 Create a table:

USE db1;

CREATE TABLE tb1 (

column1 datatype,

column2 datatype, ....);

The CREATE TABLE statement is used to create a new table named tb1.

The USE statement is used to create the table within the db1 database.

www.linkedin.com/in/sushmithadogga
2.3 Data Types:

2.3.1 String Data Types:

Data type Description Max Size Storage

char(n) Fixed width 8,000 characters Defined width


character string

varchar(n) Variable width 8,000 characters 2 bytes + number of


character string chars

varchar(max) Variable width 1,073,741,824 2 bytes + number of


character string characters chars

text Variable width 2GB of text data 4 bytes + number of


character string chars

nchar Fixed width Unicode 4,000 characters Defined width x 2


string

nvarchar Variable width 4,000 characters


Unicode string

nvarchar(max) Variable width 536,870,912


Unicode string characters

ntext Variable width 2GB of text data


Unicode string

binary(n) Fixed width binary 8,000 bytes


string

varbinary Variable width 8,000 bytes


binary string

varbinary(max) Variable width 2GB


binary string

image Variable width 2GB


binary string

www.linkedin.com/in/sushmithadogga
2.3.2 Numeric Data Types:

Data Type Description Storage

bit Integer that can be 0, 1, or


NULL

tinyint Allows whole numbers from 1 byte


0 to 255

smallint Allows whole numbers 2 bytes


between -32,768 and 32,767

int Allows whole numbers 4 bytes


between -2,147,483,648 and
2,147,483,647

bigint Allows whole numbers 8 bytes


between
-9,223,372,036,854,775,808
and
9,223,372,036,854,775,807

smallmoney Monetary data from 4 bytes


-214,748.3648 to
214,748.3647

money Monetary data from


-922,337,203,685,477.5808 8 bytes
to 922,337,203,685,477.5807

real Floating precision number 4 bytes


data from -3.40E + 38 to
3.40E + 38
decimal(p,s) Fixed precision and scale 5-17 bytes
numbers.
Allows numbers from -10^38
+1 to 10^38 –1.

The p parameter indicates


the maximum total number
of digits that can be stored
(both to the left and to the
right of the decimal point). p
must be a value from 1 to 38.
Default is 18.

The s parameter indicates the


maximum number of digits
stored to the right of the
decimal point. s must be a
value from 0 to p. Default
value is 0

numeric(p,s) Fixed precision and scale 5-17 bytes


numbers.
Allows numbers from -10^38
+1 to 10^38 –1.

The p parameter indicates


the maximum total number
of digits that can be stored
(both to the left and to the
right of the decimal point). p
must be a value from 1 to 38.
Default is 18.

The s parameter indicates the


maximum number of digits
stored to the right of the
decimal point. s must be a
value from 0 to p. Default
value is 0

float(n) Floating precision number 4 or 8 bytes


data from -1.79E + 308 to
1.79E + 308.
The n parameter indicates
whether the field should hold
4 or 8 bytes. float(24) holds a
4-byte field and float(53)
holds an 8-byte field. Default
value of n is 53.

www.linkedin.com/in/sushmithadogga
2.3.3 Date and Time Data Types:

Data Type Description Storage

datetime From January 1, 1753 to 8 bytes


December 31, 9999 with an
accuracy of 3.33 milliseconds

datetime2 From January 1, 0001 to 6-8 bytes


December 31, 9999 with an
accuracy of 100 nanoseconds

smalldatetime From January 1, 1900 to 4 bytes


June 6, 2079 with an
accuracy of 1 minute

date Store a date only. From 3 bytes


January 1, 0001 to December
31, 9999

time Store a time only to an 3-5 bytes


accuracy of 100 nanoseconds

datetimeoffset The same as datetime2 with 8-10 bytes


the addition of a time zone
offset

timestamp Stores a unique number that


gets updated every time a
row gets created or modified.
The timestamp value is based
upon an internal clock and
does not correspond to real
time. Each table may have
only one timestamp variable

2.3.4 Other Data Types:

Data Type Description

sql_variant Stores up to 8,000 bytes of data of various


data types, except text, ntext, and timestamp

uniqueidentifier Stores a globally unique identifier (GUID)

xml Stores XML formatted data. Maximum 2GB

cursor Stores a reference to a cursor used for


database operations
table Stores a result-set for later processing

2.4 Constraints:

SQL constraints are used to specify rules for data in a table. Constraints can be specified either
when the table is created using CREATE TABLE statement or after the table is created using
ALTER TABLE statement.

CREATE TABLE tb1 (

column1 datatype constraint,

column2 datatype constraint, ....);

Constraints can be column level or table level. They limit the type of data that can go into a
table.

Most commonly used Constraints in SQL :

● NOT NULL - specifies that a column must not have NULL values
● UNIQUE - specifies that all values in a column must be different
● PRIMARY KEY - combination of NOT NULL and UNIQUE. It uniquely identifies each record in
a table
● FOREIGN KEY - refers to primary key of another table
● CHECK - enables a condition to check the value being entered into a record.
● DEFAULT - sets a default value for a column if no value is specified
● CREATE INDEX - creates index in tables to retrieve data from the database very quickly

www.linkedin.com/in/sushmithadogga
2.4.1 NOT NULL :

CREATE TABLE student (

ID int NOT NULL,

Name varchar(50) NOT NULL,

Class varchar(50) NOT NULL,

Marks int

);

To create a NOT NULL constraint on the "Marks" column when the "student" table is already
created, we use:

ALTER TABLE student

ALTER COLUMN Marks int NOT NULL;

2.4.2 UNIQUE :

There can be many UNIQUE constraints per table, but only one PRIMARY KEY constraint per
table.

CREATE TABLE student (

ID int NOT NULL,

Name varchar(50) NOT NULL,

Class varchar(50),

Marks int

);

To create a UNIQUE constraint on multiple columns, we use:

CREATE TABLE student (

ID int NOT NULL,

Name varchar(50) NOT NULL,

Class varchar(50),

Marks int

CONSTRAINT UC_student UNIQUE (ID,Name)


);

To create a UNIQUE constraint on the "ID" column when the “student” table is already created,
we use:

ALTER TABLE student

ADD UNIQUE (ID);

To create a UNIQUE constraint on multiple columns, when the “student” table is already
created, we use:

ALTER TABLE student

ADD CONSTRAINT UC_student UNIQUE (ID,Name);

To drop a UNIQUE constraint, we use:

ALTER TABLE student

DROP CONSTRAINT UC_student;

2.4.3 PRIMARY KEY :

● A table can have only one primary key.


● Primary keys contain only UNIQUE values, and cannot have any NULL values.

CREATE TABLE student (

ID int NOT NULL PRIMARY KEY,

Name varchar(50) NOT NULL,

Class varchar(50),

Marks int

);

www.linkedin.com/in/sushmithadogga
To create a PRIMARY KEY constraint on multiple columns, we use:

CREATE TABLE student (

ID int NOT NULL,

Name varchar(50) NOT NULL,

Class varchar(50),

Marks int,

CONSTRAINT PK_student PRIMARY KEY (ID,Name)

);

To create a PRIMARY KEY constraint on the "ID" column when the table “student” is already
created, we use:

ALTER TABLE student

ADD PRIMARY KEY (ID);

To create a PRIMARY KEY constraint on multiple columns,when the table “student” is already
created, we use:

ALTER TABLE student

ADD CONSTRAINT PK_student PRIMARY KEY (ID,Name);

To drop a PRIMARY KEY constraint, we use:

ALTER TABLE student

DROP CONSTRAINT PK_student;

2.4.4 FOREIGN KEY :

The table with the foreign key is called the child table, and the table with the primary key is
called the parent table.

www.linkedin.com/in/sushmithadogga
Here we have two tables:

Student table:

Student_id Name Class Marks

1 Air BatchA 85

2 Water BatchB 79

3 Land BatchC 67

Department table:

Department_id Department_name Student_id

10 ECE 2

11 CSE 1

12 IT 3

To create a FOREIGN KEY on the "Student_id" column when the "Department" table is
created, we use:

CREATE TABLE Department (

Department_id int NOT NULL PRIMARY KEY,

Department_name varchar(50) NOT NULL,

Student_id int FOREIGN KEY REFERENCES Student(Student_id));

To create a FOREIGN KEY constraint on the "Student_id" column when the "Department"
table is already created, we use:

ALTER TABLE Department

ADD CONSTRAINT FK_StudentDept

ADD FOREIGN KEY (Student_id) REFERENCES Student(Student_id);

To drop a FOREIGN KEY constraint, we use:

ALTER TABLE Department

DROP CONSTRAINT FK_StudentDept;


2.4.5 CHECK :

When a CHECK constraint is defined on a table it can limit the values in certain columns based
on values in other columns in the row.

To create a CHECK constraint on the "Marks" column when the "student" table is created to
allow only those values having Marks = 80 or more, we use:

CREATE TABLE student (

ID int NOT NULL,

Name varchar(50) NOT NULL,

Class varchar(50),

Marks int CHECK (Marks>=80)

);

To create a CHECK constraint on multiple columns, we use:

CREATE TABLE student (

ID int NOT NULL,

Name varchar(50) NOT NULL,

Class varchar(50),

Marks int,

CONSTRAINT CHK_student CHECK (Marks>=80 AND Name='Air')

);

To create a CHECK constraint on the "Marks" column when the “student” table is already
created, we use:

ALTER TABLE student

ADD CONSTRAINT CHK_student CHECK (Marks>=80);

To drop a CHECK constraint, we use:

ALTER TABLE student

DROP CONSTRAINT CHK_student;


2.4.6 DEFAULT :

All new records are added with the default value if no alternative value is specified.

To set a DEFAULT value for the "Marks" column when the "student" table is created, we use:

CREATE TABLE student (

ID int NOT NULL,

Name varchar(50) NOT NULL,

Class varchar(50),

Marks int DEFAULT 50,

);

To set a DEFAULT value for the "Marks" column when the "student" table is created, we use:

ALTER TABLE student

ADD CONSTRAINT df_Marks

DEFAULT 50 FOR Marks;

To drop a DEFAULT constraint, we use:

ALTER TABLE student

ALTER COLUMN Marks DROP DEFAULT;

2.4.7 CREATE INDEX :

Although we cannot see indexes, they are used to speed up searches and queries.

To create an index on any column, in the “student” table , we use:

CREATE INDEX idx_student

ON student (ID, Name);

To drop an index in a table, we use:

DROP INDEX student.idx_student;

www.linkedin.com/in/sushmithadogga
2.5 Create a View:

● Views are virtual tables based on the result-set of the SQL query.
● Views contain rows and columns like a real table.
● The fields in a view are fields from one or more real tables in the database.
● A view always displays the most recent data.
● Every time we run the query, the database recreates the view.

To create a view, we use:

CREATE VIEW v1 AS

SELECT column1, column2, ...

FROM tb1

WHERE condition;

To drop a view, we use:

DROP VIEW v1;

www.linkedin.com/in/sushmithadogga

You might also like