SQL Basics: Data Types & Commands
SQL Basics: Data Types & Commands
Chapter 3
Introduction to SQL
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 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;
Alter and update table
ALTER TABLE employees ADD hire_date DATE;
ALTER TABLE employees DROP COLUMN department_id;
ALTER TABLE employees MODIFY salary DECIMAL(12, 2);
OR
ALTER TABLE employees ALTER COLUMN salary TYPE DECIMAL(12, 2);
ALTER DATABASE old_database_name RENAME TO new_database_name;
DROP DATABASE database_name;
Delete, Drop, Truncate
This will truncate the employees table and any tables that have a foreign key
reference to it.
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.
SQL constraints
NOT NULL using alter table
Add not null constraint:
While creating:
CREATE TABLE table_name ( column_name data_type NOT NULL, ... );
CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY, first_name
VARCHAR(100) NOT NULL, last_name VARCHAR(100) NOT NULL, email
VARCHAR(255), salary DECIMAL(10, 2) NOT NULL );
Adding constraint to existing table:
ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;
ALTER TABLE employees ALTER COLUMN email SET NOT NULL;
Drop constraint
ALTER TABLE table_name ALTER COLUMN column_name DROP NOT NULL;
ALTER TABLE employees ALTER COLUMN email DROP NOT NULL;
UNIQUE using alter table
Add unique constraint:
While creating:
CREATE TABLE table_name ( column_name data_type
UNIQUE, ... );
CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE, -- This will enforce uniqueness on
the email column first_name VARCHAR(100), last_name
VARCHAR(100) );
Adding constraint to existing table:
ALTER TABLE table_name ADD CONSTRAINT constraint_name
UNIQUE (column_name);
ALTER TABLE employees ADD CONSTRAINT unique_email UNIQUE
(email);
ALTER TABLE employees ADD CONSTRAINT
unique_first_last_name UNIQUE (first_name, last_name);
PRIMARY KEY using alter table
Add PRIMARY constraint:
While creating:
CREATE TABLE table_name ( column_name data_type PRIMARY KEY, ... );
CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY, first_name VARCHAR(100),
last_name VARCHAR(100), email VARCHAR(255) );
CREATE TABLE order_items ( order_id INT, product_id INT, quantity INT, PRIMARY KEY (order_id,
product_id) );
Adding constraint to existing table:
ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (column_name);
ALTER TABLE employees ADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);
ALTER TABLE order_items ADD CONSTRAINT pk_order_items PRIMARY KEY (order_id, product_id);
Drop constraint
ALTER TABLE employees DROP CONSTRAINT pk_employee_id;
FOREIGN KEY using alter table
Add Foreign key constraint:
While creating:
CREATE TABLE table_name ( column_name data_type, FOREIGN KEY
(column_name) REFERENCES parent_table(parent_column) );
CREATE TABLE departments ( department_id SERIAL PRIMARY KEY,
department_name VARCHAR(100) );
CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY, first_name
VARCHAR(100), last_name VARCHAR(100), department_id INT, FOREIGN KEY
(department_id) REFERENCES departments(department_id) );
Adding constraint to existing table:
ALTER TABLE child_table ADD CONSTRAINT constraint_name FOREIGN KEY
(column_name) REFERENCES parent_table(parent_column);
ALTER TABLE employees ADD CONSTRAINT fk_department FOREIGN KEY
(department_id) REFERENCES departments(department_id);
Drop constraint
ALTER TABLE employees DROP CONSTRAINT fk_department;
FOREIGN KEY using alter table
Add Foreign key constraint:
Drop constraint
ALTER TABLE employees DROP CONSTRAINT fk_department;
ON DELETE CASCADE: When a row in the parent table is deleted, the
corresponding rows in the child table are also deleted.
ON DELETE SET NULL: When a row in the parent table is deleted, the
foreign key column in the child table is set to NULL.
ALTER TABLE employees ADD CONSTRAINT fk_department FOREIGN KEY
(department_id) REFERENCES departments(department_id) ON DELETE
CASCADE;
CHECK
Add Check constraint:
CREATE TABLE table_name ( column_name data_type, CHECK (condition)
);
CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY,
first_name VARCHAR(100), last_name VARCHAR(100), salary
DECIMAL(10, 2), CHECK (salary > 0) -- Ensures salary is always greater
than 0 );
Adding CHECK to an Existing Table:
ALTER TABLE employees ADD CONSTRAINT check_salary_positive CHECK
(salary > 0);
For all the queries in upcoming slides we will use Movie dataset
Import dataset in postgres
First try to understand dataset using excel file of the dataset
In excel file for one table there is one sheet [Upcoming lab session]
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 Statement
Examples:
Simply print all the movies SELECT * FROM movies;
Get movie title and industry for all the movies SELECT title, industry FROM
movies;
SELECT DISTINCT
The SELECT DISTINCT statement is to return the different values. Output:
studio
Syntax: Hombale Films
Marvel Studios
SELECT DISTINCT column1, column2. column
United Producers
Yash Raj Films
FROM table_name; Vinod Chopra Films
Dharma Productions
Example: Castle Rock Entertainment
Warner Bros. Pictures
Get all the unique studio in the movies database Columbia Pictures
Universal Pictures
SELECT DISTINCT studio FROM movies;
Paramount Pictures
SELECT DISTINCT studio FROM movies WHERE Liberty Films
20th Century Fox
studio IS NOT NULL; Syncopy
Arka Media Works
Zee Studios
Salman Khan Films
Mythri Movie Makers
DVV Entertainment
Government of West Bengal
Vinod Chopra Productions
NULL
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
FROMtable_name WHERE CONDITION;
Example:
Print all movies from Hollywood
SELECT * FROM movies WHERE industry = 'Hollywood';
1) movies(movie_id title industry
release_year imdb_rating studio
Syntax:
104
Thor:
Hollywood 2017 7.9
Marvel
5
Ragnarok Studios
SELECT column1, column2. column
Thor: Love Marvel
105 Hollywood 2022 6.8 5
FROM and Thunder
table_name Studios
OFFSET 1
movie LIMIT 5;
Summary analytics(MAX, MIN,
AVG,SUM)
Syntax:
SELECT function(column_name) AS alias
FROM table_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
Summary analytics(MAX, MIN,
AVG,SUM)
Select highest imdb rating for bollywood movies
AVG 7.5
Summary analytics(MAX, MIN,
AVG,SUM)
Print min, max, avg rating of Marvel Studios movies
6.8
8.4
7.5
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
GROUP BY
Example:
Print count and average imdb rating of movies for each industry
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 table1.column1, table1.column2, table2.column1,
table2.column2, ... FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example: If you want to join the movies table with the financial table using
movie_id as the common column.
SELECT [Link], [Link], [Link] FROM movies INNER JOIN
financial ON movies.movie_id = financial.movie_id;
Queries
Find all movies that have a rating higher than the average
rating
Queries
•Movie_actor(movie_id, actor_id)
•Languages(language_id, name)
UNION ALL
-- Recursive step: calculate the next Fibonacci number
SELECT n2, n1 + n2, position + 1
FROM fibonacci_sequence
WHERE position < 10 -- limiting to the first 10 Fibonacci numbers
)
SELECT n1 AS fibonacci_number
FROM fibonacci_sequence;
Views
The view is a virtual table based on the result-set of an SQL statement. A
view holds rows and columns, like 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
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
A stored procedure in a database is a set of SQL statements that are
stored and executed on the database server.
They allow for the encapsulation of logic that can be reused and
executed multiple times, possibly with different parameters.
Stored procedures can take input parameters, process data, return
output parameters, and even return result sets.
Stored procedure
CREATE OR REPLACE PROCEDURE procedure_name(parameters)
LANGUAGE plpgsql
AS $$
BEGIN
-- SQL logic here
END;
$$;
Stored procedure
Execution of the Stored Procedure is very simple by using the
CALL procedure_name;
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;
Procedure to Calculate Profit Percentage for a Movie
CREATE OR REPLACE PROCEDURE calculate_profit_percentage(p_movie_id INT)
LANGUAGE plpgsql
AS $$
DECLARE
v_budget NUMERIC;
v_revenue NUMERIC;
v_profit_percentage NUMERIC;
BEGIN
----Fetch budget and revenue from the Financial table
SELECT budget, revenue INTO v_budget, v_revenue
FROM Financial
WHERE movie_id = p_movie_id;
----If the movie has budget and revenue, calculate profit percentage
IF v_budget IS NOT NULL AND v_revenue IS NOT NULL THEN
v_profit_percentage := (v_revenue / v_budget) * 100;
RAISE NOTICE 'Movie ID: %, Profit Percentage: %', p_movie_id, v_profit_percentage;
ELSE
RAISE NOTICE 'No budget or revenue available for movie ID: %', p_movie_id;
END IF;
END;
$$;
CALL calculate_profit_percentage(p_movie_id);
CALL calculate_profit_percentage(101);
Stored procedure parameters
1. IN Parameters (Input Parameters)
Purpose: Used to pass values into the procedure.
Default behavior: If you don't specify the parameter mode, it's treated as IN by default.
Stored procedure parameters
2. OUT Parameters (Output Parameters)
Purpose: Used to pass values out from the procedure back to the calling program.
Behavior: The calling program does not provide a value for an OUT parameter when calling
the procedure. The procedure will assign values to OUT parameters,
and these values are returned as output.
CALL get_movie_title();
Stored procedure parameters
3. INOUT Parameters (Output Parameters)
Purpose: Used to pass values both into and out of the procedure., and the procedure can modify that value
•and return it.
Behavior: You pass a value into the INOUT parameter, and the procedure modifies it and
sends the modified value back to the caller.
Stored procedure
Variables:
v_budget, v_revenue: Store the budget and revenue from the Financial table.
v_profit: Holds the calculated profit (revenue - budget).
v_profit_percentage: Holds the profit percentage.
Logic:
The procedure fetches the budget and revenue for the given p_movie_id.
It calculates the profit and the profit percentage, then outputs it using
RAISE NOTICE:
The RAISE NOTICE statement is used to output messages (similar to print
statements in other languages).
You can also use variables in control structures like IF, LOOP, and FOR. For
example, you could iterate through multiple movies and calculate their
profits in a loop.
CREATE OR REPLACE PROCEDURE calculate_all_movie_profits()
LANGUAGE plpgsql
AS $$
DECLARE
v_movie_id INT;
v_budget NUMERIC;
v_revenue NUMERIC;
v_profit NUMERIC;
BEGIN
FOR v_movie_id IN SELECT movie_id FROM movies
LOOP
SELECT budget, revenue INTO v_budget, v_revenue
FROM Financial
WHERE movie_id = v_movie_id;
ELSE
RAISE NOTICE 'No financial data for movie ID: %',
v_movie_id;
END IF;
END LOOP;
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 be invoked before or after the insertion of row.
CREATE TRIGGER trigger_name
{ BEFORE | AFTER | INSTEAD OF } { INSERT | UPDATE | DELETE }
ON table_name [ FOR EACH ROW | FOR EACH STATEMENT ]
EXECUTE FUNCTION function_name();
Trigger
The following are the key differences between triggers and stored
procedures:
1. Triggers cannot be manually invoked or executed.
2. There is no chance that triggers will receive parameters.
3. A transaction cannot be committed or rolled back inside a trigger.
Types of Trigger: DML
DML Triggers (Data Manipulation Language): These triggers are executed in
response to changes in data (inserts, updates, deletes) in the table.
BEFORE INSERT/UPDATE/DELETE: Executes before the data modification event
happens.
AFTER INSERT/UPDATE/DELETE: Executes after the data modification event has
occurred.
INSTEAD OF (for views): Executes instead of the triggering DML operation, often
used for views.
Use Cases:
• Automatically logging changes to sensitive data.
• Enforcing complex constraints.
• Maintaining summary tables or updating dependent tables.
DML Trigger
Suppose we want to automatically log every time a sensor’s value
changes in the Sensor_history table.
Explanation:
•This is a DML AFTER UPDATE trigger.
•It logs every change to a sensor value in the sensor_change_log table.
Types of Trigger: DDL
DDL Triggers: These triggers are executed in response to changes in
the schema, such as creating, altering, or dropping tables or other
database objects.
Use Cases:
Enforcing auditing when schema changes are made.
Preventing or logging changes to specific database objects.
Some databases like Oracle and MySQL support DDL triggers, but
PostgreSQL does not natively support DDL triggers. However, you
can monitor DDL changes using event triggers in PostgreSQL.