SQL 1
SQL 1
A database is an organized collection of data, stored and retrieved digitally from a remote
or local computer system. Databases can be vast and complex, and such databases are
developed using fixed design and modeling approaches.
2. What is DBMS?
DBMS stands for Database Management System. DBMS is a system software
responsible for the creation, retrieval, updation and management of the database. It
ensures that our data is consistent, organized and is easily accessible by serving as an
interface between the database and its end users or application softwares.
4. What is SQL?
SQL stands for Structured Query Language. It is the standard language for relational
database management systems. It is especially useful in handling organized data
comprised of entities (variables) and relations between different entities of the data.
NOT NULL - Restricts NULL value from being inserted into a column.
CHECK - Verifies that all values in a field satisfy a condition.
DEFAULT - Automatically assigns a default value if no value has been specified for the field.
UNIQUE - Ensures unique values to be inserted into the field.
INDEX - Indexes a field providing faster retrieval of records.
PRIMARY KEY - Uniquely identifies each record in a table.
FOREIGN KEY - Ensures referential integrity for a record in another table.
CREATE TABLE Students ( /* Create table with multiple fields as primary key */
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL,
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);
Q => Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a'
and fields 'col_b, col_c'.
Q => Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that
references 'col_pk' in 'table_x'.
(INNER) JOIN: Retrieves records that have matching values in both tables involved in the
join. This is the widely used join for queries.
SELECT *
FROM Table_A
JOIN Table_B;
SELECT *
FROM Table_A
INNER JOIN Table_B;
LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched
records/rows from the right table.
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON A.col = B.col;
RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched
records/rows from the left table.
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or
right table.
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;
Q => Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1'
from table_1 & 'col_2' from table_2 respectively. Do not use alias.
Q => Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1'
and 'Table_2', on columns 'Col_1' and 'Col_2' respectively.
The only difference between clustered and non-clustered indexes is that the database
manager attempts to keep the data in the database in the same order as the
corresponding keys appear in the clustered index.
Clustering index can improve the performance of most query operations because they
provide a linear-access path to data stored in the database.
1. Clustered index modifies the way records are stored in a database based on the indexed
column. Non-clustered index creates a separate entity within the table which references the
original table.
2. Clustered index is used for easy and speedy retrieval of data from the database, whereas,
fetching records from the non-clustered index is relatively slower.
3. In SQL, a table can have a single clustered index whereas it can have multiple non-
clustered indexes.
Q => Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is
equal to the above collection of "app_id".
WHERE clause in SQL is used to filter records that are necessary, based on specific
conditions.
ORDER BY clause in SQL is used to sort the records based on some field(s) in ascending
(ASC) or descending order (DESC).
SELECT *
FROM myDB.students
WHERE graduation_year = 2019
ORDER BY studentID DESC;
GROUP BY clause in SQL is used to group records with identical data and can be used in
conjuction with some aggregation functions to produce summarized results from the
database.
HAVING clause in SQL is used to filter records in combination with the GROUP BY clause.
It is different from WHERE, since WHERE clause cannot filter aggregated records.
SELECT COUNT(studentId), country
FROM myDB.students
WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;
Each SELECT statement within the clause must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement should necessarily have the same order
SELECT name FROM Students /* Fetch the union of queries */
UNION
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch the union of queries with duplicates*/
UNION ALL
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
MINUS /* that aren't present in contacts */
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
INTERSECT /* that are present in contacts as well */
SELECT name FROM Contacts;
Q => Write a SQL query to fetch "names" that are present in either table "accounts" or
in table "registry".
Q => Write a SQL query to fetch "names" that are present in "accounts" but not in table
"registry".
Q => Write a SQL query to fetch "names" from table "contacts" that are neither present
in "accounts.name" nor in "registry.name".
4. DECLARE a cursor after any variable declaration. The cursor declaration must always be
associated with a SELECT Statement.
5. Open cursor to initialize the result set. The OPEN statement must be called before
fetching rows from the result set.
6. FETCH statement to retrieve and move to the next row in the result set.
7. Call the CLOSE statement to deactivate the cursor.
8. Finally use the DEALLOCATE statement to delete the cursor definition and release the
associated resources.
DECLARE @name VARCHAR(50) /* Declare All Required Variables */
As we can observe, the Books Issued field has more than one values per record and to
convert it into 1NF, this has to be resolved into separate individual records for each book
issued. Check the following table in 1NF form -
Students Table (1st Normal Form)
Student Address Books Issued Salutation
Amanora Park Until the Day I Die (Emily
Sara Ms.
Town 94 Carpenter)
Amanora Park Inception (Christopher
Sara Ms.
Town 94 Nolan)
The Alchemist (Paulo
Ansh 62nd Sector A-10 Mr.
Coelho)
Ansh 62nd Sector A-10 Inferno (Dan Brown) Mr.
24th Street Park Beautiful Bad (Annie
Sara Mrs.
Avenue Ward)
24th Street Park Woman 99 (Greer
Sara Mrs.
Avenue Macallister)
Windsor Street
Ansh Dracula (Bram Stoker) Mr.
777
Here, WX is the only candidate key and there is no partial dependency, i.e., any proper
subset of WX doesn’t determine any non-prime attribute in the relation.
15. Third Normal Form
A relation is said to be in the third normal form, if it satisfies the conditions for second
normal form and there is no transitive dependency between the non-prime attributes,
i.e.,all non-prime attributes are determined only by the candidate keys of the relation and
not by any other non-prime attribute.
Example 1 - Consider the Students Table in the above example. As we can observe,
Students Table in 2NF form has a single candidate key Student_ID (primary key) that can
uniquely identify all records in the table. The field Salutation (non-prime attribute), however,
depends on the Student Field rather than the candidate key. Hence, the table is not in 3NF.
To convert it into 3rd Normal Form, we will once again partition the tables into two while
specifying a new Foreign Key constraint to identify the salutations for individual records in
the Students table. The Primary Key constraint for the same will be set on the Salutations
table to identify each record uniquely.
Students Table (3rd Normal Form)
Student_ID Student Address Salutation_ID
1 Sara Amanora Park Town 94 1
2 Ansh 62nd Sector A-10 2
3 Sara 24th Street Park Avenue 3
4 Ansh Windsor Street 777 1
For the above relation to exist in 3NF, all possible candidate keys in above relation should
be {P, RS, QR, T}.
16. Boyce-Codd Normal Form
A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal form
and for every functional dependency, Left-Hand-Side is super key. In other words, a
relation in BCNF has non-trivial functional dependencies in the form X –> Y, such that X
is always a super key. For example - In the above example, Student_ID serves as the sole
unique identifier for the Students Table and Salutation_ID for the Salutations Table, thus
these tables exist in BCNF. Same cannot be said for the Books Table and there can be
several books with common Book Names and same Student_ID.
Q => Write a SQL query to remove first 1000 records from table 'Temporary' based on
'id'.
Q => Write a SQL statement to delete the table 'Temporary' while keeping its relations
intact.
Scalar Function: As explained earlier, user-defined scalar functions return a single scalar
value.
Table Valued Functions: User-defined table-valued functions return a table as output.
Inline: returns a table data type based on a single SELECT statement.
Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements
can be used inside the function body.