0% found this document useful (0 votes)
4 views13 pages

Beautified SQL Guide

This SQL guide provides a comprehensive overview of relational databases, user management, data definition and manipulation languages, querying data, SQL operators, data integrity constraints, SQL functions, and advanced SQL concepts. It includes syntax examples for creating users, tables, and executing various SQL commands such as SELECT, INSERT, UPDATE, and DELETE. Additionally, it covers topics like constraints, subqueries, joins, views, and synonyms to enhance understanding of SQL functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

Beautified SQL Guide

This SQL guide provides a comprehensive overview of relational databases, user management, data definition and manipulation languages, querying data, SQL operators, data integrity constraints, SQL functions, and advanced SQL concepts. It includes syntax examples for creating users, tables, and executing various SQL commands such as SELECT, INSERT, UPDATE, and DELETE. Additionally, it covers topics like constraints, subqueries, joins, views, and synonyms to enhance understanding of SQL functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Here is the SQL guide, reorganized for clarity and a logical flow:

1. Introduction to Relational Databases

Relational Database Management System (RDBMS) is a system used to manage relational


databases1.

What is a Relational Database?

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?

A database is a collection of interrelated records3.

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.

Syntax: Create user <user-name> identified by <password> 5

Example: Create ashok identified by reddy; 6

Granting Privileges:

Once a user is created, they need permissions to connect to the database and manage its
resources.

Syntax: Grant connect,resource to <user-name>; 7

Example: Grant connect,resource to ashok; 8

Identifying the Current User:

To see which user is currently logged in, you can run the following query:

select user from dual; 9


Removing a User:

To delete a user and all their associated tables and data, you can use the DROP USER command
with the cascade option.

Syntax: Drop user <user-name> cascade; 10

Example: Drop user ashok cascade; 11

3. Data Definition Language (DDL)

DDL commands are used to define and manage the structure of your database tables. The main
DDL commands are

CREATE, ALTER, and DROP12.

Creating a Table:

The CREATE TABLE command is used to create a new table in the database.

Syntax: Create Table <table-name>(col1 type(size), col2 type(size),......,coln type(size)); 13

Example: Create table Student(sno number(3),sname varchar2(20),m1 number(3),m2


number(3),m3 number(2)); 14

You can also create tables that include date fields.

Example: sql create table reserv( doj date, pname varchar2(10), dest varchar2(15), bookdate
date ); 15

Viewing Table Structure:

To see the columns and their data types in a table, use the DESC (or Describe) command.

Syntax: Desc <table-name>; 16

Example: desc emp; 17or

Desc Student; 18

Altering a Table:

The

ALTER TABLE command is used to modify the structure of an existing table19.

Adding Columns:

Syntax: Alter table <table-name> add(col-name's type(size)); 20


Example: Alter table student add(tot number(3),avg number(6,2)); 21

Another example is adding multiple columns at once:

alter table emp add (hra number(8,2),da number(8,2),ta number(8,2),gross number(10,2)); 22

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.

Syntax: alter table <table-name> modify(col-name type(size));

Example: alter table emp modify(empid char(3)); 24

Dropping Columns:

Syntax: alter table <table-name> drop column <column-name>; 25

Example: alter table emp drop column avg; 26

Dropping a Table:

To permanently remove a table from the database, use the DROP TABLE command.

Syntax: Drop table <table-name>; 27

Example: Drop table emp; 28

4. Data Manipulation Language (DML)

DML commands are used to manage the data within your tables.

Inserting Data:

The

INSERT INTO command adds new rows of data to a table29.

Inserting into All Columns:

Syntax: insert into <table-name> values(value-list); 30

Example: Insert into student values (103,'Ashok',43,67,89); 31

Inserting into Specific Columns:

Syntax: insert into <table-name>[(partial column names)] values(value list); 32

Example: insert into student(rollno,sname)values(103,'Ashok'); 33


Interactive Inserts:

You can use substitution variables (with &) to prompt for values when inserting data. This is
useful for adding multiple rows quickly34.

Example: Insert into student values (&rollno,'&Studentname',&m1,&m2,&m3); 35After


executing this, you will be prompted to enter the values for each column36. Typing

/ and pressing enter will allow you to insert another row37.

Inserting Dates: To insert the current system date, you can use sysdate. For a specific date, use
the

to_date function38.

Example: insert into reserv values(sysdate, 'jsreddy', 'hyd', to_date('10-mar-25')); 39

Updating Data:

The

UPDATE command modifies existing records in a table40.

Syntax: update <table-name> set <column-name>= value [where <condition>]; 41

The WHERE clause is crucial. If omitted, the update will apply to all rows in the specified
column42.

Examples:

Updating a specific cell:

update student set m1=58 where rollno = 101; 43

Updating an entire column based on other columns:

update student set tot= m1+m2+m3; 44

Deleting Data:

The

DELETE FROM command removes records from a table45.

Syntax: delete from <table-name>[where<condition>]; 46

If you omit the

WHERE clause, all records in the table will be deleted47.


Examples:

Deleting all records:

delete from emp; 48

Deleting a specific record:

delete from emp where eid=10; 49or

delete from emp where ename='Ashok'; 50

Deleting multiple specific records:

delete from emp where eid=10 or eid=20; 51

5. Querying Data with SELECT

The

SELECT statement is used to retrieve data from a database52.

Basic Syntax:

select <(*) (or) list of attributes> from <table-name> [Where condition]; 53

Using

* selects all columns54. You can also specify a list of columns.

The

WHERE clause is optional and is used to filter for specific records55.

Examples:

Select * from emp; (retrieves all data from the emp table) 56

Select empid,ename,salary from emp; (retrieves specific columns) 57

Select empid,ename,salary from emp where salary>=10000; (retrieves records based on a


condition) 58

Select * from emp where ename = 'Ashok'; 59

Eliminating Duplicates with DISTINCT:

The

DISTINCT keyword is used to return only unique values in a column60.


Example: select distinct deptno from emp10; 61

Sorting Results with ORDER BY:

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.

You can use

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:

Arithmetic Operators: Used for calculations (+, -, *, /)65.

Relational Operators: Used for comparisons (<, >, <=, >=, =, !=) to produce boolean results66.

Logical Operators: Used to combine multiple conditions (AND, OR, NOT)67.

Special SQL Operators:

BETWEEN: Selects values within a given range.

Example: select * from emp10 where sal between 20000 and 50000; 68

LIKE: Used with wildcards to search for patterns in strings.

% represents zero or more characters.

_ represents a single character.

Examples:

Names starting with 'N':

select * from emp10 where ename like 'N%'; 69

Names ending with 'a':

select * from emp10 where ename like '%a'; 70

Names containing 'h':


select * from emp10 where ename like '%h%'; 71

Names with exactly 5 characters:

select * from emp10 where ename like '_____'; 72

Names where the second letter is 'i':

select * from emp10 where ename like '_i%'; 73

IN: Allows you to specify multiple values in a WHERE clause.

Example: select * from emp10 where ename in('Vidya','Suri','Janu','Meena'); 74

IS NULL: Used to retrieve records that have a null value in a column.

Example: select * from employ where sal is null; 75

7. Data Integrity Constraints

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.

Example: create table student(sno number(3) not null, ...); 78

UNIQUE: Ensures that all values in a column are different. It allows

NULL values797979.

Column Constraint Syntax (CCS): Applies to a single column.

sno number(3) Unique 80

Table Constraint Syntax (TCS): Applies to a group of columns.

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.

Example (CCS): create table emp(empid number(4) primary key, ...); 83

Example (TCS): Primary Key (sno, sname) 84


FOREIGN KEY: Establishes a link between two tables. It enforces referential integrity, meaning
that a value in the foreign key column must exist in the primary key column of the referenced
(parent) table85.

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

CHECK: Ensures that the values in a column satisfy a specific condition89.

Example: create table student(... m1 number(3) check(m1>=35) ...); 90

Another example:

gender char check(gender='M' or gender='F') 91

Managing Constraints:

Adding Constraints to an Existing Table:

Syntax: alter table <table-name> add constraint <cons-name> <constraint-type>(column-


names); 92

Example: alter table emp add constraint pk_eid primary key(empid); 93

This will fail if existing data violates the new constraint94.

Dropping Constraints:

Dropping a Primary Key: alter table emp drop primary key; 95

Dropping a Named Constraint: alter table emp drop constraint SYS_C004248; 96

Disabling and Enabling Constraints:

You can temporarily disable a constraint.

Disable: Alter table std5 disable constraint SN_UN; 97

Enable: Alter table std5 enable constraint SN_UN; 98

Viewing Constraints:
You can query the user_constraints table to see the constraints on a table.

Example: select * from user_constraints where table_name='EMP'; 99

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:

LENGTH(char): Returns the length of a string101.

Example:

select sname, length(sname) from student; 102

CONCAT(char1, char2): Joins two strings together103.

Example:

select concat(empno, ename) from emp; 104

The

|| operator can also be used for concatenation105.

UPPER(char), LOWER(char), INITCAP(char): Converts a string to uppercase, lowercase, or initial-


case capitalization, respectively106.

ASCII(char): Returns the ASCII value of the first character of a string107.

Example:

select ascii('Apple') from dual; (returns 65) 108

CHR(number): Returns the character for a given ASCII number109.

Example: select chr(65) from dual; (returns 'A')

LTRIM(char, set), RTRIM(char, set): Removes specified characters from the left or right side of a
string110.

Example:

select ltrim('infosys','info') from dual; (returns 'sys') 111


LPAD(char, n, pad_char), RPAD(char, n, pad_char): Pads a string to a certain length with
specified characters on the left or right.

Example:

select lpad(ename, 7, '*') from emp; 112

SUBSTR(char, start, length): Extracts a substring of a specified length from a string113.

Example:

select substr('Ashok Reddy', 7, 5) from dual; (returns 'Reddy') 114

REPLACE(char, search_string, replace_string): Replaces occurrences of a substring with another


string115.

Example:

select replace('jack and jue', 'j', 'bl') from dual; (returns 'black and blue') 116

Numeric Functions:

ABS(n): Returns the absolute value of a number117.

CEIL(n): Rounds a number up to the nearest integer118.

FLOOR(n): Rounds a number down to the nearest integer119.

MOD(m, n): Returns the remainder of a division120.

POWER(m, n): Raises a number to the power of another121.

SQRT(n): Returns the square root of a number122.

SIGN(n): Returns -1 for a negative number, 1 for a positive number, and 0 for zero123.

ROUND(n, m): Rounds a number to a specified number of decimal places124.

TRUNC(n, m): Truncates a number to a specified number of decimal places without


rounding125.

Date Functions:

SYSDATE: Returns the current database server date and time126.

Date + n / Date - n: Adds or subtracts a number of days from a date127.

ADD_MONTHS(d, n): Adds a specified number of months to a date128.

LAST_DAY(d): Returns the last day of the month for a given date129.
Conversion Functions:

TO_DATE(string, format): Converts a string to a date.

Example of usage during an insert:

to_date('10-mar-25') 130

Handling Nulls with NVL:

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

SUM, AVG, MAX, MIN, and COUNT137.

Using GROUP BY and HAVING:

When using group functions, you often use the GROUP BY clause to divide the rows into groups.

To filter the results of group functions, you must use the

HAVING clause, not the WHERE clause138.

9. Advanced SQL Concepts

Subqueries:

A subquery is a SELECT statement nested inside another SQL statement.

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:

A view is a virtual table based on the result-set of a

SELECT statement141.

Single-Table Views: Changes made to the data in a single-table view will also affect the original
table, and vice-versa142.

To create: Follow the steps to create a view for a single table143.

To check if created: Use the appropriate command to verify view creation144.

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:

A synonym is an alternative name for a table, view, or other database object.

To create: Follow the steps to create a synonym147.

To drop: DROP SYNONYM <synonym_name>; 148

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.

10. Report Generation and Customization

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:

You can clear or rename column headers for better readability153.

Titles:

TTITLE places a title at the top of each page of the report154. It can be aligned as needed155.

BTITLE places a title at the bottom of the page156.

To remove a title, use the appropriate command157.

Other SET Commands:

There are various

SET commands available to customize the reporting environment158.

11. Access Control

GRANT:

The

GRANT command gives specific permissions to users on database objects159.

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.

You might also like