SlideShare una empresa de Scribd logo
1 de 46
SQL
(Structured Query Language)
A LANGUAGE OF DATABASE
SQL Overview
SQL is a programming language for Relational Databases. It is designed over relational algebra
and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS.
SQL comprises both data definition and data manipulation languages. Using the data definition
properties of SQL, one can design and modify database schema, whereas data manipulation
properties allows SQL to store and retrieve data from database.
Characteristics of SQL
SQL allows the user to create, update, delete, and retrieve data from a database.
* SQL is very simple and easy to learn.
* SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL Sever etc.
Advantages of SQL
• High Speed:
SQL Queries can be used to retrieve large amounts of records from a database quickly and efficiently.
• Well Defined Standards Exist:
SQL databases use long-established standard, which is being adopted by ANSI & ISO. Non-SQL
databases do not adhere to any clear standard.
• No Coding Required:
Using standard SQL it is easier to manage database systems without having to write substantial
amount of code.
•Emergence of ORDBMS:
Previously SQL databases were synonymous with relational database. With the emergence of Object
Oriented DBMS, object storage capabilities are extended to relational databases.
Disadvantages of SQL
• Difficulty in Interfacing:
Interfacing an SQL database is more complex than adding a few lines of code.
• More Features Implemented in Proprietary way:
Although SQL databases conform to ANSI & ISO standards, some databases go for proprietary
extensions to standard SQL to ensure vendor lock-in.
SQL Data Types
1. BIGINT Data Type
2. BOOLEAN Data Type
3. CHAR Data Type
4. DECIMAL Data Type
5. DOUBLE Data Type
6. FLOAT Data Type
7. INT Data Type
8. SMALLINT Data Type
9. STRING Data Type
10. TIMESTAMP Data Type
11. TINYINT Data Type
12. VARCHAR Data Type
SQL Literals
The terms literal and constant value are synonymous and refer to a fixed data value
1. Numeric Literals
2. String Literals: String needs to be in single quotes
3. Boolean Literals: TRUE or FALSE
4. Timestamp Literals
5. NULL
String Literals
Use the text literal notation to specify values whenever 'string' or appears in the syntax of
expressions, conditions, SQL functions, and SQL statements in other parts of this reference
'Hello'
'ORACLE.dbs‘
q'!name LIKE '%DBMS_%%'!'
q'<'So,' she said, 'It's finished.'>‘
Numeric Literals
You must use the integer notation to specify an integer whenever integer appears in
expressions, conditions, SQL functions, and SQL statements described in other parts of this
reference. 25
+6.34
0.5
25e-03
-1
25f
+6.34F
0.5d
-1D
Date Time Literals
You can specify a DATE value as a string literal, or you can convert a character or numeric value
to a date value with the TO_DATE function. DATE literals are the only case in which Oracle
Database accepts a TO_DATE expression in place of a string literal.
To specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI
literal, as shown in this example:
DATE '1998-12-25‘
TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI')
Timestamp Literals
TIMESTAMP '1997-01-31 09:26:56.66 +02:00‘
TIMESTAMP '1999-04-15 8:00:00 US/Pacific‘ (with Zone)
Types of SQL Commands
1. Data Definition Language
2. Data Manipulation Language
Data Definition Language(DDL)
CREATE
Creates new databases, tables and views from RDBMS.
Create database tutorialspoint;
Create table article;
Create view for_students;
DROP
Drops commands, views, tables, and databases from RDBMS.
Drop object_type object_name;
Drop database tutorialspoint;
Drop table article;
Drop view for_students;
ALTER
Modifies database schema.
This command adds an attribute in the relation article with the
name subject of string type.
Alter table article add subject
varchar;
Data Manipulation Language(DML)
SQL is equipped with data manipulation language (DML). DML modifies the database instance by
inserting, updating and deleting its data. DML is responsible for all froms data modification in a
database. SQL contains the following set of commands in its DML section −
1. SELECT/FROM/WHERE
2. INSERT INTO/VALUES
3. UPDATE/SET/WHERE
4. DELETE FROM/WHERE
These basic constructs allow database programmers and users to enter data and information into the
database and retrieve efficiently using a number of filter options.
Select author_name From book_author Where age > 50;
INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])
UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]
DELETE FROM table_name [WHERE condition];
Tables
A relational database system contains one or more objects called tables. The data or information
for the database are stored in these tables. Tables are uniquely identified by their names and are
comprised of columns and rows. Columns contain the column name, data type, and any other
attributes for the column. Rows contain the records or data for the columns. Here is a sample
table called "weather".
city, state, high, and low are the columns. The rows contain the data for this table:
Weather
city state high low
Phoenix Arizona 105 90
Tucson Arizona 101 92
Flagstaff Arizona 88 69
San Diego California 77 60
Albuquerque New Mexico 80 72
Creating Table
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Syntax Example
PersonID LastName FirstName Address City
Insert into Table
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
INSERT INTO persons(PersonID,LastName,FirstName,Address,City)
VALUES(1011,’Mehta’,’Kunal’,’myaddress’,’Haridwar’);
CREATE TABLE persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
PersonID LastName FirstName Address City
1011 Mehta Kunal Myaddress Haridwar
SELECT STATEMENT
• SELECT column_name,column_name FROM table_name;
• SELECT * FROM table_name;
CustomerID CustomerName ContactName Address City PostalCode Country
1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany
2 RAM Ana Trujillo Avda. de la
Constitución
2222
México D.F. 05021 Mexico
3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
SELECT DISTINCT
• In a table, a column may contain many duplicate values; and sometimes you only want to list
the different (distinct) values.
• The DISTINCT keyword can be used to return only distinct (different) values.
CustomerID CustomerName ContactName Address City PostalCode Country
1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany
2 RAM Ana Trujillo Avda. de la
Constitución
2222
México D.F. 05021 Mexico
3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
SELECT DISTINCT column_name,column_name FROM table_name;
WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
SELECT * FROM Customers
WHERE Country='Mexico';
CustomerID CustomerName City Country
1 HARI Berlin Germany
2 RAM México D.F. Mexico
3 SHYAM México D.F. Mexico
AND & OR Clause
The AND operator displays a record if both the first condition AND the second condition are
true.
The OR operator displays a record if either the first condition OR the second condition is true.
CustomerID CustomerName City Country
1 HARI Berlin Germany
2 RAM México D.F. Mexico
3 SHYAM México D.F. Mexico
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
SELECT * FROM Customers
WHERE City='México D.F.'
OR City='München';
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');
DELETE STATEMENT
DELETE FROM table_name WHERE some_column=some_value;
CustomerID CustomerName City PostalCode Country
1 HARI Berlin 12209 Germany
2 RAM México D.F. 05021 Mexico
3 SHYAM México D.F. 05023 Mexico
DELETE FROM Customers WHERE CustomerName=‘Hari’ AND City=‘Berlin';
DELETE FROM Customers WHERE CustomerName=‘Ram’ AND Country=‘Germany';
UPDATE
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
CustomerID CustomerName City PostalCode Country
1 HARI Berlin 12209 Germany
2 RAM México D.F. 05021 Mexico
3 SHYAM México D.F. 05021 Mexico
CustomerID CustomerName City PostalCode Country
1 HARI Berlin 12209 Germany
2 RAM México D.F. 05021 Mexico
3 SHYAM Hamburg 05021 Germany
UPDATE Customers
SET City=‘Hamburg’,
COUNTRY=‘GERMANY’
WHERE CustomerName=‘SHYAM’;
CustomerID CustomerName City PostalCode Country
1 HARI Hamburg 12209 Germany
2 RAM Hamburg 05021 Germany
3 SHYAM Hamburg 05021 Germany
UPDATE Customers
SET City=‘Hamburg',
City=‘Germany';
ORDER BY Clause
The ORDER BY keyword is used to sort the result-set by one or more columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a
descending order, you can use the DESC keyword.
SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC;
SELECT * FROM Customers
ORDER BY Country;
CustomerID CustomerName City Country
1 HARI Berlin Germany
2 RAM México D.F. Mexico
3 SHYAM México D.F. Mexico
SELECT * FROM Customers
ORDER BY Country DESC;
DROP & TRUNCATE
DROP TABLE table_name
DROP DATABASE database_name
TRUNCATE TABLE table_name
ALTER TABLE STATEMENT
ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE table_name
DROP COLUMN column_name
P_Id FirstName Address City
1 Ola Timoteivn 10 Sandnes
2 Tove Borgvn 23 Sandnes
3 Kari Storgt 20 Stavanger
ALTER TABLE Persons
ADD DOB date
P_Id FirstName Address City DOB
1 Ola Timoteivn 10 Sandnes
2 Tove Borgvn 23 Sandnes
3 Kari Storgt 20 Stavange
r
ALTER TABLE Persons
ALTER COLUMN DOB year
Creating Views
Syntax:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Example:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
Query from View: SELECT * FROM [Current Product List]
Updating Views
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Example:
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
Aggregate Functions
1. AVG() - Returns the average value
2. COUNT() - Returns the number of rows
3. MAX() - Returns the largest value
4. MIN() - Returns the smallest value
5. SUM() - Returns the sum
SQL Scalar Functions
1. UCASE() - Converts a field to upper case
a) SELECT UCASE(column_name) FROM table_name;
2. LCASE() - Converts a field to lower case
a) SELECT LCASE(column_name) FROM table_name;
3. MID() - Extract characters from a text field
a) SELECT SUBSTRING(column_name,start,length) AS some_name FROM table_name;
4. LEN() - Returns the length of a text field
5. ROUND() - Rounds a numeric field to the number of decimals specified
6. NOW() - Returns the current system date and time
7. FORMAT() - Formats how a field is to be displayed
a) SELECT ProductName, Price, FORMAT(Now(),'YYYY-MM-DD') AS PerDate FROM Products;
LIKE
The LIKE operator is used to search for a specified pattern in a column.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
SELECT * FROM Customers
WHERE City LIKE 's%';
SELECT * FROM Customers
WHERE Country LIKE '%land%';
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';
IN
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
SELECT * FROM Customers
WHERE City IN ('Paris','London');
BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
◦ SQL statement selects all products with a price BETWEEN 10 and 20
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
◦ To display the products outside the range of the previous example, use NOT BETWEEN
Joins
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
There are four types of JOINS.
1. INNER JOIN: Returns all rows when there is at least one match in BOTH tables
2. LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
3. RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
4. FULL JOIN: Return all rows when there is a match in ONE of the tables
Inner Join
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo
Emparedados y
helados
Ana Trujillo Mexico
3 Antonio Moreno
Taquería
Antonio Moreno Mexico
SELECT Orders.OrderID, Customers.CustomerName,
Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
OrderID CustomerName OrderDate
10308 Ana Trujillo Emparedados y helados 9/18/1996
Output:
Customers
Orders
…
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
Left Join
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in
the right table (table2). The result is NULL in the right side when there is no match.
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
…
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo
Emparedados y
helados
Ana Trujillo Mexico
3 Antonio Moreno
Taquería
Antonio Moreno Mexico
CustomerName OrderID
Alfreds Futterkiste null
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería null
Customers
Orders
Output:
Right Join
The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in
the left table (table1). The result is NULL in the left side when there is no match.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
or
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
…
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
RIGHT JOIN Customers
ON Orders.CustomerID=Customers.CustomerID
ORDER BY Orders.OrderID;
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo
Emparedados y
helados
Ana Trujillo Mexico
3 Antonio Moreno
Taquería
Antonio Moreno Mexico
Customers
Orders
Output:
OrderID CustomerName
Alfreds Futterkiste
10309 Ana Trujillo Emparedados y helados
Antonio Moreno Taquería
Full Join or Full Outer Join
• The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right
table (table2).
• The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
…
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo
Emparedados y
helados
Ana Trujillo Mexico
3 Antonio Moreno
Taquería
Antonio Moreno Mexico
Customers
Orders
Output:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
CustomerName OrderID
Alfreds Futterkiste
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería
10309
10310
Union
The UNION operator is used to combine the result-set of two or more SELECT statements.
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Syntax:
This will list all
the DISTINCT city
names from both the
tables.
Output:Query:
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Syntax:
This will list all
the city names
includes duplicate
from both the
tables.
Output:Query:
SQL Operators
1. Arithmetic Operators
2. BETWEEN Operator
3. Comparison Operators
4. EXISTS Operator
5. IN Operator
6. IS NULL Operator
7. LIKE Operator
8. Logical Operators
9. REGEXP Operator
10. RLIKE Operator
Intersection
Minus
THANKS

Más contenido relacionado

La actualidad más candente

introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functionsfarwa waqar
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)Syed Hassan Ali
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)Ishucs
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Sabana Maharjan
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functionsAmrit Kaur
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQLrehaniltifat
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity ConstraintsMegha yadav
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJDharita Chokshi
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)pptGowarthini
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 

La actualidad más candente (20)

introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
Mysql
MysqlMysql
Mysql
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
SQL
SQLSQL
SQL
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
 
Rdbms
RdbmsRdbms
Rdbms
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)ppt
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 

Similar a SQL Queries Information

Similar a SQL Queries Information (20)

LECTURE NOTES.pdf
LECTURE NOTES.pdfLECTURE NOTES.pdf
LECTURE NOTES.pdf
 
LECTURE NOTES.pdf
LECTURE NOTES.pdfLECTURE NOTES.pdf
LECTURE NOTES.pdf
 
Database Management Lab -SQL Queries
Database Management Lab -SQL Queries Database Management Lab -SQL Queries
Database Management Lab -SQL Queries
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
DBMS Part-3.pptx
DBMS Part-3.pptxDBMS Part-3.pptx
DBMS Part-3.pptx
 
Sql
SqlSql
Sql
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Lab
LabLab
Lab
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
 
DBMS
DBMSDBMS
DBMS
 
12 SQL
12 SQL12 SQL
12 SQL
 
12 SQL
12 SQL12 SQL
12 SQL
 
ADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptxADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptx
 
Sql
SqlSql
Sql
 
lovely
lovelylovely
lovely
 
C# Basic Tutorial
C# Basic TutorialC# Basic Tutorial
C# Basic Tutorial
 

Más de Nishant Munjal

Database Management System
Database Management SystemDatabase Management System
Database Management SystemNishant Munjal
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointerNishant Munjal
 
Introduction to computers
Introduction to computersIntroduction to computers
Introduction to computersNishant Munjal
 
Shell Programming Concept
Shell Programming ConceptShell Programming Concept
Shell Programming ConceptNishant Munjal
 
Asynchronous Transfer Mode
Asynchronous Transfer ModeAsynchronous Transfer Mode
Asynchronous Transfer ModeNishant Munjal
 
Overview of Cloud Computing
Overview of Cloud ComputingOverview of Cloud Computing
Overview of Cloud ComputingNishant Munjal
 
Database Design and Normalization Techniques
Database Design and Normalization TechniquesDatabase Design and Normalization Techniques
Database Design and Normalization TechniquesNishant Munjal
 
Transaction Processing Concept
Transaction Processing ConceptTransaction Processing Concept
Transaction Processing ConceptNishant Munjal
 
Database Management System
Database Management SystemDatabase Management System
Database Management SystemNishant Munjal
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model IntroductionNishant Munjal
 
Virtualization, A Concept Implementation of Cloud
Virtualization, A Concept Implementation of CloudVirtualization, A Concept Implementation of Cloud
Virtualization, A Concept Implementation of CloudNishant Munjal
 
Technical education benchmarks
Technical education benchmarksTechnical education benchmarks
Technical education benchmarksNishant Munjal
 

Más de Nishant Munjal (20)

Database Management System
Database Management SystemDatabase Management System
Database Management System
 
Functions & Recursion
Functions & RecursionFunctions & Recursion
Functions & Recursion
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Introduction to computers
Introduction to computersIntroduction to computers
Introduction to computers
 
Unix Administration
Unix AdministrationUnix Administration
Unix Administration
 
Shell Programming Concept
Shell Programming ConceptShell Programming Concept
Shell Programming Concept
 
VI Editor
VI EditorVI Editor
VI Editor
 
Introduction to Unix
Introduction to UnixIntroduction to Unix
Introduction to Unix
 
Routing Techniques
Routing TechniquesRouting Techniques
Routing Techniques
 
Asynchronous Transfer Mode
Asynchronous Transfer ModeAsynchronous Transfer Mode
Asynchronous Transfer Mode
 
Overview of Cloud Computing
Overview of Cloud ComputingOverview of Cloud Computing
Overview of Cloud Computing
 
Database Design and Normalization Techniques
Database Design and Normalization TechniquesDatabase Design and Normalization Techniques
Database Design and Normalization Techniques
 
Concurrency Control
Concurrency ControlConcurrency Control
Concurrency Control
 
Transaction Processing Concept
Transaction Processing ConceptTransaction Processing Concept
Transaction Processing Concept
 
Database Management System
Database Management SystemDatabase Management System
Database Management System
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model Introduction
 
Virtualization, A Concept Implementation of Cloud
Virtualization, A Concept Implementation of CloudVirtualization, A Concept Implementation of Cloud
Virtualization, A Concept Implementation of Cloud
 
Technical education benchmarks
Technical education benchmarksTechnical education benchmarks
Technical education benchmarks
 
Bluemix Introduction
Bluemix IntroductionBluemix Introduction
Bluemix Introduction
 

Último

BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfSuman Jyoti
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spaintimesproduction05
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 

Último (20)

BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 

SQL Queries Information

  • 1. SQL (Structured Query Language) A LANGUAGE OF DATABASE
  • 2. SQL Overview SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS. SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database.
  • 3. Characteristics of SQL SQL allows the user to create, update, delete, and retrieve data from a database. * SQL is very simple and easy to learn. * SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL Sever etc.
  • 4. Advantages of SQL • High Speed: SQL Queries can be used to retrieve large amounts of records from a database quickly and efficiently. • Well Defined Standards Exist: SQL databases use long-established standard, which is being adopted by ANSI & ISO. Non-SQL databases do not adhere to any clear standard. • No Coding Required: Using standard SQL it is easier to manage database systems without having to write substantial amount of code. •Emergence of ORDBMS: Previously SQL databases were synonymous with relational database. With the emergence of Object Oriented DBMS, object storage capabilities are extended to relational databases.
  • 5. Disadvantages of SQL • Difficulty in Interfacing: Interfacing an SQL database is more complex than adding a few lines of code. • More Features Implemented in Proprietary way: Although SQL databases conform to ANSI & ISO standards, some databases go for proprietary extensions to standard SQL to ensure vendor lock-in.
  • 6. SQL Data Types 1. BIGINT Data Type 2. BOOLEAN Data Type 3. CHAR Data Type 4. DECIMAL Data Type 5. DOUBLE Data Type 6. FLOAT Data Type 7. INT Data Type 8. SMALLINT Data Type 9. STRING Data Type 10. TIMESTAMP Data Type 11. TINYINT Data Type 12. VARCHAR Data Type
  • 7. SQL Literals The terms literal and constant value are synonymous and refer to a fixed data value 1. Numeric Literals 2. String Literals: String needs to be in single quotes 3. Boolean Literals: TRUE or FALSE 4. Timestamp Literals 5. NULL
  • 8. String Literals Use the text literal notation to specify values whenever 'string' or appears in the syntax of expressions, conditions, SQL functions, and SQL statements in other parts of this reference 'Hello' 'ORACLE.dbs‘ q'!name LIKE '%DBMS_%%'!' q'<'So,' she said, 'It's finished.'>‘ Numeric Literals You must use the integer notation to specify an integer whenever integer appears in expressions, conditions, SQL functions, and SQL statements described in other parts of this reference. 25 +6.34 0.5 25e-03 -1 25f +6.34F 0.5d -1D
  • 9. Date Time Literals You can specify a DATE value as a string literal, or you can convert a character or numeric value to a date value with the TO_DATE function. DATE literals are the only case in which Oracle Database accepts a TO_DATE expression in place of a string literal. To specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal, as shown in this example: DATE '1998-12-25‘ TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI') Timestamp Literals TIMESTAMP '1997-01-31 09:26:56.66 +02:00‘ TIMESTAMP '1999-04-15 8:00:00 US/Pacific‘ (with Zone)
  • 10. Types of SQL Commands 1. Data Definition Language 2. Data Manipulation Language
  • 11. Data Definition Language(DDL) CREATE Creates new databases, tables and views from RDBMS. Create database tutorialspoint; Create table article; Create view for_students; DROP Drops commands, views, tables, and databases from RDBMS. Drop object_type object_name; Drop database tutorialspoint; Drop table article; Drop view for_students; ALTER Modifies database schema. This command adds an attribute in the relation article with the name subject of string type. Alter table article add subject varchar;
  • 12. Data Manipulation Language(DML) SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all froms data modification in a database. SQL contains the following set of commands in its DML section − 1. SELECT/FROM/WHERE 2. INSERT INTO/VALUES 3. UPDATE/SET/WHERE 4. DELETE FROM/WHERE These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options. Select author_name From book_author Where age > 50; INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ]) UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition] DELETE FROM table_name [WHERE condition];
  • 13. Tables A relational database system contains one or more objects called tables. The data or information for the database are stored in these tables. Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column. Rows contain the records or data for the columns. Here is a sample table called "weather". city, state, high, and low are the columns. The rows contain the data for this table: Weather city state high low Phoenix Arizona 105 90 Tucson Arizona 101 92 Flagstaff Arizona 88 69 San Diego California 77 60 Albuquerque New Mexico 80 72
  • 14. Creating Table CREATE TABLE table_name ( column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size), .... ); CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); Syntax Example PersonID LastName FirstName Address City
  • 15. Insert into Table INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...); INSERT INTO persons(PersonID,LastName,FirstName,Address,City) VALUES(1011,’Mehta’,’Kunal’,’myaddress’,’Haridwar’); CREATE TABLE persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); PersonID LastName FirstName Address City 1011 Mehta Kunal Myaddress Haridwar
  • 16. SELECT STATEMENT • SELECT column_name,column_name FROM table_name; • SELECT * FROM table_name; CustomerID CustomerName ContactName Address City PostalCode Country 1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany 2 RAM Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
  • 17. SELECT DISTINCT • In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values. • The DISTINCT keyword can be used to return only distinct (different) values. CustomerID CustomerName ContactName Address City PostalCode Country 1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany 2 RAM Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico SELECT DISTINCT column_name,column_name FROM table_name;
  • 18. WHERE Clause The WHERE clause is used to extract only those records that fulfill a specified criterion. SELECT column_name,column_name FROM table_name WHERE column_name operator value; SELECT * FROM Customers WHERE Country='Mexico'; CustomerID CustomerName City Country 1 HARI Berlin Germany 2 RAM México D.F. Mexico 3 SHYAM México D.F. Mexico
  • 19. AND & OR Clause The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. CustomerID CustomerName City Country 1 HARI Berlin Germany 2 RAM México D.F. Mexico 3 SHYAM México D.F. Mexico SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; SELECT * FROM Customers WHERE City='México D.F.' OR City='München'; SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');
  • 20. DELETE STATEMENT DELETE FROM table_name WHERE some_column=some_value; CustomerID CustomerName City PostalCode Country 1 HARI Berlin 12209 Germany 2 RAM México D.F. 05021 Mexico 3 SHYAM México D.F. 05023 Mexico DELETE FROM Customers WHERE CustomerName=‘Hari’ AND City=‘Berlin'; DELETE FROM Customers WHERE CustomerName=‘Ram’ AND Country=‘Germany';
  • 21. UPDATE UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value; CustomerID CustomerName City PostalCode Country 1 HARI Berlin 12209 Germany 2 RAM México D.F. 05021 Mexico 3 SHYAM México D.F. 05021 Mexico
  • 22. CustomerID CustomerName City PostalCode Country 1 HARI Berlin 12209 Germany 2 RAM México D.F. 05021 Mexico 3 SHYAM Hamburg 05021 Germany UPDATE Customers SET City=‘Hamburg’, COUNTRY=‘GERMANY’ WHERE CustomerName=‘SHYAM’; CustomerID CustomerName City PostalCode Country 1 HARI Hamburg 12209 Germany 2 RAM Hamburg 05021 Germany 3 SHYAM Hamburg 05021 Germany UPDATE Customers SET City=‘Hamburg', City=‘Germany';
  • 23. ORDER BY Clause The ORDER BY keyword is used to sort the result-set by one or more columns. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. SELECT column_name, column_name FROM table_name ORDER BY column_name ASC|DESC; SELECT * FROM Customers ORDER BY Country; CustomerID CustomerName City Country 1 HARI Berlin Germany 2 RAM México D.F. Mexico 3 SHYAM México D.F. Mexico SELECT * FROM Customers ORDER BY Country DESC;
  • 24. DROP & TRUNCATE DROP TABLE table_name DROP DATABASE database_name TRUNCATE TABLE table_name
  • 25. ALTER TABLE STATEMENT ALTER TABLE table_name ADD column_name datatype ALTER TABLE table_name DROP COLUMN column_name P_Id FirstName Address City 1 Ola Timoteivn 10 Sandnes 2 Tove Borgvn 23 Sandnes 3 Kari Storgt 20 Stavanger ALTER TABLE Persons ADD DOB date P_Id FirstName Address City DOB 1 Ola Timoteivn 10 Sandnes 2 Tove Borgvn 23 Sandnes 3 Kari Storgt 20 Stavange r ALTER TABLE Persons ALTER COLUMN DOB year
  • 26. Creating Views Syntax: CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Example: CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No Query from View: SELECT * FROM [Current Product List]
  • 27. Updating Views Syntax: CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Example: CREATE OR REPLACE VIEW [Current Product List] AS SELECT ProductID,ProductName,Category FROM Products WHERE Discontinued=No
  • 28. Aggregate Functions 1. AVG() - Returns the average value 2. COUNT() - Returns the number of rows 3. MAX() - Returns the largest value 4. MIN() - Returns the smallest value 5. SUM() - Returns the sum
  • 29. SQL Scalar Functions 1. UCASE() - Converts a field to upper case a) SELECT UCASE(column_name) FROM table_name; 2. LCASE() - Converts a field to lower case a) SELECT LCASE(column_name) FROM table_name; 3. MID() - Extract characters from a text field a) SELECT SUBSTRING(column_name,start,length) AS some_name FROM table_name; 4. LEN() - Returns the length of a text field 5. ROUND() - Rounds a numeric field to the number of decimals specified 6. NOW() - Returns the current system date and time 7. FORMAT() - Formats how a field is to be displayed a) SELECT ProductName, Price, FORMAT(Now(),'YYYY-MM-DD') AS PerDate FROM Products;
  • 30. LIKE The LIKE operator is used to search for a specified pattern in a column. SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern; SELECT * FROM Customers WHERE City LIKE 's%'; SELECT * FROM Customers WHERE Country LIKE '%land%'; SELECT * FROM Customers WHERE Country NOT LIKE '%land%';
  • 31. IN SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...); SELECT * FROM Customers WHERE City IN ('Paris','London');
  • 32. BETWEEN SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; ◦ SQL statement selects all products with a price BETWEEN 10 and 20 SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20; ◦ To display the products outside the range of the previous example, use NOT BETWEEN
  • 33. Joins An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. There are four types of JOINS. 1. INNER JOIN: Returns all rows when there is at least one match in BOTH tables 2. LEFT JOIN: Return all rows from the left table, and the matched rows from the right table 3. RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table 4. FULL JOIN: Return all rows when there is a match in ONE of the tables
  • 34. Inner Join OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; OrderID CustomerName OrderDate 10308 Ana Trujillo Emparedados y helados 9/18/1996 Output: Customers Orders
  • 35. … SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name; SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name;
  • 36. Left Join The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. Syntax: SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name; or SELECT column_name(s) FROM table1 LEFT OUTER JOIN table2 ON table1.column_name=table2.column_name;
  • 37. … SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico CustomerName OrderID Alfreds Futterkiste null Ana Trujillo Emparedados y helados 10308 Antonio Moreno Taquería null Customers Orders Output:
  • 38. Right Join The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match. SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name=table2.column_name; or SELECT column_name(s) FROM table1 RIGHT OUTER JOIN table2 ON table1.column_name=table2.column_name;
  • 39. … SELECT Orders.OrderID, Customers.CustomerName FROM Orders RIGHT JOIN Customers ON Orders.CustomerID=Customers.CustomerID ORDER BY Orders.OrderID; OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico Customers Orders Output: OrderID CustomerName Alfreds Futterkiste 10309 Ana Trujillo Emparedados y helados Antonio Moreno Taquería
  • 40. Full Join or Full Outer Join • The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2). • The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins. SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name;
  • 41. … OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico Customers Orders Output: SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; CustomerName OrderID Alfreds Futterkiste Ana Trujillo Emparedados y helados 10308 Antonio Moreno Taquería 10309 10310
  • 42. Union The UNION operator is used to combine the result-set of two or more SELECT statements. SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City; SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2; SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; Syntax: This will list all the DISTINCT city names from both the tables. Output:Query: SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City; SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2; Syntax: This will list all the city names includes duplicate from both the tables. Output:Query:
  • 43. SQL Operators 1. Arithmetic Operators 2. BETWEEN Operator 3. Comparison Operators 4. EXISTS Operator 5. IN Operator 6. IS NULL Operator 7. LIKE Operator 8. Logical Operators 9. REGEXP Operator 10. RLIKE Operator
  • 45. Minus