Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

SQL

Uploaded by

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

SQL

Uploaded by

abhinavramesan19
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

SQL

KEYS
Foreign Key:
A foreign key is a column within a table that refers to (or "relates to") a
unique value in a referenced table. Each value in the foreign key column
must have a matching value in the referenced table.
Primary Key VS Foreign Key
S.no. Primary key Foreign key

The foreign key of a particular


The primary key of a particular table is table is simply the primary key
1 the attribute which uniquely identifies of some other table which is
every record. used as a reference key in the
second table.

A primary key attribute in a table can A foreign key attribute may


2 never contain a null value. have null values as well.
A table can have one or more
Not more than one primary key is
3 than one foreign key for
permitted in a table.
referential purposes.

Duplicity is strictly prohibited in the Duplicity is permitted in the


4 primary key; there cannot be any foreign key attribute, hence
duplicate values. duplicate values are permitted.
Referential Integrity
• It ensures that relationship between
records in related tables are valid.
• User should not accidentally delete
or change related data.
• Referential Integrity is set when the
following conditions are met:
1.The matching filed from the primary
table is a primary key
2.Related field have the same data
type.
3.Both tables belong to the same
database.
SQL Commands

• CREATE database
Syntax : CREATE database <databasename>;

• USE database
Syntaax : USE parkavi;
• CREATE TABLE
Syntax: CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

• Insert Data into table


INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
• Inserting multiple records
Syntax:
INSERT INTO table_name (column_list) VALUES (value_list_1),
(value_list_2), ... (value_list_n);
• NULL Values
A field with a NULL value is a field with no value.
A NULL value is different from a zero value or a field that contains spaces. A
field with a NULL value is one that has been left blank during record
creation!
Not Null: By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values
• SELECT Command
The SELECT statement is used to select data from a
database
Syntax: (to retrieve all records)
SELECT * FROM table_name;
• SELECT (Particular row) • SELECT (row with condition
using WHERE )
• SELECT (Particular column) • SELECT (with DISTINCT)
SELECT (ALL Vs DISTINCT)
• Select all name from student1; • Select Distinct name from student1;
DESCRIBE /DESC (View the structure of
the table)
CREATE TABLE users ( id INT PRIMARY
KEY, name
VARCHAR(50),
email VARCHAR(100),
age INT );
Syntax:
DESC users;
• Calculation • Current System Date
Syntax: Select curdate;
Write the calculation next to
the keyword SELECT
Condition based on Range (BETWEEN operator
defines the range)
List condition (using WHERE)
Pattern matching using LIKE command
• SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any
position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the
second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a"
and are at least 2 characters in length

WHERE CustomerName LIKE 'a__%' Finds any values that start with "a"
and are at least 3 characters in length

WHERE ContactName LIKE 'a%o' Finds any values that start with "a"
and ends with "o"
IS NULL Vs IS NOT NULL
IS NULL

IS NOT NULL
Relational operators
• To compare 2 values relational operators are used.
• True / false state
Relational operators used in sql
=,>,<,>=,<=,<> (not equal to)
Logical operators
OR
• OR (II)
• AND (&&)
• NOT(!)

AND

NOT
SQL Constraints
• NOT NULL- Ensures that the column can not have null value.
• UNIQUE –Ensures that all values in a column are different.
• PRIMARY KEY-used to uniquely identify a row in the table.
• Example NOT NULL
• CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
UNIQUE command

The UNIQUE constraint ensures that all values in a


column are different.
Primary Key
The PRIMARY KEY. constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values
CREATE TABLE department (
Did int NOT NULL, By using Alter table
Dname varchar(30),
Demployee varchar(30),
PRIMARY KEY (Did)
);

With the primary key,


we cannot modify or
delete the values. With
the unique key, we can
modify the column
values.
SQL PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the existing column when the table
is already created, use the following SQL:

Syntax:

ALTER TABLE student1


ADD PRIMARY KEY (sroll);

DROP a PRIMARY KEY Constraint


Syntax:
ALTER TABLE student
DROP PRIMARY KEY;
Inserting new column and adding
values using Alter table.
Modifying Data using UPDATE
command
The UPDATE statement is used to modify the existing records
in a table.
DELETE STATMENT ALTERING
TABLE add, delete, or modify columns in an
existing table.
To change column name use
RENAME command in Alter Table
• ALTER TABLE table_name
RENAME COLUMN oldcolumn_name to newcolumn_name;
DATABASE AND TABLES
• Create Database database_name;
• Use database;
• Show database;
• Create table table_name;
• Show tables;
DROP TABLE
The DROP TABLE statement is used to drop an existing table in a
database.
SQL JOINS
A JOIN clause is used to combine rows from two or more tables, based on
a related column between them.

• Cartesian product on two tables


• Equi join
• Natural join
CARTESIAN JOIN / CROSS JOIN
• Cartesian product (X)/cross joint Cartesian Product is denoted by X
symbol. Lets say we have two relations R1 and R2 then the cartesian
product of these two relations (R1 X R2) would combine each tuple of
first relation R1 with the each tuple of second relation R2. Visit :
python.mykvs.in for regular up
Syntax:
select * from t1
CROSS JOIN t2;
EQUI JOIN
• SQL EQUI JOIN performs a JOIN
against equality or matching
column(s) values of the
associated tables. An equal sign
(=) is used as comparison
operator in the where clause to
refer equality.

Syntax:

SELECT column_list FROM table1,


table2.... WHERE table1.column_name
= table2.column_name;
;

Natural join
• The SQL NATURAL JOIN is a type of EQUI JOIN and is structured in
such a way that, columns with the same name of associated tables
will appear once only.
• Natural Join: Guidelines
• - The associated tables have one or more pairs of identically named
columns.
- The columns must be the same data type.
Syntax:
SELECT * FROM table1 NATURAL JOIN table2
SQL commands are mainly categorized into five categories:

• DDL – Data Definition Language


• DQL – Data Query Language
• DML – Data Manipulation Language
• DCL – Data Control Language
• TCL – Transaction Control Language
• List of DDL commands:

• CREATE: This command is used to create the database or its objects (like
table, index, function, views, store procedure, and triggers).
• DROP: This command is used to delete objects from the database.
• ALTER: This is used to alter the structure of the database.
• TRUNCATE: This is used to remove all records from a table, including all
spaces allocated for the records are removed.
• COMMENT: This is used to add comments to the data dictionary.
• RENAME: This is used to rename an object existing in the database.
List of DML commands:

• INSERT: It is used to insert data into a table.


• UPDATE: It is used to update existing data within a table.
• DELETE: It is used to delete records from a database table.
ORDER BY
• The ORDER BY keyword is
used to sort the result-set in
ascending or descending
order.

SYNTAX:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|
DESC;
What is an Aggregate Function in SQL?
• An aggregate function in SQL returns one value after
calculating multiple values of a column. We often use
aggregate functions with the GROUP BY and HAVING
clauses of the SELECT statement.
• Various types of SQL aggregate functions are:
Count()
Sum()
Avg()
Min()
Max()
Order By Two
Columns in SQL

SELECT * FROM employee


ORDER BY salary desc,
last_name asc;
Why Use Aggregate Functions?
• Aggregate functions are a vital component of database management
systems.
• They allow us to perform calculations on large data sets quickly and
efficiently.
EXAMPLE:
statistical reports,
perform financial analysis, and
manage inventory levels.
COUNT() Function
• The COUNT() function returns the number of rows in a database table.
Syntax:
SELECT COUNT(column_name)
FROM table_name
WHERE condition; SELECT COUNT (product_id)
from product;
SUM() Syntax
SELECT SUM(column_name)
FROM table;
SELECT SUM(Price)
FROM OrderDetails;
AVG() Syntax
The AVG() function returns the average value of a numeric column.
SELECT AVG(column_name)
FROM table_name
AVG(Price)
WHERE condition; 28.866363636363637
The SQL MIN() and MAX() Functions

The MIN() function returns The MAX() function returns


the smallest value of the the largest value of the
selected column. selected column.

MIN() Syntax MAX() Syntax


SELECT MIN(column_name) SELECT MAX(column_name)
FROM table_name FROM table_name
WHERE condition; WHERE condition;
AS keyword(alias)
The AS command is used to rename a
column or table with an alias.
An alias only exists for the duration of
the query.

SELECT NAME, SUM(SALARY) as


total_salary
FROM CUSTOMERS
SELECT *
GROUP BY Statement FROM Store
GROUP BY Item;
• The GROUP BY statement is
often used with aggregate
functions (COUNT(), MAX(),
MIN(), SUM(), AVG()) to group
the result-set by one or more
columns.
• The GROUP BY statement groups
rows that have the same values
into summary rows,

SYNTAX:
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s)
GROUP BY.. SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
having clause
• The HAVING clause was added to SQL because the WHERE keyword
cannot be used with aggregate functions.
• SQL HAVING clause is similar to the WHERE clause; they are both used
to filter rows in a table based on conditions. However, the HAVING
clause was included in SQL to filter grouped rows instead of single
rows.
SELECT column_name(s) SELECT
COUNT(CustomerID),
FROM table_name Country
FROM Customers
GROUP BY column_name(s) GROUP BY Country
HAVING
HAVING condition COUNT(CustomerID) > 5;

ORDER BY column_name(s);
HAVING WITH ORDER BY
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
retrieve all records from the
CUSTOMERS table where the
sum of their salary is less than
4540, ordered by their name in
ascending order
SELECT NAME, SUM(SALARY)
as total_salary
FROM CUSTOMERS
GROUP BY NAME
HAVING SUM(SALARY) < 4540
ORDER BY NAME
MAX() function
on date
To get data of 'ord_num',
'ord_amount', 'ord_date',
'agent_code' from the
'orders' table with the
following conditions -

1. 'ord_date' is equal to the


maximum 'ord_date',

2. maximum 'ord_date' from


those agents whose
'agent_code' is 'A002',
set update (python)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.update(y)
print(x)

output:
{'google', 'microsoft', 'apple', 'cherry', 'banana'}

You might also like