SQL Flashcards
What are SQL dialects? Give some examples.
The various versions of SQL, are called SQL dialects. All the flavors of SQL have a very similar syntax and vary insignificantly only in additional functionality. Some examples are Microsoft SQL Server, PostgreSQL, MySQL, SQLite, T-SQL, Oracle, and MongoDB.
What are the main applications of SQL?
Using SQL, we can:
- create, delete, and update tables in a database
access, - manipulate, and modify data in a table
- retrieve and summarize the necessary information from a table or several tables
- add or remove certain rows or columns from a table
- integrate with other programming languages, such as Python or R, so we can use their combined power.
List examples of the types of SQL commands (or SQL subsets)
- Data Definition Language (DDL) – to define and modify the structure of a database. (CREATE, ALTER TABLE, DROP, TRUNCATE, and ADD COLUMN)
- Data Manipulation Language (DML) – to access, manipulate, and modify data in a database. (UPDATE, DELETE, and INSERT)
- Data Control Language (DCL) – to control user access to the data in the database and give or revoke privileges to a specific user or a group of users. (GRANT and REVOKE)
- Transaction Control Language (TCL) – to control transactions in a database. (COMMIT, SET TRANSACTION, ROLLBACK, and SAVEPOINT)
- Data Query Language (DQL) – to perform queries on the data in a database to retrieve the necessary information from it. (SELECT)
What is a constraint, provide examples
A set of conditions defining the type of data that can be input into each column of a table. Constraints ensure data integrity in a table and block undesired actions.
- DEFAULT – provides a default value for a column.
- UNIQUE – allows only unique values.
- NOT NULL – allows only non-null values.
- PRIMARY KEY – allows only unique and strictly non-null values (NOT NULL and UNIQUE).
- FOREIGN KEY – provides shared keys between two and more tables.
What is a join and what are the different types? How else can you combine data from two tables?
A clause used to combine and retrieve records from two or multiple tables. SQL tables can be joined based on the relationship between the columns of those tables.
- (INNER) JOIN – returns only those records that satisfy a defined join condition in both (or all) tables. It’s a default SQL join.
- LEFT (OUTER) JOIN – returns all records from the left table and those records from the right table that satisfy a defined join condition.
- RIGHT (OUTER) JOIN – returns all records from the right table and those records from the left table that satisfy a defined join condition.
- FULL (OUTER) JOIN – returns all records from both (or all) tables. It can be considered as a combination of left and right joins.
Can also use UNION to combine data from two tables
What’s the basic syntax for updating a table?
UPDATE table_name
SET col_1 = value_1, column_2 = value_2
WHERE condition;
How to get the count of records in a table?
Using the COUNT() aggregate function with the asterisk passed as its argument: SELECT COUNT(*) FROM table_name;.
How to select common records from two tables?
Using the INTERSECT statement:
SELECT * FROM table_1
INTERSECT
SELECT * FROM table_1;
NOTE: both select statements must return same number of columns
What are some common aggregate functions?
AVG() – returns the average value
SUM() – returns the sum of values
MIN() – returns the minimum value
MAX() – returns the maximum value
COUNT() – returns the number of rows, including those with null values
FIRST() – returns the first value from a column
LAST()– returns the last value from a column
What are some common scalar functions?
LEN() (in other SQL flavors – LENGTH()) – returns the length of a string, including the blank spaces
UCASE() (in other SQL flavors – UPPER()) – returns a string converted to the upper case
LCASE() (in other SQL flavors – LOWER()) – returns a string converted to the lower case
INITCAP() – returns a string converted to the title case (i.e., each word of the string starts from a capital letter)
MID() (in other SQL flavors – SUBSTR()) – extracts a substring from a string
ROUND() – returns the numerical value rounded to a specified number of decimals
NOW() – returns the current date and time
What are some common string manipulation functions?
CONCAT() – joins two or more string values appending the second string to the end of the first one
SUBSTR() – returns a part of a string satisfying the provided start and end points
LENGTH() (in other SQL flavors – LEN()) – returns the length of a string, including the blank spaces
REPLACE() – replaces all occurrences of a defined substring in a provided string with another substring
INSTR() – returns the numeric position of a defined substring in a provided string
LPAD() and RPAD() – return the padding of the left-side/right-side character for right-justified/left-justified value
TRIM() – removes all the defined characters, as well as white spaces, from the left, right, or both ends of a provided string
What is the difference between a primary key and a unique key?
While both types of keys ensure unique values in a column of a table, the first one identifies uniquely each record of the table, and the second one prevents duplicates in that column.
What is the order of appearance of the common statements in the SELECT query?
SELECT – FROM – JOIN – ON – WHERE – GROUP BY – HAVING – ORDER BY – LIMIT
What’s a CASE statement and what’s the syntax?
The way to implement the if-then-else logic in SQL. This function sequentially checks the provided conditions in the WHEN clauses and returns the value from the corresponding THEN clause when the first condition is satisfied. If none of the conditions is satisfied, the function returns the value from the ELSE clause in case it’s provided, otherwise, it returns NULL. The syntax is:
CASE
WHEN condition_1 THEN value_1
WHEN condition_2 THEN value_2
WHEN condition_3 THEN value_3
…
ELSE value
END;
How to select all even or all odd records in a table?
SELECT * FROM table_name
WHERE ID_column % 2 = 0;
Find the 6th highest value in a column of a table.
SELECT * FROM table_name
ORDER BY column_name DESC
LIMIT 1
OFFSET 5;
How to find the values in a text column of a table that start with a certain letter?
SELECT * FROM table_name
WHERE surname LIKE ‘A%’;
Select 5 random rows from a table
SELECT * FROM your_table
ORDER BY RANDOM()
LIMIT 5;
NOTE: This will be very slow on a large table
what’s a CTE in sql?
What’s the basic syntax to create one? 
A Common Table Expression (CTE) in SQL is a temporary result set that can be referred to within the context of a SELECT, INSERT, UPDATE, or DELETE statement. CTEs provide a way to break down complex queries into simpler, more manageable parts. They are defined using the WITH clause and can be referenced within the query.
The basic syntax is:
WITH cte_name (column1, column2, …) AS (
– CTE query definition
SELECT column1, column2, …
FROM your_table
WHERE conditions
)
– Main query using the CTE
SELECT *
FROM cte_name;
***subquery examples
Given table Products (productId, name, supplierId) :
Find the percentage of the products supplied by each supplier.
SELECT SupplierID,
count() * 100.0 / (SELECT count() from Products) as “Supplier Percentage”
FROM Products
GROUP BY SupplierID
***percent change overtime
What is guaranteed to be returned from the following query if there is a NULL value in races.winner_id?
SELECT * FROM runners WHERE id NOT IN (SELECT winner_id FROM races)
Nothing. If there is a NULL in the subquery nothing will be returned even if there are some other matches. Instead use:
SELECT * FROM runners WHERE id NOT IN (SELECT winner_id FROM races WHERE winner_id IS NOT NULL)
Assume a schema of Emp ( Id, Name, DeptId ) , Dept ( Id, Name).
If there are 10 records in the Emp table and 5 records in the Dept table, how many rows will be displayed in the result of the following SQL query:
Select * From Emp, Dept
The query will result in 50 rows as a “cartesian product” or “cross join”, which is the default whenever the ‘where’ clause is omitted.