Beautified SQL Guide
Beautified SQL Guide
A relational database stores data in a structured format using rows and columns2. This
organization makes it easy to establish relationships between different data points.
What is a Database?
Management System:
The "management system" part of RDBMS refers to the frequent transactions performed on the
database, such as inserting, deleting, modifying, and retrieving data4.
2. User Management
Before you can start working with a database, you often need a user account.
Creating a User:
To create a new user, you can use the CREATE USER command.
Granting Privileges:
Once a user is created, they need permissions to connect to the database and manage its
resources.
To see which user is currently logged in, you can run the following query:
To delete a user and all their associated tables and data, you can use the DROP USER command
with the cascade option.
DDL commands are used to define and manage the structure of your database tables. The main
DDL commands are
Creating a Table:
The CREATE TABLE command is used to create a new table in the database.
Example: sql create table reserv( doj date, pname varchar2(10), dest varchar2(15), bookdate
date ); 15
To see the columns and their data types in a table, use the DESC (or Describe) command.
Desc Student; 18
Altering a Table:
The
Adding Columns:
Modifying Columns:
You can change a column's data type or size. It's generally possible to increase a column's size
even if it contains data, but decreasing the size is often only allowed for empty columns23.
Dropping Columns:
Dropping a Table:
To permanently remove a table from the database, use the DROP TABLE command.
DML commands are used to manage the data within your tables.
Inserting Data:
The
You can use substitution variables (with &) to prompt for values when inserting data. This is
useful for adding multiple rows quickly34.
Inserting Dates: To insert the current system date, you can use sysdate. For a specific date, use
the
to_date function38.
Updating Data:
The
The WHERE clause is crucial. If omitted, the update will apply to all rows in the specified
column42.
Examples:
Deleting Data:
The
The
Basic Syntax:
Using
The
Examples:
Select * from emp; (retrieves all data from the emp table) 56
The
The ORDER BY clause sorts the results in ascending (ASC) or descending (DESC) order.
Example: select * from emp10 order by ename desc; 62This sorts the employees by name in
descending (Z-A) order63.
DISTINCT and ORDER BY together: select distinct deptno from emp10 order by deptno; 64
6. SQL Operators
Operators are symbols used to perform operations on data and to combine conditions in your
queries.
Types of Operators:
Relational Operators: Used for comparisons (<, >, <=, >=, =, !=) to produce boolean results66.
Example: select * from emp10 where sal between 20000 and 50000; 68
Examples:
Constraints are rules applied to data columns to ensure the accuracy and reliability of the data
in the database. They are typically defined when a table is created76.
Types of Constraints:
NOT NULL: Ensures that a column cannot have a NULL value. It does, however, allow duplicate
values77.
NULL values797979.
Unique(sno, sname) (ensures the combination of sno and sname is unique) 818181
PRIMARY KEY: A combination of NOT NULL and UNIQUE. It uniquely identifies each record in a
table and does not allow null or duplicate values82.
The data type and size of the foreign key and the parent table's primary key must be identical86.
The
ON DELETE CASCADE option automatically deletes corresponding records in the child table if a
record in the parent table is deleted878787.
Example: create table Admission (... ccode number(3) References Course(ccode) on delete
cascade ...); 88
Another example:
Managing Constraints:
Dropping Constraints:
Viewing Constraints:
You can query the user_constraints table to see the constraints on a table.
8. SQL Functions
SQL has built-in functions to perform operations on data. These are categorized into single-row
functions and group functions100.
Single-Row Functions
These functions operate on a single row and return one result per row.
Character Functions:
Example:
Example:
The
Example:
LTRIM(char, set), RTRIM(char, set): Removes specified characters from the left or right side of a
string110.
Example:
Example:
Example:
Example:
select replace('jack and jue', 'j', 'bl') from dual; (returns 'black and blue') 116
Numeric Functions:
SIGN(n): Returns -1 for a negative number, 1 for a positive number, and 0 for zero123.
Date Functions:
LAST_DAY(d): Returns the last day of the month for a given date129.
Conversion Functions:
to_date('10-mar-25') 130
The
NVL(column, default_value) function replaces null values with a specified default value131. This
is essential for calculations involving columns that may contain nulls, as adding a number to
NULL results in NULL132132132132.
Calculation Example: update employee set gross = salary + nvl(hra,0) + da + ta; 133This ensures
the gross salary is calculated correctly even if
hra is null134.
Display Example: select emp_id, nvl(emp_name, 'not avl'), salary from employee; 135This will
display 'not avl' for any employee with a null name136.
Group Functions
These functions operate on a group of rows and return a single result for the entire group.
Common group functions include
When using group functions, you often use the GROUP BY clause to divide the rows into groups.
Subqueries:
Joins:
Joins are used to combine rows from two or more tables based on a related column between
them.
Equi-Join: Combines rows that have equal values in the join columns.
Non-Equi-Join: Joins tables using comparison operators other than equals (=), such as BETWEEN,
>=, or <=139.
Outer Join: Returns all rows from one table and the matched rows from the other table. If there
is no match, the columns from the second table will have null values140.
Views:
SELECT statement141.
Single-Table Views: Changes made to the data in a single-table view will also affect the original
table, and vice-versa142.
Multi-Table Views: Views can be created from multiple tables using joins. This simplifies complex
queries, as you don't have to write the join condition every time145. Data added to the
underlying tables will be reflected in the view automatically146.
Synonyms:
Sequences:
A sequence is a database object that generates a sequence of unique numbers. They are often
used to automatically generate primary key values149.
Example: A sequence can be used to automatically assign account numbers like 101, 102, 103,
and so on150.
Indexing:
An index is used to speed up the retrieval of rows from a table by providing a quick lookup
mechanism. It internally sorts the data in ascending order151.
You can use various commands to format the output of your SQL queries.
Setting Line Size:
Set linesize 500; helps in adjusting the width of the output line to prevent wrapping152.
Column Formatting:
Titles:
TTITLE places a title at the top of each page of the report154. It can be aligned as needed155.
GRANT:
The
Example: You can grant SELECT and INSERT permissions on a table to another user. That user
can then log in and perform those actions, but they won't be able to
DELETE records if that permission was not granted160. Any data they insert will also be reflected
in the original table161.
REVOKE:
The
REVOKE command is used to take back permissions that were previously granted162.