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

SQL Statements (1)

SQL, or Structured Query Language, is the standard language for managing and querying relational databases. It includes various commands categorized into data definition, manipulation, control, and transactional control languages, allowing users to create, update, and manage database structures and data. Key concepts include constraints for data integrity, query types for data retrieval, and commands for table creation and modification.

Uploaded by

ayushjhavns
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL Statements (1)

SQL, or Structured Query Language, is the standard language for managing and querying relational databases. It includes various commands categorized into data definition, manipulation, control, and transactional control languages, allowing users to create, update, and manage database structures and data. Key concepts include constraints for data integrity, query types for data retrieval, and commands for table creation and modification.

Uploaded by

ayushjhavns
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Structured Query Language

SQL
SQL: Structured Query Language
SQL stands for Structured Query Language
Database management Language
SQL has become the de facto standard
language for creating and querying relational
databases.
ANSI (American National Standards
Institute) Standarad
Who should learn SQL?
Who should learn SQL?
i) Database Developers

 Design and deploy Database table structures, forms, reports and


queries etc…

ii) Database Administrators (DBA)

 Keeping databases up to date and managing database access


 Writing Reports, documentation and operating manuals

iii) Database Testers

 Verify Data Integrity


 Verify Data Manipulations (Add, Update and Delete)
 Verify Data comparisons
SQL
SQL Commands
SQL commands can be classified into 4 types
data definition language (DDL)
 create, alter, and drop tables, views, and indexes
data manipulation language (DML)
 updating, inserting, modifying, and querying the data in
the database.
data control language (DcL)
 Commands used to control a database, including those for
administering privileges. Granting and revoking the access
transactional Control Language (TCL)
 COMMIT, ROLLBACK statements
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 Data types
Constraints
SQL Constraints are rules used to limit the type of
data that can go into a table, to maintain the
accuracy and integrity of the data inside table.

Constraints can be specified when the table is created


with the CREATE TABLE statement, or after the table
is created with the ALTER TABLE statement.
Constraints
The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value

 UNIQUE - Ensures that all values in a column are different

 PRIMARY KEY- A combination of a NOT NULL and UNIQUE.


Uniquely identifies each row in a table

 FOREIGN KEY- Uniquely identifies a row/record in another table

 CHECK- Ensures that all values in a column satisfies a specific


condition

 DEFAULT- Sets a default value for a column when no value is specified


Query
A query is a request for data or information
from a database table or combination of tables.

 A database query can be either a select query


or an action query.

A select query is a data retrieval query, while an


action query asks for additional operations on
the data, such as insertion, updating or deletion

Queries can also calculate or summarize data


Data Definition Language
Data Type
SQLite uses dynamic type system.
For example, the value stored in a column
determines its data type, not the column’s data
type
Data types
Null Values :Unknown or Missing Information -
without quotes
Integer: Whole Number
Real :Decimal Number
Text :Characters -enclosed by single or double
quotes
Blob: Images, Audio,Video
typeof() function allows to check the datatype
Create Table
 The CREATE TABLE statement is used to create a new
table in a database.
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Primary Key
In the column definition itself:

ColumnName INTEGER NOT NULL PRIMARY KEY;

CREATE TABLE table_name(


column_1 INTEGER NOT NULL PRIMARY KEY, ...);

 As a separate definition:

PRIMARY KEY(ColumnName);

CREATE TABLE table_name(


column_1 INTEGER NOT NULL,
column_2 INTEGER NOT NULL, ...
PRIMARY KEY(column_1));

 To create a combination of columns as a primary key:

PRIMARY KEY(ColumnName1, ColumnName2);

CREATE TABLE table_name(


column_1 INTEGER NOT NULL,
column_2 INTEGER NOT NULL, ...
PRIMARY KEY(column_1,column_2,...)
);
Foreign Key
 CREATE TABLE table_name
( column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
... FOREIGN KEY (column1) REFERENCES table name (column1) );

 CREATE TABLE table_name


( column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
... FOREIGN KEY (column1,column2) REFERENCES table
name (column1,column2) );

 CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),FOREIGN KEY (PersonID) REFERENCES P
ersons(PersonID)
);
Constraints
Not Null
 By default, all columns in a table accept NULL values except you
explicitly use NOT NULL constraints

CREATE TABLE table_name ( ..., column_name type_name


NOT NULL, ...);

Once a NOT NULL constraint is attached to a column, any


attempt to set the column value to NULL such as inserting or
updating will cause a constraint violation.

CREATE TABLE suppliers(supplier_id INTEGER PRIMARY


KEY, name TEXT NOT NULL);

INSERT INTO suppliers(name)------------Error constraint viola-


tion
Constraints
 Unique
 Ensures all values in a column or a group of columns are distinct from one another or unique.

CREATE TABLE table_name( ...,column_name type UNIQUE, ...);

CREATE TABLE table_name( ..., UNIQUE(column_name1,column_name2,...));

Once a UNIQUE constraint is defined, if you attempt to insert or update a value that already
exists in the column, SQLite will issue an error and abort the operation.

 CREATE TABLE contacts(


contact_id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT NOT NULL UNIQUE);

INSERT INTO contacts(first_name,last_name,email)VALUES


('John','Doe','[email protected]');

INSERT INTO contacts(first_name,last_name,email)VALUES


('Johnny','Doe','[email protected]');
Create Table
CREATE TABLE [IF NOT EXISTS] table_name
(column_1 data_type PRIMARY KEY,
column_2 data_type NOT NULL,
column_3 data_type DEFAULT 0,
table_constraint )

For e.g.
The contacts table stores contact information.
The groups table stores group information.
The contact_groups table stores the relationship
between contacts and groups.
Create Table
 CREATE TABLE contacts (contact_id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
email text NOT NULL UNIQUE,
phone text NOT NULL UNIQUE);

 CREATE TABLE groups ( group_id integer PRIMARY KEY, name


text NOT NULL);

 CREATE TABLE contact_groups (contact_id integer,


group_id integer, PRIMARY KEY (contact_id, group_id),
FOREIGN KEY (contact_id) REFERENCES contacts (contact_id)
ON DELETE CASCADE ON UPDATE NO ACTION,
FOREIGN KEY (group_id) REFERENCES groups (group_id)
ON DELETE CASCADE ON UPDATE NO ACTION);
Create Table
ON DELETE CASCADE (when a referenced parent
table row is removed all the child are removed
automatically)

ON DELETE NO ACTION (which is the default)


prevents deleting a parent when there are children

ON UPDATE CASCADE means that if the parent


primary key is changed, the child value will also
change to reflect that.

ON UPDATE NO ACTION (which is the default)


prevents updating a parent when there are
children
countries
country_id INTEGER ,PRIMARY
KEY

name text ,NOT NULL

languages
language_id PRIMARY KEY ,integer

name text ,NOT NULL

country_languages
country_id integer ,NOT NULL
language_id integer NOT NULL
PRIMARY KEY country_id, language_id
Create Table
 CREATE TABLE countries (country_id INTEGER PRIMARY KEY,
name text NOT NULL);

 CREATE TABLE languages ( language_id integer,


name text NOT NULL, PRIMARY KEY (language_id));

 CREATE TABLE country_languages (


country_id integer NOT NULL,
language_id integer NOT NULL,
PRIMARY KEY (country_id, language_id),
FOREIGN KEY (country_id) REFERENCES countries (country_id)
ON DELETE CASCADE ON UPDATE NO ACTION,
FOREIGN KEY (language_id) REFERENCES languages
(language_id)
ON DELETE CASCADE ON UPDATE NO ACTION
);
SQL | DEFAULT
Constraint
CREATE TABLE tablename (Columnname DEFAULT
‘defaultvalue’ );

CREATE TABLE Geeks (


ID int NOT NULL,
Name varchar(255),
Age int,
Location varchar(255) DEFAULT 'Noida');
Insert Statement
Single-row INSERT
Multirow INSERT
Insert- Using Select statement
The INSERT INTO statement is used to add
new data to a database.
INSERT INTO can contain values for some or
all of its columns.
INSERT INTO can be combined with a SELECT
to insert records.
Insert Statement

INSERT INTO table1 (column1, column2 ,..)


VALUES ( value1, value2 ,...);

INSERT INTO table1 ( column1, column2 ,..)


VALUES ( value1, value2 ,...),( value1,
value2 ,...), ...( value1,
value2 ,...);
Insert Statement
INSERT INTO Geeks VALUES (4, 'Mira', 23, 'Delhi’);

INSERT INTO Geeks VALUES (5, 'Hema', 27,DEFAULT);

INSERT INTO Geeks VALUES (6, 'Neha', 25, 'Delhi’);

INSERT INTO Geeks VALUES (7, 'Khushi', 26,DEFAULT);


Table Creation
CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);
Insert Statement

INSERT INTO Customer(CustomerID, CustomerName, LastName,


Country, Age, Phone)
VALUES (1, "Shubham", "Thakur", "India",23,1111111111)
,(2, "Aman", "Chopra", "Australia",21,222222222);
(3, “Naveen”, “Tulasi”, “Sri lanka”,24,333333333),
(4, “Aditya”, “Arpan’, “Austria”,21,444444444),
(5, “NishantSalchichas”, “Jain”, “Spain’,22,55555555);
Create table with select statement
CREATEor TABLE new_table_name AS
Create a Table Using Another Table
SELECT column1, column2,…
FROM existing_table_name
WHERE ….;

CREATE TABLE SubTable AS SELECT


CustomerID, CustomerName FROM
customer;
CREATE TABLE new_table_name AS
SELECT *
FROM existing_table_name
WHERE ….;

CREATE TABLE customer_copy AS SELECT *


FROM customer;
Describe Statement
Desc Tablename
DROP Table
Drop table tablename;
Alter Table
 to rename the name of the table.

 to modify the structure of an existing table

 ALTER TABLE table_name


 RENAME TO new_table_name;

 Columns can also be given a new name with the use of ALTER TABLE.

 ALTER TABLE table_name


 RENAME COLUMN old_name TO new_name;
Create Table Student
Create Table
 CREATE TABLE Student (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
email VARCHAR(50),
phone VARCHAR(20)
);

 INSERT INTO Student (id, name, age, email, phone)


 VALUES
 (1, 'Amit', 20, '[email protected]', '9999999999'),
 (2, 'Rahul', 22, '[email protected]', '8888888888'),
 (3, 'Priya', 21, '[email protected]', '7777777777'),
 (4, 'Sonia', 23, '[email protected]', '6666666666'),
 (5, 'Kiran', 19, '[email protected]', '5555555555');
Alter Table
ALTER TABLE Student RENAME name TO
FIRST_NAME;

ALTER TABLE Student RENAME TO


Student_Details;
SQL ALTER TABLE – ADD, DROP, MODIFY
 The ALTER TABLE statement in SQL is used to add, remove, or modify columns in
an
 existing table. The ALTER TABLE statement is also used to add and remove various
 constraints on existing tables.

 ALTER TABLE table_name ADD (Columnname_1 datatype,


 Columnname_2 datatype, …Columnname_n datatype);

 ALTER TABLE Students


 ADD Email varchar(255);

 ALTER TABLE table_name


 DROP COLUMN column_name;

 ALTER TABLE Students


 DROP COLUMN Email;
Alter Table
ALTER TABLE MODIFY Column Statement
Syntax:
 ALTER TABLE table_name
 MODIFY column_name column_type;

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

 ALTER TABLE Student


 MODIFY age int(5);
Alter Table
ALTER TABLE Student ADD marks INT;
Select Statement
SELECT [DISTINCT | ALL] {* | select_list}
FROM {table_name [alias] | view_name}
[{table_name [alias] | view_name}]...
[WHERE condition]
[GROUP BY condition_list] [HAVING condition]
[ORDER BY {column_name | column_# [ ASC |
DESC ] }
Select Statement
SELECT column1,
column2....columnN FROM
table_name;

SELECT * FROM table_name;

SELECT DISTINCT column1,


column2....columnN FROM
table_name;
Select Statement
SELECT column1, column2, ...FR
OM table_name
WHERE condition;
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this
operator may be written as !=
> Greater than
< Less than

>= Greater than or equal


<= Less than or equal
BETWEE Between a certain range
N
LIKE Search for a pattern
IN To specify multiple possible values for a
Select Statement
SELECT CustomerName, LastName FROM
Customer;
Select Statement
 SELECT * FROM Customer;
Where Clause
SELECT CustomerName FROM Customer
where Age = '21’;

SELECT CustomerName FROM Customer


where Country = ‘Austria’;

SELECT CustomerName, Country FROM


Customer WHERE Age > 21;
Between Operator
SELECT column1,column2 FROM table_name
WHERE column_name BETWEEN value1
AND value2;

SELECT * FROM Customer WHERE Age


BETWEEN 22 AND 24;
Select Statment
 SELECT * FROM employees WHERE Department = ‘HR’;
 SELECT * FROM employees WHERE Gender = ‘Female’ OR
Department = ‘IT’;
 SELECT * FROM employees WHERE (Gender = ‘Female’ OR
Department = ‘IT’) AND Salary > 35000;
 SELECT * FROM employee WHERE id =1006
 SELECT * FROM employee WHERE age=28
 SELECT * FROM employee WHERE salary > 50000
 SELECT * FROM employee WHERE NOT id = 1006
 SELECT * FROM employee WHERE NOT department = ‘IT’;
Order By clause
SELECT * FROM Customer ORDER BY Age
DESC;

You might also like