0% found this document useful (0 votes)
31 views86 pages

Introduction To SQL

The document provides an introduction to SQL including key concepts like SQL syntax, case sensitivity, creating databases and tables, inserting, selecting, updating, and deleting data. It also covers SQL statements like SELECT, INSERT, UPDATE, DELETE, CREATE DATABASE, DROP DATABASE, CREATE TABLE, DROP TABLE, TRUNCATE TABLE, ALTER TABLE and clauses like WHERE, GROUP BY, ORDER BY, DISTINCT. Functions like COUNT, MAX are also introduced.

Uploaded by

salar
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)
31 views86 pages

Introduction To SQL

The document provides an introduction to SQL including key concepts like SQL syntax, case sensitivity, creating databases and tables, inserting, selecting, updating, and deleting data. It also covers SQL statements like SELECT, INSERT, UPDATE, DELETE, CREATE DATABASE, DROP DATABASE, CREATE TABLE, DROP TABLE, TRUNCATE TABLE, ALTER TABLE and clauses like WHERE, GROUP BY, ORDER BY, DISTINCT. Functions like COUNT, MAX are also introduced.

Uploaded by

salar
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/ 86

Introduction to SQL

 What is SQL Syntax?


 SQL syntax is a unique set of rules and guidelines to be followed while writing SQL
statements.
 All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE,
DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a
semicolon (;)
SQL is Case insensitive.

 Case Sensitivity
 The most important point to be noted here is that SQL is case insensitive, which
means SELECT and Select have same meaning in SQL statements. Whereas, MySQL
makes difference in table names. So, if you are working with MySQL, then you need to
give table names as they exist in the database.
SQL CREATE DATABASE Statement

 SQL CREATE DATABASE Statement


 To store data within a database, you first need to create it. This is necessary to
individualize the data belonging to an organization.

 Example:
 CREATE DATABASE sampleDB;
SQL USE Statement

 SQL USE Statement


 Once the database is created, it needs to be used in order to start storing the data
accordingly.

 Example:
 Use sampleDB;
SQL DROP DATABASE Statement

 SQL DROP DATABASE Statement


 If a database is no longer necessary, you can also delete it. To delete/drop a database.

 Example:
 Drop database sampleDB;
SQL CREATE TABLE Statement

 SQL CREATE TABLE Statement


 In an SQL driven database, the data is stored in a structured manner, i.e. in the form of
tables.
Example:

 With constraints
 The following code block is an example, which creates a CUSTOMERS table given above,
with an ID as a primary key and NOT NULL are the constraints showing that these fields
cannot be NULL while creating records in this table −
SQL DESC Statement

 SQL DESC Statement


 Every table in a database has a structure of its own. To display the structure of database
tables, we use the DESC statements.
 Syntax:

 Example: Desc customers;


SQL INSERT INTO Statement

 SQL INSERT INTO Statement


 The SQL INSERT INTO Statement is used to insert data into database tables.
 Syntax:
Example: inserting data into table
SQL SELECT Statement

 In order to retrieve the result-sets of the stored data from a database table, we use the
SELECT statement.

 To retrieve the data from CUSTOMERS table, we use the SELECT statement as shown
below.
 Example:
 SELECT * FROM CUSTOMERS;
SQL UPDATE Statement

 SQL UPDATE Statement


 When the stored data in a database table is outdated and needs to be updated without
having to delete the table, we use the UPDATE statement.
Example:

 Update example:

SQL DELETE Statement

 SQL DELETE Statement


 Without deleting the entire table from the database, you can also delete a certain part of the
data by applying conditions. This is done using the DELETE FROM statement.
 Syntax:

 Example:
SQL DROP TABLE Statement

 SQL DROP TABLE Statement


 To delete a table entirely from a database when it is no longer needed, following syntax is
used.
 Syntax:

 Example:
 DROP TABLE CUSTOMERS;
SQL TRUNCATE TABLE Statement

 The TRUNCATE TABLE statement is implemented in SQL to delete the data of the table
but not the table itself.
 When this SQL statement is used, the table stays in the database like an empty table.
 Following is the syntax −

 Example:
 TRUNCATE TABLE CUSTOMERS;
SQL ALTER TABLE Statement

 SQL ALTER TABLE Statement


 The ALTER TABLE statement is used to alter the structure of a table. For instance, you
can add, drop, and modify the data of a column using this statement.
 Following is the syntax −

 Example:
SQL DISTINCT Clause
 SQL DISTINCT Clause
 The DISTINCT clause in a database is used to identify the non-duplicate data from a
column. Using the SELECT DISTINCT statement, you can retrieve distinct values from a
column.
 Following is the syntax −

 Example:
 SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY.
 As an example, lets use the DISTINCT keyword with a SELECT query.
 The repetitive salary 2000.00 will only be retrieved once and the other record is ignored.
SQL WHERE Clause

 SQL WHERE Clause


 The WHERE clause is used to filter rows from a table by applying a condition.
 Syntax:
WHERE clause Example:

 The following query is an example to fetch all the records from CUSTOMERS table where
the salary is greater than 2000, using the SELECT statement.
SQL AND/OR Operators
 The AND/OR Operators are used to apply multiple conditions in the WHERE clause.
Following is the syntax −

 Example: SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY


> 2000 AND age < 25;
 The above query is an example to fetch all the records from CUSTOMERS table where
the salary is greater than 2000 AND age is less than 25, using the SELECT statement .
SQL IN Clause
 SQL IN Clause
 The IN Operator is used to check whether the data is present in the column or not, using
the WHERE clause.

 Example:
SQL BETWEEN Clause

 SQL BETWEEN Clause


 The BETWEEN Operator is used to retrieve the values from a table that fall in a certain
range, using the WHERE clause.
 Syntax:
 SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
Example:
SQL LIKE Clause

 SQL LIKE Clause


 The LIKE Operator is used to retrieve the values from a table that match a certain pattern,
using the WHERE clause.

 Example:
 SQL ORDER BY Clause
 The ORDER BY Clause is used to arrange the column values in a given/specified order.
 Syntax:
Example:

 In the following example we are trying to sort the result in an ascending order by the
alphabetical order of customer names −

 In the above example we are trying to sort the result in an ascending order by the
alphabetical order of customer names.
SQL GROUP BY Clause

 SQL GROUP BY Clause


 The GROUP BY Clause is used to group the values of a column together. Following is the
syntax −
Example:

 We are trying to group the customers by their age and calculate the average salary for each
age group using the following query −
Count()

 To Count the number of rows in a table.


SQL COUNT Function

 SQL COUNT Function


 The COUNT Function gives the number of non-null values present in the specified
column. Following is the syntax −

 Example:
Example

 -- count of customers who live in the UK

 SELECT COUNT(country)
FROM Customers
WHERE country = 'UK';
Count()
Count(*)

 --returns the number of rows in the Customers table

 SELECT COUNT(*)
FROM Customers;
Example:
COUNT() With DISTINCT

 If we need to count the number of unique rows, we can use the COUNT() function with the
DISTINCT clause.
Count() with distinct
Group by()

 The COUNT() function can be used with the GROUP BY clause to count the rows with
similar values.
Max()

 Example: to get the maximum salaried employee:


 Select max(salary) from employee;
 Example: To get the employee name who is receiving highest salary.
 Select ename from employee where salary = ( select max(Salary) from employee;
 The above concept can be referred as sub query or nested query.
 Where we find, also a outer query vs inner query using a comparison operator.
What is SQL?
 – Structure Query Language(SQL) is a database query language used
for storing and managing data in Relational DBMS.
 – SQL was the first commercial language introduced for E.F
Codd's Relational model of database.
 – Almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) use
SQL as the standard database query language.
 – SQL is used to perform all types of data operations in RDBMS.
 – SQL lets you access and manipulate databases
SQL Structure

 A typical SQL query has the form:


 select A1, A2, ..., An
from r1, r2, ..., rm
where P
 » A  represent attributes
 » R  represent relations
 » P  is a predicate
The SELECT Clause

 SELECT query is used to retrieve data from a table. It is the most used SQL query.
 We can retrieve complete table data, or partial by specifying conditions using the WHERE
clause.
 Syntax of SELECT query
SELECT
column_name1, column_name2, ... column_nameN
FROM table_name;
Performing Simple Calculations using SELECT Query

 The select clause can contain arithmetic expressions involving


the operators, +, −, ∗, and /, and operating on constants or
attributes of tuples.
Example:
 SELECT eid, name, salary+3000 FROM employee;
The WHERE SQL clause

 WHERE clause is used to specify/apply any condition while retrieving, updating or


deleting data from a table.
 This clause is used mostly with SELECT, UPDATE and DELETE query.
 When we specify a condition using the WHERE clause then the query executes only for
those records for which the condition specified by the WHERE clause is true.
Cont..

 Operators for WHERE clause condition


 SQL uses the logical connectives and, or, and not.
 It allows the use of arithmetic expressions as operands to the comparison operators.
 Following is a list of operators that can be used while specifying the WHERE clause
condition.
Types of Operator in SQL

 SQL supports following types of operators:


 Arithmetic operators
 Comparison operators
 Logical operators
 Operators used to negate conditions.
SQL Arithmetic Operators

 SQL Arithmetic Operators are used to perform mathematical operations on the numerical
values.
 SQL provides following operators to perform mathematical operations.

Operator Description Example


+ Addition 10 + 20 = 30
- Subtraction 20 - 30 = -10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 5%2=1
SQL Comparison Operators
SQL Comparison Operators test whether two given expressions are the same or not. These
operators are used in SQL conditional statements while comparing one expression with
another.
Operator Description Example
= Equal to 5 = 5 returns TRUE
!= Not equal 5 != 6 returns TRUE
<> Not equal 5 <> 4 returns TRUE
> Greater than 4 > 5 returns FALSE
< Less than 4 < 5 returns TRUE
>= Greater than or equal to 4 >= 5 returns FALSE
<= Less than or equal to 4 <= 5 returns TRUE
!< Not less than 4 !< 5 returns FALSE
!> Not greater than 4 !> 5 returns TRUE
Comparison operators Example Queries.

 Example1: SELECT * FROM MATHS WHERE MARKS=50;


 SELECT * FROM MATHS WHERE MARKS>60;
 SELECT * FROM MATHS WHERE MARKS<40;
 SELECT * FROM MATHS WHERE MARKS>=80;
 Not equal to (<>) Operator: It returns the rows/tuples which have the value of
the attribute not equal to the given value.
 SELECT * FROM MATHS WHERE MARKS<>70; (not equal to the given
value).
AND and OR operators in SQL
 In SQL, the AND & OR operators are used for filtering the data and getting
precise results based on conditions.
 The SQL AND & OR operators are also used to combine multiple conditions.
These two operators can be combined to test for multiple conditions in a
SELECT, INSERT, UPDATE, or DELETE statement.
 When combining these conditions, it is important to use parentheses so that the
database knows what order to evaluate each condition.
 The AND and OR operators are used with the WHERE clause.
 SELECT * FROM table_name WHERE condition1 AND condition2 and …
conditionN;
OR

 SELECT * FROM table_name WHERE condition1 OR condition2 OR… conditionN;


 Example:
 SELECT * FROM Student WHERE Age = 18 AND ADDRESS = 'Delhi';
 SELECT * FROM Student WHERE Age = 18 AND NAME = ‘Hamza';
 SELECT * FROM Student WHERE NAME = ‘Hamza' OR NAME = ‘Ramya';
 SELECT * FROM Student WHERE NAME = 'Ramya' OR Age = 20;
Combining AND and OR

 We can combine AND and OR operators in the below manner to write complex queries.
 Syntax: SELECT * FROM table_name WHERE condition1 AND (condition2 OR
condition3);
 Example:
 SELECT * FROM Student WHERE Age = 18 AND (NAME = 'Ramya' OR NAME =
'Hamza');
Wildcard operators
 Wildcard operators are used with the LIKE operator, which is generally used to search the
data in the database and there are four basic operators %, _,-,[range_of_chracters].
 Let us explain all these operators in brief –

Operator Description

% It is used in substitute of zero or more characters.

_ It is used as a substitute for one character.

– It is used to substitute a range of characters.

It is used to fetch a matching set or range of


[range_of_characters]
characters specified inside the brackets.
Syntax for Wildcard operator
 Syntax:
 SELECT column1,column2 FROM table_name
WHERE column LIKE wildcard_operator;
 Example:
To fetch records from the Customer table with NAME starting with
the letter ‘A’.
 SELECT * FROM Customer WHERE CustomerName LIKE 'A%';
 Example: To fetch records from the Customer table with NAME with
the letter ‘A’ at any position.
 SELECT * FROM Customer WHERE CustomerName LIKE '%A%';
Using the _ Wildcard
 Example: To fetch records from the Customer table with NAME ending any letter
but starting from ‘Sal’.
 SELECT * FROM Customer WHERE CustomerName LIKE ‘Sal___';
 Using the [Charlist] Wildcard
 1. To fetch records from the Customer table with LastName containing letters ‘a,
‘b’, or ‘c’.
 Example:
 SELECT * FROM Customer WHERE LastName REGEXP '[A-C]';
Cont..

 To fetch records from the Customer table with LastName not containing letters ‘y’, or ‘z’.
 Query
 SELECT * FROM Students WHERE LastName NOT LIKE '%[y-z]%';
concatenation operator

 concatenation operator is use to link columns or character strings. We can also use
a literal. A literal is a character, number or date that is included in the SELECT
statement.
 Example:
 SELECT id, first_name, last_name, first_name || last_name,
salary, first_name || salary FROM myTable
 Note: Here above we have used || which is known as Concatenation operator which is
used to link 2 or as many columns as you want in your select query and it is independent
of the datatype of column.
 Here above we have linked 2 columns i.e, first_name+last_name as well
as first_name+salary
Example:

 SELECT id, first_name, last_name, salary,


first_name||' has salary '||salary as "new" FROM myTable

 Output: Harshith has salary 100000.


Relational Query Languages
 Query Language: It is a higher level than that of a standard
programming language.
 Categories:
 Procedural query language(SQL)
 Where, every instruction (Step by step) is passed inorder to fetch the data using
query.
 Non- procedural query language( Front-end )
 Where, we embed the queries in the application programming inoder to bring a
desired results for a user.
 Note: User is unaware of query how it is functioning on to the database.
Procedural query language

 A sequence of operations on to the database


 To compute the desired result
 What data is required
 How to retrieve those data
 Example for procedural query language: Relational Algebra.
Non- procedural query language

 Here, user describes only the desired information


 What data is required
 No need to describe how to retrieve those data
 Example for Non- procedural is Relational calculus
Relational Algebra
 Relational algebra is a set of operations on relation(s).
 It is a set of algebraic operations
 Input: one or more relations
 Output: A relation
 It provides a theortical foundation for relational databases
 Ex: Structured query language
 What Sql Does: Sql allows us to understand database operations in more
detail and motivate us to write optimized queries.
Relational Algebra Fundamental operations or Basic operators

 1) Projection
 2) Selection
 3) Union
 4) Cross product
 5)Rename
 6) set difference.
Basic operations:

• select, project, and rename operations are called unary operations, because they
operate on one relation.
• other three operations operate on pairs of relations and are, therefore, called
binary operations.
The Select Operation(σ)
 The select operation selects tuples that satisfy a given predicate. We use the
lowercase Greek letter sigma (σ) to denote selection. The predicate appears as a
subscript to σ. The argument relation is in parentheses after the σ.
For example, to select those tuples of the Instructor relation where the faculty is in
the “Physics” department, we write:
 σdept_name=“Physics”(Instructor)
Relational Algebra
Select ()_ Relation Algebra
Example 2:
Example3: using And (^)
Project
The Project Operation(pi (∏)):
 The project operation is a unary operation that returns its argument
relation , with certain attributes left out. Since a relation is a set, any duplicate rows
are eliminated.

 Projection is denoted by the uppercase Greek letter pi (∏). List those


attributes that we wish to appear in the result as a subscript to ∏ and argument
relation follows in parentheses.
Project (╥)
Example:
Example1: Output.
Example 2:
Output:
Union (U)
R Union S (RUS)
Example:
Case study:
Example: using case study for Union.
Set Difference(-)
Set Difference (Formal Example):
Set Difference(-)
Relational Algebra : Set difference Sol:
Cartesian product(x)
Example:
Guess the ambiguity in the above relation:

You might also like