SQL Questions I Flashcards

1
Q

What is Pattern Matching in SQL?

A

SQL pattern matching provides for p**attern search in data **if you have no clue as to what that word should be.

This kind of SQL query uses wildcards to match a string pattern, rather than writing the exact word. The LIKE operator is used in conjunction with SQL Wildcards to fetch the required information.

Using the % wildcard to perform a simple search

The % wildcard matches zero or more characters of any type and can be used to define wildcards both before and after the pattern.
Search a student in your database with first name beginning with the letter K:

SELECT *
FROM students
WHERE first_name LIKE ‘K%

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Omitting the patterns using the NOT keyword

A

SELECT *
FROM students
WHERE first_name NOT LIKE ‘K%’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Matching a pattern anywhere using the % wildcard twice

A

Search for a student in the database where he/she has a K in his/her first name.

SELECT *
FROM students
WHERE first_name LIKE ‘%Q%’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Using the _ wildcard to match pattern at a specific position

A

The _ wildcard matches exactly one character of any type. It can be used in conjunction with **% **wildcard. This query fetches all students with letter K at the third position in their first name.

SELECT *
FROM students
WHERE first_name LIKE ‘__K%’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Matching patterns for a specific length

A

The _ wildcard plays an important role as a limitation when it matches exactly one character. It limits the length and position of the matched results. For example -

SELECT * /* Matches first names with three or more letters */
FROM students
WHERE first_name LIKE ‘___%’

SELECT * /* Matches first names with exactly four characters */
FROM students
WHERE first_name LIKE ‘____’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to create empty tables with the same structure as another table?

A

Creating empty tables with the same structure can be done smartly by fetching the records of one table into a new table using the INTO operator while fixing a WHERE clause to be false for all records.
Hence, SQL prepares the new table with a duplicate structure to accept the fetched records but since no records get fetched due to the WHERE clause in action, nothing is inserted into the new table.

SELECT * INTO Students_copy
FROM Students WHERE 1 = 2

SQL SELECT INTO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a Recursive Stored Procedure?

A

A stored procedure that calls itself until a boundary condition is reached is called a recursive stored procedure. This recursive function helps the programmers to deploy the same set of code several times as and when required.** Some SQL programming languages limit the recursion depth** to prevent an infinite loop of procedure calls from causing a stack overflow, which slows down the system and may lead to system crashes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a Stored Procedure

A

A stored procedure is a subroutine available to applications that access a relational database management system (RDBMS). Such procedures are stored in the database data dictionary. The sole disadvantage of stored procedure is that it can be executed nowhere except in the database and occupies more memory in the database server. It also provides a sense of security and functionality as users who can’t access the data directly can be granted access via stored procedures.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is Collation? What are the different types of Collation Sensitivity?

A

Collation refers to a set of rules that determine how data is sorted and compared

Rules defining the correct character sequence are used to sort the character data. It incorporates options for specifying case sensitivity, accent marks, kana character types, and character width. Below are the different types of collation sensitivity:

Case sensitivity: A and a are treated differently.

Accent sensitivity: a and á are treated differently.

Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated differently.

Width sensitivity: Same character represented in single-byte (half-
width) and double-byte (full-width) are treated differently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the differences between OLTP and OLAP?

A

OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting transaction-oriented programs. An important attribute of an OLTP system is its ability to maintain concurrency. OLTP systems often follow a decentralized architecture to avoid single points of failure. These systems are generally designed for a large audience of end-users who conduct short transactions. Queries involved in such databases are generally simple, need fast response times, and return relatively few records. A number of transactions per second acts as an effective measure for such systems.

OLAP stands for Online Analytical Processing, a class of software programs that are characterized by the relatively low frequency of online transactions. Queries are often too complex and involve a bunch of aggregations. For OLAP systems, the effectiveness measure relies highly on response time. Such systems are widely used for data mining or maintaining aggregated, historical data, usually in multi-dimensional schemas.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is OLTP?

A

OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting transaction-oriented programs. An essential attribute of an OLTP system is its ability to maintain concurrency. To avoid single points of failure, OLTP systems are often decentralized. These systems are usually designed for a large number of users who conduct short transactions. Database queries are usually simple, require sub-second response times, and return relatively few records. Here is an insight into the working of an OLTP system [ Note - The figure is not important for interviews ] -

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is User-defined function? What are its various types?

A

The user-defined functions in SQL are like functions in any other programming language that accept parameters, perform complex calculations, and return a value. They are written to use the logic repetitively whenever required. There are two types of SQL user-defined functions:

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a UNIQUE constraint?

A

A UNIQUE constraint ensures that all values in a column are different. This provides uniqueness for the column(s) and helps identify each row uniquely. Unlike primary key, there can be multiple unique constraints defined per table. The code syntax for UNIQUE is quite similar to that of PRIMARY KEY and can be used interchangeably.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a Query?

A

A query is a request for data or information from a database table or combination of tables. A database query can be either a select query or an action query.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is Data Integrity?

A

Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle and is a critical aspect of the design, implementation, and usage of any system which stores, processes, or retrieves data. It also defines integrity constraints to enforce business rules on the data when it is entered into an application or a database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between Clustered and Non-clustered index?

A

As explained above, the differences can be broken down into three small factors -

Clustered index modifies the way records are stored in a database based on the indexed column.

A non-clustered index creates a separate entity within the table which references the original table.

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.

In SQL, a table can have a single clustered index whereas it can have multiple non-clustered indexes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a Cross-Join?

A

Cross join can be defined as a cartesian product of the two tables included in the join. The table after join contains the same number of rows as in the cross-product of the number of rows in the two tables. If a WHERE clause is used in cross join then the query will work like an INNER JOIN.

everything from table A is connected with ever record from table B

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a Self-Join?

A

A self JOIN is a case of regular join where a table is joined to itself based on some relation between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN clause and a table alias is used to assign different names to the table within the query.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is a Join? List its different types.

A

The SQL Join clause is used to combine records (rows) from two or more tables in a SQL database based on a related column between the two.

(INNER) JOIN: Retrieves records that have matching values in both tables involved in the join. This is the widely used join for queries.

LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched records/rows from the right table.

in the right table there can be nulls!

RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched records/rows from the left table.

FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or right table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is a Foreign Key?

A

A FOREIGN KEY comprises of single or collection of fields in a table that essentially refers to the PRIMARY KEY in another table . Foreign key constraint ensures referential integrity in the relation between two tables.

The table with the foreign key constraint is labeled as the child table, and the table containing the candidate key is labeled as the referenced or parent table.

21
Q

What is a Subquery? What are its types?

A

A subquery is a query within another query, also known as a nested query or inner query. It is used to restrict or enhance the data to be queried by the main query, thus restricting or enhancing the output of the main query respectively. For example, here we fetch the contact information for students who have enrolled for the maths subject:

There are two types of subquery - Correlated and Non-Correlated.

-> A correlated subquery cannot be considered as an independent query, but it can refer to the column in a table listed in the FROM of the main query.
-> A non-correlated subquery can be considered as an independent query and the output of the subquery is substituted in the main query.

22
Q

What is a Primary Key?

A

The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is comprised of single or multiple fields (columns).

23
Q

What are Constraints in SQL?

A

Constraints are used to specify the rules concerning data in the table. It can be applied for single or multiple fields in an SQL table during the creation of the table or after creating using the ALTER TABLE command. The constraints are:

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.

24
Q

What are Tables and Fields?

A

A table is an organized collection of data stored in the form of rows and columns. Columns can be categorized as vertical and rows as horizontal. The columns in a table are called fields while the rows can be referred to as records.

25
Q

What is the difference between SQL and MySQL?

A

SQL is a standard language for retrieving and manipulating structured databases. On the contrary, MySQL is a relational database management system, like SQL Server, Oracle or IBM DB2, that is used to manage SQL databases.

26
Q

What is SQL?

A

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

27
Q

What is RDBMS? How is it different from DBMS?

A

RDBMS stands for Relational Database Management System. The key difference here, compared to DBMS, is that RDBMS stores data in the form of a collection of tables, and relations can be defined between the common fields of these tables. Most modern database management systems like MySQL, Microsoft SQL Server, Oracle, IBM DB2, and Amazon Redshift are based on RDBMS.

28
Q

What is DBMS?

A

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 software.

29
Q

What is Database?

A

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

30
Q

What are UNION, MINUS and INTERSECT commands?

A

The UNION operator combines and returns the result-set retrieved by two or more SELECT statements.

The MINUS operator in SQL is used to remove duplicates from the result-set obtained by the second SELECT query from the result-set obtained by the first SELECT query and then return the filtered results from the first.

The INTERSECT clause in SQL combines the result-set fetched by the two SELECT statements where records from one match the other and then returns this intersection of result-sets.

Certain conditions need to be met before executing either of the above statements in SQL -

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

31
Q

What is Cursor? How to use a Cursor?

A

A database cursor is a control structure that allows for the traversal of records in a database.

Kursor (ang. cursor) w SQL to mechanizm umożliwiający iteracyjne przetwarzanie wyników zapytania. Jest szczególnie przydatny, gdy potrzebujesz manipulować rekordami jeden po drugim, a nie przetwarzać całej tabeli naraz.

Cursors, in addition, facilitates processing after traversal, such as retrieval, addition, and deletion of database records. They can be viewed as a pointer to one row in a set of rows.

Working with SQL Cursor:

DECLARE a cursor after any variable declaration. The cursor declaration must always be associated with a SELECT Statement.

Open cursor to initialize the result set. The OPEN statement must be called before fetching rows from the result set.

FETCH statement to retrieve and move to the next row in the result set.

Call the CLOSE statement to deactivate the cursor.

Finally use the DEALLOCATE statement to delete the cursor definition and release the associated resources.

32
Q

What are Entities and Relationships?

A

Entity: An entity can be a real-world object, either tangible or intangible, that can be easily identifiable. For example, in a college database, students, professors, workers, departments, and projects can be referred to as entities. Each entity has some associated properties that provide it an identity.

Relationships: Relations or links between entities that have something to do with each other. For example - The employee’s table in a company’s database can be associated with the salary table in the same database.

33
Q

List the different types of relationships in SQL.

A

One-to-One - This can be defined as the relationship between two tables where each record in one table is associated with the maximum of one record in the other table.

One-to-Many & Many-to-One - This is the most commonly used relationship where a record in a table is associated with multiple records in the other table.

Many-to-Many - This is used in cases when multiple instances on both sides are needed for defining a relationship.

Self-Referencing Relationships - This is used when a table needs to define a relationship with itself.

34
Q

What is an Alias in SQL?

A

An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a temporary name assigned to the table or table column for the purpose of a particular SQL query. In addition, aliasing can be employed as an obfuscation technique to secure the real names of database fields. A table alias is also called a correlation name.

An alias is represented explicitly by the AS keyword but in some cases, the same can be performed without it as well. Nevertheless, using the AS keyword is always a good practice.

35
Q

What is a View?

A

A view in SQL is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.

36
Q

What is Normalization?

A

Normalization represents the way of organizing structured data in the database efficiently.

It includes the creation of tables, establishing relationships between them, and defining rules for those relationships.

Inconsistency and redundancy can be kept in check based on these rules, hence, adding flexibility to the database.

37
Q

What is Denormalization?

A

Denormalization is the inverse process of normalization, where the normalized schema is converted into a schema that has redundant information.

The performance is improved by using redundancy and keeping the redundant data consistent.

The reason for performing denormalization is the overheads produced in the query processor by an over-normalized structure.

38
Q

What is the difference between DROP and TRUNCATE statements?

A

If a table is dropped, all things associated with the tables are dropped as well. This includes - the relationships defined on the table with other tables, the integrity checks and constraints, access privileges and other grants that the table has.

To create and use the table again in its original form, all these relations, checks, constraints, privileges and relationships need to be redefined.

However, if a table is truncated, none of the above problems exist and the table retains its original structure

39
Q

What is the difference between DELETE and TRUNCATE statements?

A

The TRUNCATE command is used to delete all the rows from the table and free the space containing the table.

The DELETE command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.

40
Q

What are Aggregate functions?

A

An aggregate function performs operations on a collection of values to return a single scalar value.

Aggregate functions are often used with the GROUP BY and HAVING clauses of the SELECT statement. Following are the widely used SQL aggregate functions:

AVG() - Calculates the mean of a collection of values.
COUNT() - Counts the total number of records in a specific table or view.
MIN() - Calculates the minimum of a collection of values.
MAX() - Calculates the maximum of a collection of values.
SUM() - Calculates the sum of a collection of values.
FIRST() - Fetches the first element in a collection of values.
LAST() - Fetches the last element in a collection of values.
Note: All aggregate functions described above ignore NULL values except for the COUNT function.

41
Q

What are scalar functions?

A

A scalar function returns a single value based on the input value. Following are the widely used SQL scalar functions:

LEN() - Calculates the total length of the given field (column).
UCASE() - Converts a collection of string values to uppercase characters.
LCASE() - Converts a collection of string values to lowercase characters.
MID() - Extracts substrings from a collection of string values in a table.
CONCAT() - Concatenates two or more strings.
RAND() - Generates a random collection of numbers of a given length.
ROUND() - Calculates the round-off integer value for a numeric field (or decimal point values).
NOW() - Returns the current date & time.
FORMAT() - Sets the format to display a collection of values.

42
Q

What is PostgreSQL?

A

PostgreSQL was first called Postgres and was developed by a team led by Computer Science Professor Michael Stonebraker in 1986. It was developed to help developers build enterprise-level applications by upholding data integrity by making systems fault-tolerant. PostgreSQL is therefore an enterprise-level, flexible, robust, open-source, and object-relational DBMS that supports flexible workloads along with handling concurrent users. It has been consistently supported by the global developer community. Due to its fault-tolerant nature, PostgreSQL has gained widespread popularity among developers

43
Q

Define tokens in PostgreSQL?

A

A token in PostgreSQL is either a keyword, identifier, literal, constant, quotes identifier, or any symbol that has a distinctive personality. They may or may not be separated using a space, newline or a tab. If the tokens are keywords, they are usually commands with useful meanings. Tokens are known as building blocks of any PostgreSQL code

44
Q

SQL execution of order

A

FROM,
JOIN,
WHERE,
GROUP BY,
HAVING,

SELECT,
DISTINCT,
ORDER BY,
and finally, LIMIT/OFFSET.

45
Q

Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)

A

Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is driven by a database engine. The primary work of the database engine is to interpret SQL queries and find the accessing technique for getting different data structures in the database.

This is also an important feature of the data engine so used to evaluate the accuracy and efficiency of the outcomes. Here are few groups of commands included in the SQL – DDL (Data Definition Language) and DML (Data Manipulation Language).

DDL is used for describing and modification of several data structures.

While DML is intended to access and change of the data save within the data structures defined by DDL.

Transact-SQL (T-SQL): Transact-SQL (T-SQL) is an extension of SQL. It is considered as procedural language, unlike SQL that is used by SQL server. It is helpful in doing operations like getting the data from a single row, addition of new rows, getting multiple rows. The syntax is different from others like PL-SQL. However, it has the same functionality and generates similar results as other languages. This is the Microsoft implementation of the structured query language for SQL server.

46
Q

DDL and DML

A

This is also an important feature of the data engine so used to evaluate the accuracy and efficiency of the outcomes. Here are few groups of commands included in the SQL – DDL (Data Definition Language) and DML (Data Manipulation Language). DDL is used for describing and modification of several data structures. While DML is intended to access and change of the data save within the data structures defined by DDL.

47
Q

DDL

A

CREATE: tworzenie nowych obiektów w bazie danych, np. tabel.
ALTER: modyfikacja istniejących obiektów, np. dodawanie kolumn.
DROP: usuwanie obiektów z bazy danych.
TRUNCATE: szybkie usuwanie wszystkich danych z tabeli (ale nie samej tabeli).

48
Q

DML

A

INSERT: dodawanie danych do tabeli.
UPDATE: aktualizacja istniejących danych w tabeli.
DELETE: usuwanie danych z tabeli.
SELECT: pobieranie danych z tabeli (często zaliczane do DQL - Data Query Language).