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

2 Unit-SQL BCS

SQL notes BCS

Uploaded by

kiranhandifod112
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

2 Unit-SQL BCS

SQL notes BCS

Uploaded by

kiranhandifod112
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

o SQL stands for Structured Query Language.

It is used for storing and managing data


in relational database management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create,
read, update and delete relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as
their standard database language.
o SQL allows users to query the database in a number of ways, using English-like
statements.

Rules:

SQL follows the following rules:

o Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase.
o Statements of SQL are dependent on text lines. We can use a single SQL statement
on one or multiple text line.
o Using the SQL statements, you can perform most of the actions in a database.
o SQL depends on tuple relational calculus and relational algebra.

Characteristics of SQL
o SQL is easy to learn.
o SQL is used to access data from relational database management systems.
o SQL can execute queries against the database.
o SQL is used to describe the data.
o SQL is used to define the data in the database and manipulate it when needed.
o SQL is used to create and drop the database and table.
o SQL is used to create a view, stored procedure, function in a database.
o SQL allows users to set permissions on tables, procedures, and views.

Advantages of SQL
There are the following advantages of SQL:

High speed

Using the SQL queries, the user can quickly and efficiently retrieve a large amount of
records from a database.

No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.

Well defined standards

Long established are used by the SQL databases that are being used by ISO and ANSI.

Portability

SQL can be used in laptop, PCs, server and even some mobile phones.

Interactive language

SQL is a domain language used to communicate with the database. It is also used to receive
answers to the complex questions in seconds.

Multiple data view

Using the SQL language, the users can make different views of the database structure.

SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.

Datatype of SQL:

1. Binary Datatypes
There are Three types of binary Datatypes which are given below:

Data Type Description

binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.

varbinary It has a maximum length of 8000 bytes. It contains variable-length binary


data.

image It has a maximum length of 2,147,483,647 bytes. It contains variable-length


binary data.

2. Approximate Numeric Datatype :

The subtypes are given below:

Data type From To Description

float -1.79E + 1.79E + It is used to specify a floating-point value e.g. 6.2,


308 308 2.9 etc.

real -3.40e + 3.40E + It specifies a single precision floating point number


38 38

3. Exact Numeric Datatype

The subtypes are given below:

Data type Description

int It is used to specify an integer value.

smallint It is used to specify small integer value.

bit It has the number of bits to store.

decimal It specifies a numeric value that can have a decimal number.


numeric It is used to specify a numeric value.

4. Character String Datatype

The subtypes are given below:

Data Description
type

char It has a maximum length of 8000 characters. It contains Fixed-length non-


unicode characters.

varchar It has a maximum length of 8000 characters. It contains variable-length non-


unicode characters.

text It has a maximum length of 2,147,483,647 characters. It contains variable-


length non-unicode characters.

5. Date and time Datatypes

The subtypes are given below:

Datatype Description

date It is used to store the year, month, and days value.

time It is used to store the hour, minute, and second values.

timestamp It stores the year, month, day, hour, minute, and the second value.

SQL | Constraints


Constraints are the rules that we can apply on the type of data in a table. That is, we
can specify the limit on the type of data that can be stored in a particular column in a
table using constraints.
The available constraints in SQL are:

 NOT NULL: This constraint tells that we cannot store a null value in a column. That
is, if a column is specified as NOT NULL then we will not be able to store null in this
particular column any more.
 UNIQUE: This constraint when specified with a column, tells that all the values in the
column must be unique. That is, the values in any row of a column must not be
repeated.
 PRIMARY KEY: A primary key is a field which can uniquely identify each row in a
table. And this constraint is used to specify a field in a table as primary key.
 FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a
another table. And this constraint is used to specify a field as Foreign key.
 CHECK: This constraint helps to validate the values of a column to meet a particular
condition. That is, it helps to ensure that the value stored in a column meets a
specific condition.
 DEFAULT: This constraint specifies a default value for the column when no value is
specified by the user.
How to specify constraints?
We can specify constraints at the time of creating the table using CREATE TABLE
statement. We can also specify the constraints after creating a table using ALTER TABLE
statement.
Syntax:
Below is the syntax to create constraints using CREATE TABLE statement at the time of
creating the table.

CREATE TABLE sample_table


(
column1 data_type(size) constraint_name,
column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name,
....
);

sample_table: Name of the table to be created.


data_type: Type of data that can be stored in the field.
constraint_name: Name of the constraint. for example- NOT NULL,
UNIQUE, PRIMARY KEY etc.
Let us see each of the constraint in detail.

1. NOT NULL –
If we specify a field in a table to be NOT NULL. Then the field will never accept null
value. That is, you will be not allowed to insert a new row in the table without specifying
any value to this field.
For example, the below query creates a table Student with the fields ID and NAME as
NOT NULL. That is, we are bound to specify values for these two fields every time we
wish to insert a new row.

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20)
);
2. UNIQUE –
This constraint helps to uniquely identify each row in the table. i.e. for a particular
column, all the rows should have unique values. We can have more than one UNIQUE
columns in a table.
For example, the below query creates a table Student where the field ID is specified as
UNIQUE. i.e, no two students can have the same ID. Unique constraint in detail.

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);
3. PRIMARY KEY –
Primary Key is a field which uniquely identifies each row in the table. If a field in a table
as primary key, then the field will not be able to contain NULL values as well as all the
rows should have unique values for this field. So, in other words we can say that this is
combination of NOT NULL and UNIQUE constraints.
A table can have only one field as primary key. Below query will create a table named
Student and specifies the field ID as primary key.

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);
4. FOREIGN KEY –
Foreign Key is a field in a table which uniquely identifies each row of a another table.
That is, this field points to primary key of another table. This usually creates a kind of
link between the tables.
Consider the two tables as shown below:

Orders

O_I
D ORDER_NO C_ID

1 2253 3

2 3325 3

3 4521 2

4 8532 1

Customers

C_ID NAME ADDRESS

1 RAMESH DELHI

2 SURESH NOIDA

3 DHARMESH GURGAON

As we can see clearly that the field C_ID in Orders table is the primary key in Customers
table, i.e. it uniquely identifies each row in the Customers table. Therefore, it is a
Foreign Key in Orders table.
Syntax:

CREATE TABLE Orders


(
O_ID int NOT NULL,
ORDER_NO int NOT NULL,
C_ID int,
PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)
)
(i) CHECK –
Using the CHECK constraint we can specify a condition for a field, which should be
satisfied at the time of entering values for this field.
For example, the below query creates a table Student and specifies the condition for the
field AGE as (AGE >= 18 ). That is, the user will not be allowed to enter any record in
the table with AGE < 18. Check constraint in detail

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);
(ii) DEFAULT –
This constraint is used to provide a default value for the fields. That is, if at the time of
entering new records in the table if the user does not specify any value for these fields
then the default value will be assigned to them.
For example, the below query will create a table named Student and specify the default
value for the field AGE as 18.

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);

SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is
also used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)

o DDL changes the structure of the table like creating a table, deleting a table, altering
a table, etc.
o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP
o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:

1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);


Example:

1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

1. DROP TABLE table_name;

Example

1. DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.

Syntax:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

1. ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));


2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space containing
the table.

Syntax:

1. TRUNCATE TABLE table_name;

Example:

1. TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language

o DML commands are used to modify the database. It is responsible for all form of
changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.

Syntax:

1. INSERT INTO TABLE_NAME


2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);

Or

1. INSERT INTO TABLE_NAME


2. VALUES (value1, value2, value3, .... valueN);

For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

INSERT INTO Syntax


The syntax of the SQL INSERT INTO statement is:

INSERT INTO table_name(column1, column2, column3, ...)


VALUES
(value11, value12, value13, ...)
(value21, value22, value23, ...)
... ;

Here,

 table_name is the name of the table into which the rows are to be inserted
 column1, column2, column3, ... are the names of columns where the values are to be
inserted
 value11, value12, value13, ... , value21, value22, value23, ... are the values to be
inserted
Insert Row Into a Table
In SQL, the INSERT INTO statement is used to insert new row(s) into a database table.
For example,
-- insert a row in the Customers table
INSERT INTO Customers(customer_id, first_name, last_name, age, country)
VALUES
(5, 'Harry', 'Potter', 31, 'USA');
Run Code

Here, the SQL command inserts a new row into the Customers table with the given values.
Exa
mple: SQL Insert Into

Skip Auto Incremented Fields While Inserting a Row


In a database table, the ID field is usually unique and auto incremented. In such cases, we
can omit the value for that column during row insertion. For example,
-- insert a row to Customers table
-- skip auto incremented customer_id column
INSERT INTO Customers(first_name, last_name, age, country)
VALUES
('James', 'Bond', 48, 'USA');
Run Code

Here, the SQL command automatically sets the new customer_id for the new row and
inserts it in a table.

Exa
mple: SQL INSERT INTO

Note: If we want to insert data from any other existing table, we can use the SQL INSERT
INTO SELECT statement.
Insert Multiple Rows at Once in SQL
It's also possible to insert multiple rows to a database table at once. For example,
INSERT INTO Customers(first_name, last_name, age, country)
VALUES
('Harry', 'Potter', 31, 'USA'),
('Chris', 'Hemsworth', 43, 'USA'),
('Tom', 'Holland', 26, 'UK');
Run Code

Here, the SQL command inserts three rows to the Customers table.

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CON


DITION]

For example:

1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'

Update a Single Value in a Row


In SQL, a single value can be updated by using the UPDATE command with the WHERE clause.
For example,
-- update a single value in the given row
UPDATE Customers
SET first_name = 'Johnny'
WHERE customer_id = 1;
Run Code

Here, the SQL command changes the value of the first_name column
to Johnny if customer_id is equal to 1.
Exa
mple: SQL UPDATE Statement

Note: If we want to insert a new row instead of updating an existing row, we can use
the SQL INSERT INTO statement.
Update Multiple Values in a Row
We can also update multiple values in a single row at once. For example,
-- update multiple values in the given row
UPDATE Customers
SET first_name = 'Johnny', last_name = 'Depp'
WHERE customer_id = 1;
Run Code

Here, the SQL command changes the value of the first_name column
to Johnny and last_name to Depp if customer_id is equal to 1.

Update Multiple Rows


The UPDATE statement can update multiple rows at once. For example,
-- update multiple rows satisfying the condition
UPDATE Customers
SET country = 'NP'
WHERE age = 22;
Run Code

Here, the SQL command changes the value of the country column to NP if age is 22. If
there are more than one rows where age equals to 22, all the matching rows will be edited.

Update all Rows


We can update all the rows in a table at once by omitting the WHERE clause. For example,
-- update all rows
UPDATE Customers
SET country = 'NP';
Run Code

Here, the SQL command changes the value of the country column to NP for all rows.
Note: We should be cautious while using the UPDATE statement. If we omit the WHERE clause,
all the rows will be changed and this change is irreversible.

4.

c. DELETE: It is used to remove one or more row from a table.

Syntax:

1. DELETE FROM table_name [WHERE condition];

For example:

1. DELETE FROM javatpoint


2. WHERE Author="Sonoo";

3. Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

b. Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be
used while creating tables or dropping them.

Here are some commands that come under TCL:


o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

1. COMMIT;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.

Syntax:

1. ROLLBACK;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.

Syntax:

1. SAVEPOINT SAVEPOINT_NAME;

5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

a. SELECT: This is the same as the projection operation of relational algebra. It is used to
select the attribute based on the condition described by WHERE clause.
Syntax:

1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;

For example:

1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
DDL DML
Used to define database objects like tables,
Used to manipulate data within the database.
indexes, views, etc.
Examples of DDL statements include Examples of DML statements include SELECT,
CREATE, ALTER, and DROP. INSERT, UPDATE, and DELETE.
Changes made using DDL affect the Changes made using DML affect the data
structure of the database. stored in the database.
DDL statements are not transactional, DML statements are transactional, meaning
meaning they cannot be rolled back. they can be rolled back if necessary.

Parameters DELETE Command DROP Command TRUNCATE Command


The TRUNCATE
The DELETE command The DROP command is Data
command is a Data
Language is Data Manipulation Definition Language
Definition Language
Language Command. Command.
Command.
The TRUNCATE
The DELETE command
The DROP Command drops Command deletes all the
deletes one or more
Use the complete table from the rows from the existing
existing records from the
database. table, leaving the row with
table in the database.
the column names.
We can restore any
We cannot get the complete We cannot restore all the
deleted row or multiple
table deleted from the deleted rows from the
Transition rows from the database
database using the database using the
using the ROLLBACK
ROLLBACK command. ROLLBACK command.
command.
The DELETE command The TRUNCATE
The DROP command
Memory does not free the command does not free the
removes the space allocated
Space allocated space of the space allocated for the
for the table from memory.
table from memory. table from memory.
Parameters DELETE Command DROP Command TRUNCATE Command
The DROP Command has
The DELETE command The TRUNCATE
faster performance than
performs slower than the command works faster
DELETE Command but not
DROP command and than the DROP command
Performance as compared to the Truncate
TRUNCATE command and DELETE command
Speed Command because the DROP
as it deletes one or more because it deletes all the
command deletes the table
rows based on a specific records from the table
from the database after
condition. without any condition.
deleting the rows.
The Integrity Constraints
The Integrity Constraints The Integrity Constraints get
Integrity will not get removed from
remain the same in the removed for the DROP
Constraints the TRUNCATE
DELETE command. command.
command.
We need ALTER permission
DELETE permission is on the schema to which the We need table ALTER
Permission required to delete the table belongs and CONTROL permission to use the
rows of the table. permission on the table to use TRUNCATE command.
the DROP command.
DELETE FROM
TRUNCATE TABLE
Syntax table_name WHERE DROP TABLE table_name;
table_name;
condition;

You might also like