0% found this document useful (0 votes)
28 views48 pages

Structured Query Language

SQL is a standard language used to manage data in relational database management systems. It allows users to define, manipulate, and retrieve data from databases. Popular SQL commands include CREATE, SELECT, INSERT, UPDATE, DELETE, and DROP which are used to create and modify database structures and manage data.

Uploaded by

Pavith Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
28 views48 pages

Structured Query Language

SQL is a standard language used to manage data in relational database management systems. It allows users to define, manipulate, and retrieve data from databases. Popular SQL commands include CREATE, SELECT, INSERT, UPDATE, DELETE, and DROP which are used to create and modify database structures and manage data.

Uploaded by

Pavith Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 48

SQL

Structured
Query
Language
• SQL is a computer language for managing and retrieving data in relational databases.
• It is the standard language for relational database management systems (RDBMS).
• Popular RDBMS like MySQL, MS Access, Oracle, and SQL Server use SQL.
• Each RDBMS may have its own dialect of SQL, such as T-SQL for MS SQL Server
and PL/SQL for Oracle.
• SQL allows for storing, manipulating, and retrieving data in a structured manner.
• SQL supports operations like data insertion, modification, deletion, and querying.
• It provides a standardized way to define database structures, create tables, and
establish relationships.
• SQL queries are used to retrieve specific data from databases using SELECT

What is SQL? statements.


• SQL supports various functions for performing calculations on data, such as SUM,
COUNT, and AVG.
• Joins can be used in SQL to combine data from multiple tables based on
relationships.
• SQL includes data manipulation statements like INSERT, UPDATE, and DELETE.
• It also provides data control statements for managing user permissions and security.
• Transaction control statements ensure data consistency and integrity.
• SQL is widely used across industries and applications for managing and analyzing
large datasets efficiently.
• SQL is widely popular because it offers the following
advantages:  Allows users to access data in the relational
database management systems.
• Allows users to describe the data.
• Allows users to define the data in a database and
manipulate that data.
• Allows to embed within other languages using SQL
Why SQL? modules, libraries & pre-compilers.
• Allows users to create and drop databases and tables.
• Allows users to create view, stored procedure, functions in
a database.
• Allows users to set permissions on tables, procedures and
views.
What is RDBMS?

RDBMS stands for Relational


A Relational database
Database Management System.
management system (RDBMS)
RDBMS is the basis for SQL, and
is a database management
for all modern database
system (DBMS) that is based on
systems like MS SQL Server, IBM
the relational model as
DB2, Oracle, MySQL, and
introduced by E. F. Codd.
Microsoft Access.
What is a table?
• The data in an RDBMS is stored in database
objects which are called as tables. This table is
basically a collection of related data entries and
it consists of numerous columns and rows.
Remember, a table is the most common and
simplest form of data storage in a relational
database. The following program is an example
of a CUSTOMERS table:
What is a field?
• Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist of ID,
NAME, AGE, ADDRESS and SALARY. A field is a column in a table that is designed to maintain specific
information about every record in the table.

What is a Record or a Row?


• A record is also called as a row of data is each individual entry that exists in a table. For example, there are 7 records in
the above CUSTOMERS table. Following is a single row of data or record in the CUSTOMERS table:
What is a column?
• A column is a vertical entity in a table that contains all information
associated with a specific field in a table.

What is a NULL value?


• A NULL value in a table is a value in a field that appears to
be blank, which means a field with a NULL value is a field
with no value. It is very important to understand that a
NULL value is different than a zero value or a field that
contains spaces. A field with a NULL value is the one that
has been left blank during a record creation.
SQL • The standard SQL commands to interact with relational
databases are CREATE, SELECT, INSERT, UPDATE, DELETE
and DROP. These commands can be classified into the
Commands following groups based on their nature:
SQL – CREATE Database

• The SQL CREATE DATABASE statement is used to create a new SQL


database.
• Syntax :The basic syntax of this CREATE DATABASE statement is as
follows:

• Always the database name should be unique within the RDBMS.


SQL ─ DROP or DELETE Database
• The SQL DROP DATABASE statement is used to drop an existing
database in SQL schema.
• Syntax
• The basic syntax of DROP DATABASE statement is as follows:

• Always the database name should be unique within the RDBMS.


Truncate
In SQL, the TRUNCATE statement is used to remove all rows from a table, effectively deleting all data within
the table. Unlike the DELETE statement, which removes individual rows, TRUNCATE removes all rows in a
single operation. It is a faster and more efficient way to delete all data from a table.
Syntax:
TRUNCATE TABLE table_name;

Example: Suppose we have a table named "customers" that contains customer records, and we want
to delete all the data from this table:

TRUNCATE TABLE customers;


Truncate vs Delete vs Drop
TRUNCATE:
•Removes all rows from a table quickly.
•Does not log individual row deletions, making it faster and more efficient than DELETE.
•Cannot be rolled back.
•Resets auto-increment values.
•Does not trigger associated triggers.
DROP:
•Completely removes a table or database object from the database.
•Deletes all data, indexes, constraints, and triggers associated with the object.
•The operation is not logged and cannot be rolled back.
DELETE:
•Removes specific rows from a table based on specified conditions.
•Operates on individual rows.
•Generates more transaction log entries compared to TRUNCATE.
•Can be rolled back within a transaction.
•Triggers associated triggers before and after row deletion.
SELECT Database, USE Statement
• When you have multiple databases in your SQL Schema, then before
starting your operation, you would need to select a database where
all the operations would be performed. The SQL USE statement is
used to select any existing database in the SQL schema.
• Syntax :
• The basic syntax of the USE statement is as shown below:
CREATE Table
• Creating a basic table involves naming the table and defining its
columns and each column's data type.
• The SQL CREATE TABLE statement is used to create a new table.
• Syntax :The basic syntax of the CREATE TABLE statement is as follows:
SQL –Creating a Table from an Existing
Table
• A copy of an existing table can be created using a combination of the CREATE
TABLE statement and the SELECT statement. The new table has the same column
definitions. All columns or specific columns can be selected. When you will create
a new table using the existing table, the new table would be populated using the
existing values in the old table.
• Syntax :The basic syntax for creating a table from another table is as follows:
DROP or DELETE Table
The DROP TABLE command is used to permanently remove an existing table from a database. It completely
deletes the table structure and all its associated data, including indexes, constraints, and triggers. Be cautious
when using this command as it cannot be undone.
Syntax:

DROP TABLE table_name;

Example: Suppose we have a table called "customers" that we want to remove from the database:

DROP TABLE customers;

This command will delete the "customers" table from the database, along with all its data and related objects. It is
important to note that once the table is dropped, it cannot be recovered, so it is advisable to take backups or ensure
the table removal is intentional.
INSERT Query
The INSERT command is used to insert new rows of data into a specified table in a database. It allows
you to specify the columns you want to insert data into and the corresponding values for those columns.

Syntax

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

Example: Suppose we have a table called "employees" with columns "id", "name", and "salary". We
want to insert a new employee into the table:
INSERT INTO employees (id, name, salary) VALUES (1, 'John Doe', 5000);
SELECT Query

The SELECT command is used to retrieve data from one or more tables in a database. It allows you to
specify the columns you want to retrieve and optionally apply conditions to filter the data.

Syntax

SELECT column1, column2, ... FROM table_name WHERE condition;

Example: Suppose we have a table called "customers" with columns "id", "name", and "city". We want to
retrieve the names of all customers from the city 'New York':

SELECT name FROM customers WHERE city = 'New York';


WHERE Clause

The WHERE clause is used in conjunction with the SELECT statement to filter data based on specific
conditions. It allows you to specify a condition that must be met for a row to be included in the result set
Syntax

SELECT column1, column2, ...


FROM table_name
WHERE condition;
Example: Suppose we have a table called "products" with columns "id", "name", and "price". We want to
retrieve all products with a price greater than 50:

SELECT * FROM products


WHERE price > 50;
AND & OR Conjunctive
Operators

The AND and OR operators are used in conjunction with the WHERE
clause to create more complex conditions for filtering data.
•AND: The AND operator is used to combine multiple conditions, and all
the conditions must evaluate to true for a row to be included in the result
set.
•OR: The OR operator is used to combine multiple conditions, and at
least one of the conditions must evaluate to true for a row to be included
in the result set.
Syntax with AND
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2;

Example with AND: Suppose we have a table called "employees" with columns "id",
"name", "age", and "department". We want to retrieve all employees who are both
from the "Sales" department and are above 30 years old:
SELECT * FROM employees
WHERE department = 'Sales' AND age > 30;
Syntax with OR
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2;

Example with OR: Suppose we have a table called "products" with columns "id",
"name", and "category". We want to retrieve all products that are either in the
"Electronics" category or have a price greater than 1000:
SELECT * FROM products
WHERE category = 'Electronics' OR price > 1000;
UPDATE Query

The UPDATE command is used to modify existing data in a table. It allows you to update specific columns
with new values based on specified conditions.
Syntax

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Example: Suppose we have a table called "employees" with columns "id", "name", and "salary". We want to
update the salary of an employee with ID 1 to 6000:
UPDATE employees
SET salary = 6000
WHERE id = 1;
DELETE Query

The DELETE command is used to remove rows from a table based on specified conditions. It allows you to
selectively delete data from a table.

Syntax
DELETE FROM table_name
WHERE condition;

Example: Suppose we have a table called "customers" with columns "id", "name", and "city". We want to
delete all customers from the city 'London':

DELETE FROM customers


WHERE city = 'London';
TOP, LIMIT or ROWNUM
Clause
The usage of the "TOP", "LIMIT", or "ROWNUM" clause depends on the specific database system you are
working with. These clauses are used to limit the number of rows returned in a query result.

1."TOP" clause (Microsoft SQL Server):


Syntax:

SELECT TOP number_of_rows column1, column2, ...


FROM table_name
WHERE condition;

Example:

SELECT TOP 5 name, age


FROM customers
WHERE country = 'USA';
2."LIMIT" clause (MySQL, PostgreSQL, SQLite):
SELECT column1, column2, ...
FROM table_name
WHERE condition
LIMIT number_of_rows;

Example:
SELECT name, age
FROM customers
WHERE country = 'USA'
LIMIT 5;

3."ROWNUM" (Oracle):
SELECT column1, column2, ...
FROM table_name
WHERE ROWNUM <= number_of_rows;
ORDER BY Clause
The ORDER BY clause is used to sort the result of a query based on one or more columns. It allows you to specify
the sorting order, either in ascending (ASC) or descending (DESC) order.

Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Example: Suppose we have a table called "employees" with columns "id", "name", and "salary". We want to retrieve
all employees' names and salaries in descending order of their salaries:

SELECT name, salary


FROM employees
ORDER BY salary DESC;
Group By
The GROUP BY clause is used in conjunction with aggregate functions to group rows based on specified
columns. It allows you to perform calculations on groups of data rather than individual rows.
Syntax:
SELECT column1, column2, ..., aggregate_function(column)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...;
Example: Suppose we have a table called "orders" with columns "order_id", "customer_id", and
"total_amount". We want to calculate the total amount of orders for each customer.
SELECT customer_id, SUM(total_amount) AS
total_order_amount
FROM orders
GROUP BY customer_id;
Distinct Keyword
The DISTINCT keyword is used in a SELECT statement to eliminate duplicate rows from the result set. It
filters out repeated values and returns only unique values.
Syntax:

SELECT DISTINCT column1, column2, ...


FROM table_name
WHERE condition;

Example: Suppose we have a table called "employees" with columns "id", "name", and "department".
We want to retrieve all unique department names from the table.

SELECT DISTINCT department


FROM employees;
SORTING Results
Sorting in SQL is done using the ORDER BY clause, which allows you to sort the result set based on one or
more columns. You can specify the sorting order as either ascending (ASC) or descending (DESC).
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

Example: Suppose we have a table called "products" with columns "product_id", "name", and "price". We
want to retrieve all products sorted by their price in ascending order.

SELECT product_id, name, price


FROM products
ORDER BY price ASC;
Using Joins
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means
for combining fields from two tables by using values common to each.
INNER JOIN
The most important and frequently used of the joins is the INNER JOIN. They are also referred to as an
EQUIJOIN. The INNER JOIN creates a new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find
all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each
matched pair of rows of A and B are combined into a result row
LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that
if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in
each column from the right table. This means that a left join returns all the values from the left table, plus matched
values from the right table or NULL in case of no matching join predicate.
RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the
left table. This means that if the ON clause matches 0 (zero) records in the left table; the join will
still return a row in the result, but with NULL in each column from the left table. This means that
a right join returns all the values from the right table, plus matched values from the left table or
NULL in case of no matching join predicate.
FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins. The joined table will contain all records
from both the tables and fill in NULLs for missing matches on either side.
UNIONS
The UNION operator in SQL is used to combine the result sets of two or more SELECT
statements into a single result set. It merges rows from different SELECT statements and removes
duplicates.
Syntax
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;

Example:We want to retrieve a combined list of unique customer IDs from both the "orders" and
"invoices" tables. We can use the UNION operator to achieve this:
SELECT customer_id
FROM orders
UNION
SELECT customer_id FROM invoices;
Intersect
In SQL, the INTERSECT clause is used to combine the result sets of two or more SELECT statements and
return only the rows that are common to all the result sets. It returns the intersection of rows between the result
sets, meaning only the rows that exist in all SELECT statements will be included in the final result set.
Syntax:
SELECT column1, column2, ...
FROM table1
INTERSECT
SELECT column1, column2, ...
FROM table2;
Example:Suppose we have two tables, "employees" and "managers", both with a column "employee_name". We want
to find the names of employees who are also managers in the company.
SELECT employee_name
FROM employees
INTERSECT
SELECT employee_name FROM managers;
Except
The EXCEPT operator in SQL is used to subtract the result set of one SELECT statement from the result set of
another SELECT statement. It returns only the rows that exist in the first SELECT statement but not in the
second SELECT statement
Syntax:
SELECT column1, column2, ...
FROM table1
EXCEPT
SELECT column1, column2, ...
FROM table2;
Suppose we have two tables, "employees" and "managers", both with a column "employee_name". We want to
find the names of employees who are not managers.
SELECT employee_name
FROM employees
EXCEPT
SELECT employee_name FROM managers;
Alias Syntax
In SQL, an alias is used to assign a temporary name or alias to a table or column in a query. Aliases can make the query
more readable and provide a shorthand notation for referring to tables or columns.
Here's the syntax for assigning aliases in SQL:
Table Alias:
SELECT column1, column2, ...
FROM table_name AS alias_name;
Column Alias:
SELECT column_name AS alias_name
FROM table_name;

Example
SELECT e.employee_name AS name, d.department_name
FROM employees AS e
JOIN departments AS d ON e.department_id =
d.department_id;
Like Operator
In SQL, the LIKE operator is used in a WHERE clause to search for a specified pattern in a column. It is
commonly used with string values to perform pattern matching.
The LIKE operator uses two wildcard characters:
•'%' (percent sign): Represents any sequence of characters (including none).
•'_' (underscore): Represents any single character.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE pattern;
Example : Suppose we have a table named "products" with a column called
"product_name". We want to retrieve all products that start with the letter 'A'.
sql

SELECT product_name
FROM products
WHERE product_name LIKE 'A%';
SQL CONSTRAINTS
In SQL, constraints are used to enforce rules or conditions on the columns or tables
to maintain the integrity, consistency, and validity of the data. There are several
types of constraints commonly used in SQL:
Primary Key Constraint:
•Ensures that a column or a combination of columns uniquely identifies
each row in a table.
•Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50),
...
);
Foreign Key Constraint:
•Establishes a relationship between two tables based on a column(s) from one
table referencing the primary key column(s) of another table.
•Example:

CREATE TABLE orders (


order_id INT PRIMARY KEY,
customer_id INT,
...
FOREIGN KEY (customer_id) REFERENCES
customers(customer_id)
);
Unique Constraint:
•Ensures that the values in a column or a combination of
columns are unique across the table.
•Example:
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(50),
...
UNIQUE (product_name)
);
Not Null Constraint:
•Ensures that a column does not contain null values.
•Example:

CREATE TABLE customers (


customer_id INT PRIMARY KEY,
customer_name VARCHAR(50) NOT NULL,
...
);
Check Constraint:
•Defines a condition that must be satisfied for the data being inserted or
updated in a column.
•Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50),
age INT,
...
CHECK (age >= 18)
);

You might also like