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

Introduction SQL

This document discusses SQL commands and concepts. It covers creating and manipulating databases and tables using DDL, DML, and DCL statements. It also covers retrieving data using SELECT statements, joins, aggregation functions and grouping data.

Uploaded by

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

Introduction SQL

This document discusses SQL commands and concepts. It covers creating and manipulating databases and tables using DDL, DML, and DCL statements. It also covers retrieving data using SELECT statements, joins, aggregation functions and grouping data.

Uploaded by

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

Introduction to SQL

Chapter 3
Introduction to SQL
• SQL : Structural Query Language
• It is used for storing, manipulation, and retrieving data from the
database.
• SQL is an ANSI (American National Standards Institute) standard
language, but there are many different versions of the SQL language.
• SQL history
• Installation of MySQL workbench
SQL Commands
• These commands can be classified into the following groups based on
their nature:
1. DDL: Data definition language
• CREATE, ALTER, DROP
2. DML - Data Manipulation Language
• SELECT, INSERT, UPDATE, DELETE
3. DCL - Data Control Language
• GRANT, REVOKE
4. TCL-Transaction Control Language
• COMMIT, ROLLBACK, SAVEPOINT
Section 1

Database creation and Updates


DDL statements
Database design
• Steps of database design
1. Conceptual design
2. ER model
3. Database Schema
4. Implementing it using SQL
Data types in SQL
Numeric data type in SQL
String data types

String

Fixed length Variable length Enum

Units
Currency (Char) Title (Varchar)
(“millions,”Billion”)
Date time data types
Create Database
• It creates new database schema
• Syntax: CREATE DATABASE database_name;
• To check whether a database exists or not
• Syntax: show databases
• Drop database
• Syntax: DROP DATABASE database_name
Create table
• Syntax:
• CREATE TABLE table_name( column1 datatype, column2 datatype, column3
datatype, ..... columnN datatype,
PRIMARY KEY( one or more columns ) );
• Example: CREATE TABLE cutomer(id integer, first_name varchar(10),
last_name varchar(10), city varchar(10), country varchar(15), phone
varchar(15));
• To check schema of a table:
• DESC tablename;
Insert into
• Insert into:
• Syntax: INSERT INTO table_name( column1, column2....columnN) VALUES
( value1, value2....valueN);
• Example:INSERT INTO customer(id , first_name,
last_name ,city ,country,phone)VALUES (2, ‘Ana’, ‘Trujillo’, ‘Mexico’, ‘Mexico’,
(5) 555-4729);
• If users are adding values for all the columns of the table, you don’t
need to specify the particular column names in the SQL query.
• However, ensure the order of the values is in the same order as the
columns in the table.
Alter and update table
• Alter table:
• Syntax: ALTER TABLE table_name {ADD|DROP|MODIFY} column_name
{data_ype};
• ALTER TABLE table_name RENAME TO new_table_name;
• Update table:
• UPDATE table_name SET column1 = value1, column2 =
value2....columnN=valueN [ WHERE CONDITION ];
• Rename column and table
• ALTER TABLE members RENAME COLUMN join_date TO jd;
• Alter table customer_details rename to cust_details;
Delete, Drop, Truncate
• The DROP TABLE statement in SQL is used to drop an existing table in
a database.(drop structure also)
• Syntax: DROP TABLE table name;
• Delete: (delete only row)
• DELETE FROM table_name WHERE {CONDITION};
• Truncate: (delete only data
• TRUNCATE TABLE table_name;
SQL constraints
• The Constraints in SQL can be specified when the table is created with
the CREATE TABLE statement, or after the table is altered with the ALTER
TABLE statement.
• Syntax: CREATE TABLE table_name ( column1 datatype constraint,
column2 datatype constraint, column3 datatype constraint, .... );
• SQL constraints are used to specify any rules for the records in a table.
• Constraints can be used to limit the type of data that can go into a table.
• if there is any violation between the constraint and the record action, the
action is aborted.
• Constraints can be column level or table level.
Constraints using alter table
• Add unique constraint:
• ALTER TABLE persons ADD UNIQUE (first_name);
• ALTER TABLE person ADD CONSTRAINT UC_person UNIQUE (age, last_name);
• Drop constraint
• ALTER TABLE person DROP CONSTRAINT UC_Person;
Section 2
Data retrieval from single table
SQL Query
• A database most often contains tables. Some name identifies each table. The table
includes records(rows) with Data. To access those records, we need SQL Syntax. Most of
the action you need to perform Database by using the SQL Statement.
• Note: SQL keywords are not case-sensitive (e.g., select as SELECT)
• Keywords include SELECT, UPDATE, WHERE, ORDER BY ETC. Four fundamental
operations that can apply to any databases are:
• Read the Data -- SELECT
• Insert the new Data -- INSERT
• Update existing Data -- UPDATE
• Remove Data –DELETE
• These operations are referred to as the CRUD (Create, Read, Update, Delete).
Movie dataset
• For all the queries in upcoming slides we will use Movie dataset
• Import dataset in MySQL workbench
• First try to understand dataset using excel file of the dataset
• In excel file for one table there is one sheet
SELECT Statement
• The SELECT statement permits you to read data from one or more
tables.
• Syntax:
SELECT column1, column2, ,columnN
FROM table_name;
• Examples:
• Simply print all the movies
• Get movie title and industry for all the movies
SELECT DISTINCT

• The SELECT DISTINCT statement is to return the different values.


• Syntax:
SELECT DISTINCT column1, column2. column
FROM table_name;
• Example:
• Get all the unique studio in the movies database
WHERE CLAUSE
• The WHERE clause allows the user to filter the data from the table. The WHERE
clause allows the user to extract only those records that satisfy a specified
condition.
• SQL requires single quotes around text values (many database systems will also
use double quotes). And numeric fields should not be enclosed in quotes.
• Syntax:
SELECT column1, column2, columnN
FROM table_name WHERE CONDITION;
• Example:
• Print all movies from Hollywood
SQL AND/OR Clause
• To merge more than one conditions
• Syntax:
SELECT column1, column2. columnN
FROMtable_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
• Example:
• Which movies had greater than 9 imdb rating?
• Movies with rating between 6 and 8
• Select all movies whose release year can be 2018 or 2019 or 2022
IN clause
• IN: Specify multiple possible values for a column
• Syntax:
SELECT column1, column2. columnN
FROMtable_name
WHERE column_name IN (val-1, val-2,val-N);
• Example:
• Select all movies whose release year can be 2018 or 2019 or 2022
BETWEEN Clause
• BETWEEN: Between a range
• Syntax:
SELECT column1, column2. columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
• Example:
• Movies with rating between 6 and 8
LIKE Clause
• LIKE: To find pattern
• Syntax:
SELECT column1, column2. columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
• Pattern contains two symbols: %(any number of character) and _(one
character)
• Example:
• Select all movies that starts with THOR
• Select all movies that have 'America' word in it.
COUNT Clause
• COUNT: To calculate total rows in the column
• Syntax:
SELECT COUNT(column_name) FROM table_name
WHERE CONDITION;
• Example:
• How many total movies do we have in our movies table?
• How many hollywood movies are present in the database?
IS NULL and IS NOT NULL
• IS NULL: To check if column value is empty
• Syntax:
SELECT column1, column2. columnN
FROMtable_name
WHERE column_name IS NULL;
• Example:
• Print all movies where we don't know the value of the studio
• All movies where imdb rating is not available
• All movies where imdb rating is available
ORDER BY
• ORDER BY: To sort rows bases on values of a column
• Syntax:
SELECT column1, column2. columnN
FROM table_name WHERE CONDITION
ORDER BY column_name {ASC|DESC}
LIMIT top_values_required
OFFSET how_many_top_values_to_skip;
• Example:
• Print first 5 bollywood movies with highest rating
• Select movies starting from second highest rating movie till next 5 movies from bollywood
Summary analytics(MAX, MIN, AVG,SUM)
• Syntax:
SELECT function(column_name) AS alias
FROMtable_name
WHERE CONDITION;
• Example:
• Select highest imdb rating for bollywood movies
• Select lowest imdb rating for bollywood movies
• Print average rating of Marvel Studios movies
• Print min, max, avg rating of Marvel Studios movies
GROUP BY
• The GROUP BY used to group rows from the table
• It is often used with aggregate functions like (COUNT, MAX, MIN, SUM, AVG) to group the result-set by
one or more columns.
• Columns in the group by must be in select statement
• Syntax:
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
• Example:
• Print count and average imdb rating of movies for each industry
• Count number of movies released by a given production studio(hint: do not incude which doesn’t have studio
information)
• What is the average rating of movies per studio and also order them by average rating in descending format?
• Find maximum imdb_rating of each industry
HAVING Clause
• The HAVING clause is added to SQL because the WHERE keyword can
not be used with aggregate functions.
• Syntax:
SELECT SUM(column_name)
FROMtable_name WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
• Example:
• Print all the years where more than 2 movies were released
Rules for Having clause
• Order of execution
FROM ->WHERE->GROUP BY ->HAVING->ORDER BY
• Columns used in Having must be present in select.
• Columns used in where may not be in select
Section 3
Data retrieval from multiple tables
Complex Queries
Joins
• The SQL Join help in retrieving data from two or more database
tables. The tables are mutually related using primary keys and foreign
keys.
• The INNER JOIN is used to print rows from both tables that satisfy the
given condition.
• The INNER JOIN keyword selects records that have matching values in
both the tables.
Inner join
• Syntax:
SELECT column_name(s) FROM table1 t1
INNER JOIN
table2 t2 ON t1.column_name = t2.column_name;
• Syntax:
SELECT column_name(s) FROM table1 t1 INNER JOIN table2 t2 USING
(column_name);
• Example: Print all movies along with their title, budget, revenue,
currency and unit.
Left outer join
• The LEFT JOIN returns all the records from the table1 (left table) and
the matched records from the table2 (right table). The output is NULL
from the right side if there is no match.
• Syntax:
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON
table1.column_name = table2.column_name;
• Sholay and inception doesn’t have info in financials
Right join
• The RIGHT JOIN is the opposite of LEFT JOIN.
• The RIGHT JOIN prints all the columns from the table2(right table) even
if there no matching rows have been found in the table1 (left table).
• If there no matches have been found in the table1 (left table), NULL is
returned
• Syntax:
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON
table1.column_name = table2.column_name;
• 402 and 416 doesn’t have info in movies
Full outer join
• The FULL OUTER JOIN keyword returns all records when there are a match in left
(table1) or right (table2) table records.
• Syntax:
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON
table1.column_name = table2.column_name WHERE condition
• Note: MySQL does not support the Full Join, so we can perform left join and right
join separately then take the union of them.
• Syntax:
SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1 RIGHT JOIN t2 ON t1.id = t2.id
Union
• The UNION operator allows the user to combine the result-set of two or
more SELECT statements in SQL.
• Each SELECT statement within UNION should have the same number of
columns.
• The columns in each SELECT statement should also be in the same order.
• The columns should also have similar data types.
• Syntax:
Select column_name(s) from table1
UNION
Select column_name(s) from table2;
Union All
• The UNION operator selects only different values by default.
• To allow duplicate values, the user can use UNION ALL operator.
• Syntax:
SELECT column_name(s) FROM table1 UNION ALL SELECT
column_name(s) FROM table2;
Group_concat
• The GROUP_CONCAT() function in MySQL is used to concatenate data
from multiple rows into one field.
• This is an aggregate (GROUP BY) function which returns a String value,
if the group contains at least one non-NULL value. Otherwise, it
returns NULL.
• Syntax:
Select count(*), group_concat(title separator “,”) from movies group by
industry
Subquery
• A subquery in MySQL is a query, which is nested into another SQL query and
embedded with SELECT, INSERT, UPDATE or DELETE statement along with the
various operators.
• We can also nest the subquery with another subquery. A subquery is known as
the inner query, and the query that contains subquery is known as the outer
query.
• The inner query executed first gives the result to the outer query, and then the
main/outer query will be performed.
• MySQL allows us to use subquery anywhere, but it must be closed within
parenthesis.
• All subquery forms and operations supported by the SQL standard will be
supported in MySQL also.
Rules for subqueries
• Subqueries should always use in parentheses.
• If the main query does not have multiple columns for subquery, then
a subquery can have only one column in the SELECT command.
• We can use various comparison operators with the subquery, such as
>, <, =, IN, ANY, SOME, and ALL. A multiple-row operator is very useful
when the subquery returns more than one row.
• We cannot use the ORDER BY clause in a subquery, although it can be
used inside the main query.
• If we use a subquery in a set function, it cannot be immediately
enclosed in a set function.
Subqueries
• Syntax:
SELECT column_list (s) FROM table_name
WHERE column_name OPERATOR
(SELECT column_list (s) FROM table_name [WHERE])
SQL queries
• Select a movie with highest imdb_rating
• select all movies whose rating is greater than *any* of the marvel
movies rating
• select all movies whose rating is greater than *all* of the marvel
movies rating
SQL Databases
Lecture 4
Nikita Joshi
Advanced SQL concepts
Table of content
• Common table expression (CTE)
• View
Common Table Expressions(CTE)
• common table expression (CTE) is a temporary named result set that
you can reference within a SELECT, INSERT, UPDATE, or DELETE
statement.
• You can also use a CTE in a CREATE a view, as part of the view’s SELECT
query
• Syntax:
WITH cte_name (column_names) AS (query)
SELECT * FROM cte_name;
• Select statement of cte is valid only its scope, after its scope (;) its not
valid
• We can have multiple CTEs at a time
• Syntax:
With cte1 as select (),
Cte2 as select(),
Select * from cte1 join cte2;
• Recursive CTE
WITH RECURSIVE
odd_num_cte (id, n) AS
(
SELECT 1, 1
union all
SELECT id+1, n+2 from odd_num_cte where id < 5
)
SELECT * FROM odd_num_cte;
SQL queries
• Select all the actors whose age is greater than 70 and less than 85
• Movies that produced 500% profit and their rating was less than
average rating for all movies
• select all hollywood movies released after year 2000 that made more
than 500 millions $ profit or more profit.
• find average profit of each movie industry
• Find average profit each actor
Views
• The view is a virtual table based on the result-set of an SQL statement. A
view holds rows and columns, similar to a real table.
• You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table.
• Syntax:
CREATE VIEW view_name
AS SELECT column1, column2, ... FROM table_name
WHERE condition;
• A view always shows up-to-date data! The database engine recreates the
data, using the view's SQL statement, every time a user queries a view.
SQL query
• Create view which has % profit of each movie.
• Create view which has all the details of actors and their age.
WITH CHECK OPTION
• The WITH CHECK OPTION in SQL is a CREATE VIEW statement option.
• The objective of the WITH CHECK OPTION is to make sure that all UPDATE
and INSERTs satisfy the condition(s) in the view definition.
• If they do not satisfy the condition(s), the UPDATE or INSERT returns an
error.
• Syntax:
CREATE VIEW CUSTOMER_VIEW AS
SELECT name, age FROM customers
WHERE age IS NOT NULL
WITH CHECK OPTION;
DELETING ROWS INTO A VIEW
• Rows of data can be deleted from a view. The same rules that apply to the
UPDATE and INSERT commands apply to the DELETE command.
• DELETE FROM CUSTOMER_VIEW WHERE age = 25;
• If you are deleting from the table which contains primary key run this
command before;
SET FOREIGN_KEY_CHECKS=0;
• Deletion from the view also deletes from original table;
• DROPPING VIEWS
• Where the user has a view, you need a method to drop the view if it is no
longer needed. The query is straightforward and is given below:
• DROP VIEW view_name;
Difference between CTE and View
• In contrast to a CTE, a view is a physical object in a database and is stored on a disk.
• However, views store the query only, not the data returned by the query. The data is
computed each time you reference the view in your query.
• For queries that are referenced occasionally (or just once), it’s usually better to use a
CTE. If you need the query again, you can just copy the CTE and modify it if necessary.
• If you tend to reference the same query often, creating a corresponding view is a good
idea. However, you’ll need create view permission in your database to create a view.
• Access management. A view might be used to restrict particular users’ database access
while still allowing them to get the information they need. You can give users access to
specific views that query the data they’re allowed to see without exposing the whole
database. In such a case, a view provides an additional access layer.
SQL Databases
Lecture 5
Table of content
• Stored Procedure
• Trigger
Stored procedure
• The stored procedure is a prepared SQL query that you can save so
that the query can be reused over and over again.
• So, if the user has an SQL query that you write over and over again,
keep it as a stored procedure and execute it.
• Users can also pass parameters to a stored procedure so that the
stored procedure can act based on the parameter value that is given.
• Syntax:
DELIMITER $$
CREATE PROCEDURE PROCEDURE_NAME()
BEGIN SELECT Column_name1, Column_name2,………..
FROM Table_name
END$$
DELIMITER
• Here, the DELIMITER is not the part of Query, the first Delimiter is
change the default delimiter to // and the second delimiter is change
the delimiter to the default. The Stored procedure is saved
automatically in the database while creation
Example
• Create
DELIMITER &&
CREATE PROCEDURE age_calculation ()
BEGIN
select actor_id, year(curdate())-birth_year as age from actors ;
END &&
DELIMITER ;
• Execution of the Stored Procedure is very simple by using the
CALL procedure_name;
Call age_calculation();
• Drop procedure use to delete the stored procedure from the
databases. The following query used to delete the stored procedure
for the Database:
DROP Stored_procedure_name;
drop age_calculation();
Stored procedure parameters
• We can create a stored procedure with parameters. In Stored
procedure the parameters are like IN, OUT , INOUT. The parameters
make the Stored Procedure more flexible and useful
• DEFINING A PARAMETERS To define the parameter inside the stored
procedure, run the below query: [ IN | OUT|INOUT ]
PARAMETER_NAME datatype[(length)]
IN parameters
• It is the default parameter in Stored Procedure and the calling
program should pass an argument to stored Procedure.
• The value of IN is protected that means even the IN value is changed
inside the stored procedure the original value will retained after end
of the Stored Procedure
Example
• Create a stored procedure which takes maximum age as criteria and finds actors
whose age is below criteria
DELIMITER &&
CREATE PROCEDURE movie_eligible (in criteria int)
BEGIN
with act_age as (select actor_id, year(curdate())-birth_year as age from actors)
select * from act_age where age<criteria;
END &&
DELIMITER ;
• Call it
call movie_eligible(50);
Out parameters
• The value of the Output Parameter can be changed inside the Store Procedure and pass the new
value while calling the Stored Procedure.
• Example:
DELIMITER &&
CREATE PROCEDURE movie_eligible (in criteria int, out eligibility varchar(20))
BEGIN
set eligibility = criteria>0;
with act_age as (select actor_id, year(curdate())-birth_year as age from actors)
select * from act_age where age<criteria;
END &&
DELIMITER ;
call movie_eligible(50, @eel);
select @eel;
Variables of stored procedure
• To declare the variable inside a stored procedure, use the below query:
• DECLARE Variable_name datatype(size) [DEFAULT Default_value]

• ASSIGNING VARIABLE
• Once we declare the variable, now it is ready to use. To assign a value to the
variable use SET
• statement:

• Variable scope is for limited time period. It is defined inside the stored procedure
within BEGIN and it will be out of scope once the END statement reaches.
TRIGGERS
• Trigger is a stored program that invoked automatically in response to an
event such as insert, delete or update that occurs in the table. Suppose,
you defined a trigger and you insert a row inside the table, then it will
automatically invoked before or after the insertion of row.
• There are two types of the TRIGGERS:
• Row-level-Triggers: it is activated for each row that is inserted, deleted or updated.
• Statement-level-Triggers: it is executed for each transaction.
• Advantage of Triggers
• It provides a way to check the integrity in data.
• It can be useful for auditing the data changes in tables
• It handles the errors from the database layer.
CREATING TRIGGERS

• CREATE TRIGGER statement is used to create the triggers. The syntax is


following:
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | DELETE | UPDATE }
ON table_name FOR EACH ROW trigger_body;
• Here,
• The first line is for creating the trigger with trigger_name.
• It will make the condition that the trigger invokes before or after any modification
in row.
• The operation we can choose as INSERT, DELETE OR UPDATE on the table_name at
any row
Example of before insertion trigger
DELIMITER //
Create Trigger before_insert_movies BEFORE INSERT
ON movies FOR EACH ROW
BEGIN
IF NEW.imdb_rating >10 THEN SET NEW.imdb_rating = 10;
END IF; END //
• insert into movies values (510,"Pushpa",
"bollywood",2023,10.5,"dharma production", 3);
• select * from movies;
• Other Examples of trigger

You might also like