0% found this document useful (0 votes)
3 views28 pages

Constraints

The document provides a comprehensive guide on installing and using PostgreSQL, covering database creation methods, data types, SQL command types, and various SQL operations. It details the use of constraints such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK to ensure data integrity. Additionally, it includes examples of SQL commands for altering tables and managing data effectively.

Uploaded by

edla.laxman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views28 pages

Constraints

The document provides a comprehensive guide on installing and using PostgreSQL, covering database creation methods, data types, SQL command types, and various SQL operations. It details the use of constraints such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK to ensure data integrity. Additionally, it includes examples of SQL commands for altering tables and managing data effectively.

Uploaded by

edla.laxman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Learning

Postgres SQL
Installing Postgres SQL
Go to link below and download the Windows Installer
https://www.postgresql.org/download/windows/

And follow the steps mentioned in Installer


Create Database
There are various ways by which you can create Database in Postgres
1. Command line tool
2. PgAdmin
3. PgAdmin Query Tool
DataTypes in Postgres

Numeric Data types


Charater Data types
Date/Time Data types
Boolean Data type
Numeric Data types
smallint : Used to store small integers ranging from -32768 to +32767
integer : Used to store whole numbers up to 2∧31.
bigint : Used to store large integers ranging from -2∧63 to 2∧63-1.
decimal : Used to store the numbers with decimal places.
numeric : Used to store the numbers with decimal places.
real : Used to store floating point numbers with 6 decimal digits of precession.
double precession : Used to store floating point numbers with 15 decimal
digits of precession.
Syntax - Create table <table name>(
id integer,
temp_capture_at timestamp,
temperature real
)
Charater Data types
Character data types are used to store textual data of different lengths.
char : Used to store fixed-length strings up to a maximum of 255 characters.
varchar : Used to store variable-length strings upto a maximum of 1GB.
text : Used to store variable-length strings up to a maximum of 1GB.

Syntax - Create table customers (


id integer,
name varchar(255),
email varchar(255)
)
Insert into customers (id, name, email) values (
123, 'Sunil Ghate', '[email protected]'
);
Date/Time Data types
Date/time data types are used to store data and time values and perform various
operatoions on them.
date : Used to store dates ranging from 4713 BC to 5874897 AD.
time : Used to store time values upto 6 decimal digits of precession.
timestamp : Used to store date and time values with upto 6 decimal digits of
precession.
interval : Used to store time intervals ranging from -178000000 years to
178000000 years

Syntax - Create table customers (


id integer,
name varchar(255),
email varchar(255),
date_of_birth date
)
Boolean Data type
Boolean data type is used to store true or false values.

boolean : Used to store true or false values.

Syntax - Create table customers (


id integer,
name varchar(255),
email varchar(255),
is_active boolean
)
Types of SQL Commands
In basic terms SQL has different keywords, we perform certain actions over data using this keywords

There are 4 types of SQL Commands

DDL (Data Defination Language)


DML (Data Manipulation Language)
DCL (Data COntrol Language)
TCL (Transaction COntrol Language)
DDL (Data Defination Language)
DDL is a language used to define structure of a database, including creating, altering and
dropping tables and other database objects.
Create table <tablename>
Alter table <tablename>
Drop table <tablename>
DML (Data Manipulation Language)
DML is a language used to manipulate data stored in a database. It is used to add, delete,
update and retrive data from database.
Insert into <tablename>
Updae <tablename>
Delete from <tablename>
DCL (Data COntrol Language)
DCL is a language used to control access to the database by creating and managing user
accounts and permissions.
Create user <user> identified by 'password';
Grant select, insert, update on <tablename> to <user>
TCL (Transaction Control Language)
TCL It is a set of SQL commands used to manage transactions in a relational database
management system
Begin Transaction;
Commit;
Rollback;
Operators
Operator Function Example

= Equal to where customer_name = ‘Sunil Ghae’

<> or != Not Equal to where customer_id <> 123

> Greater than where salary > 2000

< Smaller than where salary < 2000

>= Greater than or equal to where salary >= 2000

<= Less than or equal to where salary <= 2000

BETWEEN Within range where salary between 200 and 1000

IN Match one out of a set of values where cust_name in (‘Ram’,’Sam’)

LIke Match the pattern where cust_name like ‘Sunil%’


Alter Query
PostgreSQL provides a wide range of features, including the ability to modify existing tables
and their columns via the ALTER query.

Create a table

CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR(50), email VARCHAR(50),
age INTEGER);

Insert data into the table

INSERT INTO users (name, email, age) VALUES


('John Doe', '[email protected]', 25),
('Jane Doe', '[email protected]', 30),
('Bob Smith', '[email protected]', 40);
Alter Query
Altering a table's column name

To change the name of a column in a table, we can use the ALTER TABLE
statement with the RENAME COLUMN option. For example, to change the name
of the email column to user_email, we can use the following query:

ALTER TABLE users RENAME COLUMN email TO user_email;

This will rename the email column to user_email in the users table.
Alter Query
Adding a new column to a table

To add a new column to a table, we can use the ALTER TABLE statement with the
ADD COLUMN option. For example, to add a new column named phone of data
type VARCHAR(20) to the users table, we can use the following query:

ALTER TABLE users ADD COLUMN phone VARCHAR(20);

This will add a new phone column to the users table.


Alter Query
Modifying an existing column's data type

To modify the data type of an existing column in a table, we can use the ALTER
TABLE statement with the ALTER COLUMN option. For example, to change the
data type of the age column from INTEGER to SMALLINT, we can use the
following query:

ALTER TABLE users ALTER COLUMN age TYPE SMALLINT;

This will change the data type of the age column in the users table from INTEGER
to SMALLINT
Alter Query
Deleting a column from a table

To delete a column from a table, we can use the ALTER TABLE statement with the
DROP COLUMN option. For example, to delete the phone column from the users
table, we can use the following query:

ALTER TABLE users DROP COLUMN phone;

This will delete the phone column from the users table.
Database Constraints in PostgreSQL

Database constraints are rules that restrict the values that can be inserted,
updated, or deleted in a database table.

NOT NULL Constraint


UNIQUE Constraint
PRIMARY KEY Constraint
FOREIGN KEY Constraint
CHECK Constraint
Database Constraints in PostgreSQL
NOT NULL Constraint
The NOT NULL constraint ensures that a column cannot have a null value. This means that when a new row is inserted
into the table, the value for the NOT NULL column must be provided.

Example:

Suppose we have a table called employees with columns employee_id, employee_name, and employee_salary.
We want to ensure that a value is always provided for the employee_name" and employee_salary columns.
We can add a NOT NULL constraint to these columns using the following SQL command:

CREATE TABLE employees (


employee_id INTEGER ,
employee_name TEXT ,
employee_salary NUMERIC(10, 2)
);
ALTER TABLE employees ALTER COLUMN employee_name SET NOT NULL;
ALTER TABLE employees ALTER COLUMN employee_salary SET NOT NULL;

Now, any attempt to insert a row into the "employees" table without providing a value for the "employee_name" or
"employee_salary" column will result in an error.
UNIQUE Constraint
The UNIQUE constraint ensures that the values in a column are unique across all rows in the table. This means that no
two rows can have the same value in the column with the UNIQUE constraint.

Example:

Suppose we have a table called students with columns student_id and email. We want to ensure that each student has a
unique email address. We can add a UNIQUE constraint to the email column using the following SQL command:

ALTER TABLE students ADD CONSTRAINT unique_email UNIQUE (email);

Now, any attempt to insert a row into the "students" table with a duplicate email address will result in an error.
PRIMARY KEY Constraint
The PRIMARY KEY constraint is a combination of a UNIQUE constraint and a NOT NULL constraint. It ensures that the
values in a column are unique across all rows in the table, and that the column cannot have a null value.

Example:

Suppose we have a table called orders with columns order_id, customer_id, and order_date. We want to ensure that
each order has a unique order ID. We can add a PRIMARY KEY constraint to the order_id column using the following SQL
command:

CREATE TABLE orders (


order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
order_date DATE);

ALTER TABLE orders ADD CONSTRAINT pk_orders PRIMARY KEY (order_id);

Now, the order_id column cannot have a null value, and any attempt to insert a row into the orders table with a duplicate
order ID will result in an error.
FOREIGN KEY Constraint
The FOREIGN KEY constraint ensures that the values in a column match the values in another table's column. It creates
a relationship between two tables based on the values in one or more columns.

Example:

Suppose we have two tables called customers and orders.

The customers table has columns customer_id and customer_name, while the orders table has columns order_id,
customer_id, and order_date.

We want to ensure that the customer_id column in the orders table matches a valid customer_id in the customers table.
We can add a FOREIGN KEY constraint to the customer_id column in the orders table using the following SQL
command:

ALTER TABLE orders ADD CONSTRAINT fk_orders_customers


FOREIGN KEY (customer_id)REFERENCES customers (customer_id);

Now, any attempt to insert a row into the "orders" table with a "customer_id" value that does not exist in the "customers"
table will result in an error.
CHECK Constraint
The CHECK constraint ensures that the values in a column meet a specific condition. This condition can be a simple
comparison or a more complex expression.

Example:

Suppose we have a table called students with columns student_id and age.

We want to ensure that each student is at least 18 years old. We can add a CHECK constraint to the "age" column using
the following SQL command:

ALTER TABLE students ADD CONSTRAINT check_age CHECK (age >= 18);

Now, any attempt to insert a row into the "students" table with an age value less than 18 will result in an error.
Constraints are an important tool for ensuring the accuracy and consistency of data in a PostgreSQL database. By using
constraints, you can prevent invalid data from being inserted, updated, or deleted, and ensure that your data remains
reliable and trustworthy.
Thank You

You might also like