SQL is the modular connection utilized to define, query, modify, secure, and negociate information successful relational databases. It matters because existent systems specified arsenic UPI payments, infirmary records, SaaS dashboards, and e-commerce checkouts dangle connected accurate, fast, accordant information retrieval. After reading, you tin creation queries, logic astir performance, and reply interview-style SQL questions confidently.
SQL sits betwixt exertion codification and system information storage, truthful backend developers, information analysts, information engineers, DBAs, and merchandise analytics teams trust connected it daily. If you request a compact bid reference while practising, support the List of SQL Commands pinch Examples useful for revision.
You will beryllium capable to categorize SQL commands, constitute joins and subqueries, usage constraints and transactions correctly, use indexes thoughtfully, and explicate precocious features specified arsenic CTEs, model functions, stored procedures, triggers, and cursors.
Who This Guide Is For
This guideline is specifically designed for:
Core Concepts
SQL is not 1 feature; it is simply a family of connection categories, relational operations, integrity rules, and capacity tools. A mature SQL personification knows erstwhile to specify schema, erstwhile to query data, erstwhile to alteration data, erstwhile to unafraid access, and erstwhile to power transactions. The array beneath maps the modular concepts you must know.
SQL Command Categories
SQL commands are grouped by intent. DDL changes structure, DML changes rows, DQL sounds rows, DCL manages permissions, and TCL controls transactions. This classification is heavy tested because galore learners retrieve commands by syntax but not by purpose.
A acquainted illustration is simply a PAN verification app: DDL creates the applicant table, DML inserts verification status, DQL retrieves pending cases, DCL restricts entree to compliance staff, and TCL commits the full verification update only aft each checks pass. An industry-specific illustration is simply a SaaS billing level wherever schema changes, invoice inserts, gross queries, domiciled permissions, and costs transaction commits must beryllium separated cleanly.
A modular exam mobility asks: categorize CREATE, INSERT, SELECT, GRANT, and COMMIT. The reply is DDL, DML, DQL, DCL, and TCL respectively.Code Example
Data Definition Language
DDL defines and changes database objects. Common DDL commands see CREATE, ALTER, DROP, TRUNCATE, and RENAME. These commands impact structure, truthful they request other attraction successful accumulation because a incorrect DROP aliases TRUNCATE tin region captious objects aliases information very quickly.
A acquainted illustration is creating a array for metro smart-card top-ups pinch paper number, recharge amount, and timestamp. An industry-specific illustration is an ed-tech level adding a caller nullable file for proctored exam position aft launching online assessments. DDL is besides wherever naming conventions, information types, keys, and storage-related choices begin.
DDL changes database structure. Many database engines auto-commit DDL statements, truthful rollback behaviour tin disagree crossed systems. Check your DBMS earlier moving destructive DDL.Code Example
Data Manipulation Language
DML changes the information stored wrong tables. INSERT adds rows, UPDATE modifies existing rows, DELETE removes rows, and MERGE performs conditional insert-or-update behaviour successful systems that support it. Good DML ever targets the correct rows, particularly erstwhile penning UPDATE and DELETE statements.
A acquainted illustration is updating the transportation position for a market app bid aft the rider picks it up. An industry-specific illustration is simply a banking reconciliation occupation that marks settled NEFT transfers aft matching them pinch a colony file. In some cases, a missing WHERE clause tin harm thousands of rows.
The astir communal DML correction is moving UPDATE aliases DELETE without a WHERE clause. In production, preview target rows pinch SELECT earlier modifying them.Code Example
Querying and Filtering
DQL is chiefly represented by SELECT. It retrieves information utilizing projection, filtering, sorting, limiting, grouping, and expressions. Intermediate SQL accomplishment originates erstwhile you extremity penning wide SELECT * queries and commencement selecting only the columns and rows needed for the task.
A acquainted illustration is filtering FASTag toll transactions for a circumstantial conveyance and day range. An industry-specific illustration is simply a healthcare analytics squad retrieving only high-risk laboratory reports from the past 7 days for a objective dashboard. Good filters trim web transfer, amended privacy, and thief the optimizer take amended plans.
Logical SQL processing bid is commonly tested: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. The written bid is different from the logical information order.Code Example
Constraints and Keys
Constraints are database-enforced rules that protect information integrity. Standard constraints see PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, and DEFAULT. Keys picture personality and relationships: a superior cardinal identifies a row, a overseas cardinal references different table, campaigner keys tin uniquely place rows, and composite keys usage aggregate columns together.
A acquainted illustration is Aadhaar-based demographic retention wherever 1 resident grounds should person 1 unsocial Aadhaar value. An industry-specific illustration is simply a drugstore inventory strategy wherever a medicine point must reference a valid medicine and amount must beryllium greater than zero. Constraints forestall invalid information moreover erstwhile aggregate applications constitute to the aforesaid database.
Primary keys cannot beryllium NULL and must beryllium unique. Foreign keys whitethorn beryllium NULL unless explicitly declared NOT NULL, but non-NULL overseas cardinal values must lucifer a referenced key.Code Example
Joins and Relationships
Joins harvester rows from related tables. INNER JOIN keeps matching rows, LEFT JOIN keeps each rows from the near side, RIGHT JOIN keeps each rows from the correct side, FULL OUTER JOIN keeps each rows from some sides, CROSS JOIN creates each combinations, SELF JOIN joins a array to itself, and NATURAL JOIN automatically joins same-named columns wherever supported.
A acquainted illustration is an IRCTC booking study that joins passengers pinch tickets to show train, berth, and costs details. An industry-specific illustration is simply a logistics power building joining shipment, warehouse, and bearer tables to place delayed consignments. Joins are wherever relational modeling becomes visible successful query form.
Do not usage NATURAL JOIN casually. If a caller same-named file is added later, the subordinate information tin silently alteration and nutrient incorrect results.Code Example
Subqueries and CTEs
Subqueries spot 1 query wrong another. They tin beryllium scalar, row, table, correlated, aliases non-correlated, and they look successful SELECT, FROM, WHERE, HAVING, INSERT, UPDATE, and DELETE statements. CTEs, written pinch WITH, sanction a impermanent consequence group and make analyzable logic easier to read.
A acquainted illustration is simply a wallet app uncovering users whose monthly spending is supra their metropolis average. An industry-specific illustration is simply a telecom fraud-detection query that first builds suspicious telephone patterns and past filters accounts utilizing that intermediate result. For deeper syntax practice, the elaborate guideline connected CTE successful SQL is simply a earthy companion to this topic.
A correlated subquery executes pinch reference to the outer query row. Interviewers often inquire why it tin beryllium slower than a subordinate aliases CTE-based rewrite connected ample datasets.Code Example
Aggregation and Grouping
Aggregation converts elaborate rows into summaries. COUNT, SUM, AVG, MIN, and MAX are the halfway aggregate functions, usually mixed pinch GROUP BY. WHERE filters rows earlier grouping, while HAVING filters groups aft aggregation.
A acquainted illustration is calculating monthly energy measure totals for each user category. An industry-specific illustration is simply a marketplace finance squad computing gross merchandise value, refund value, and nett gross by seller. Aggregation is basal for dashboards, reconciliations, compliance summaries, and analytics interviews.
Use WHERE for row-level filtering earlier GROUP BY and HAVING for aggregate filtering aft GROUP BY. This favoritism is simply a predominant root of incorrect answers.Code Example
Window Functions
Window functions cipher crossed related rows without collapsing the consequence set. Common categories see ranking functions specified arsenic ROW_NUMBER, RANK, and DENSE_RANK; offset functions specified arsenic LAG and LEAD; aggregate windows specified arsenic moving SUM; and distribution functions specified arsenic NTILE, CUME_DIST, and PERCENT_RANK wherever supported.
A acquainted illustration is ranking exam candidates wrong each metropolis while still showing each campaigner row. An industry-specific illustration is simply a stock-broking level comparing each waste and acquisition value pinch the erstwhile waste and acquisition value for the aforesaid instrument. Window functions are a awesome measurement beyond GROUP BY because they sphere row-level detail.
RANK leaves gaps aft ties, DENSE_RANK does not time off gaps, and ROW_NUMBER ever assigns a unsocial sequence. This quality is wide tested successful SQL interviews.Code Example
Views and Indexes
A position is simply a saved query exposed for illustration a table. It tin hide analyzable joins, restrict columns, and standardize business logic. A materialized view, supported by respective databases, stores the query consequence physically and refreshes it based connected database-specific rules.
An scale is simply a information building that speeds up lookups, joins, sorting, and characteristic checks, usually astatine the costs of other retention and slower writes. A acquainted illustration is simply a taxation portal position that exposes only safe payer fields to support agents. An industry-specific illustration is simply a food-delivery hunt scale connected edifice metropolis and cuisine to make find faster during highest traffic.
Indexes are not automatically bully for each column. Low-selectivity columns, very mini tables, and heavy-write workloads whitethorn not use from other indexes.Code Example
Transactions and ACID
A transaction is simply a logical portion of activity that succeeds wholly aliases fails safely. ACID stands for Atomicity, Consistency, Isolation, and Durability. Transaction isolation levels commonly see READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE, though nonstop behaviour differs by database engine.
A acquainted illustration is simply a UPI transportation wherever debit and in installments must hap together aliases not astatine all. An industry-specific illustration is an security declare support travel wherever declare status, ledger entry, and audit way must enactment consistent. Transactions protect correctness erstwhile galore users and services run astatine the aforesaid time.
The astir tested transaction anomalies are soiled read, non-repeatable read, phantom read, and mislaid update. Higher isolation reduces anomalies but tin trim concurrency.Code Example
Stored Logic
Stored logic moves reusable behaviour into the database. Stored procedures execute actions, functions return values, triggers tally automatically connected array events, and cursors process consequence sets statement by row. These devices are useful but should not switch clear exertion creation aliases set-based SQL erstwhile a simpler query works.
A acquainted illustration is simply a coupon strategy utilizing a stored process to use discount rules consistently. An industry-specific illustration is simply a infirmary audit trigger that records each update to a diligent admittance status. Cursors are little communal successful modern set-based SQL, but they still look successful administrative scripts and bequest endeavor systems.
Prefer set-based SQL for bulk operations. Use cursors only erstwhile each statement genuinely needs sequential handling, outer calls, aliases procedural authorities that cannot beryllium expressed cleanly arsenic a group operation.Code Example
Normalization and Design
Normalization organizes information to trim plagiarism and update anomalies. First Normal Form removes repeating groups, Second Normal Form removes partial dependency connected a composite key, Third Normal Form removes transitive dependency, and BCNF strengthens determinant rules. In production, teams sometimes denormalize cautiously for performance, but they should understand the trade-off.
A acquainted illustration is separating elector floor plan information from polling booth allocation truthful booth changes do not copy elector details. An industry-specific illustration is simply a subscription level separating plan, customer, invoice, and costs tables truthful value changes and invoice history stay accurate. Good schema creation makes queries simpler and constraints much meaningful.
Normalization questions often inquire which normal shape is violated. Check repeating groups for 1NF, partial dependency for 2NF, transitive dependency for 3NF, and non-candidate-key determinants for BCNF.Code Example
Security and Injection
SQL information includes authentication, authorization, slightest privilege, auditing, information masking, encryption support, and safe query execution. DCL commands negociate permissions, while exertion codification must usage parameterized queries to forestall SQL injection. Security belongs successful some database creation and exertion development.
A acquainted illustration is simply a assemblage results portal wherever students should publication only their ain marks, not the full marks table. An industry-specific illustration is simply a lending level wherever credit-risk analysts tin publication anonymized borrower features but cannot update disbursal records. Least privilege keeps accidental and malicious harm limited.
Never build SQL by concatenating earthy personification input. Parameterized queries are the modular defense against SQL injection successful exertion code.Code Example
Write SQL successful this bid mentally: exemplary the data, enforce integrity, query only what you need, protect transactions, scale based connected existent entree patterns, and unafraid each support path.Learning Path
Use this way to move from correct syntax to production-ready reasoning. Practise each shape connected a existent database specified arsenic PostgreSQL, MySQL, SQL Server, SQLite, aliases Snowflake, because SQL behaviour tin alteration crossed engines.
Frequently Asked Questions
What is SQL?
SQL is simply a connection for defining, querying, modifying, controlling, and securing information successful relational database systems. It is utilized successful exertion backends, reporting systems, analytics platforms, information warehouses, and administrative scripts.
What is the quality betwixt SQL and MySQL?
SQL is the language, while MySQL is simply a relational database guidance strategy that implements SQL pinch its ain features and dialect. PostgreSQL, SQL Server, Oracle Database, SQLite, and Snowflake besides support SQL, but syntax and behaviour tin differ.
What is the quality betwixt WHERE and HAVING?
WHERE filters rows earlier grouping, while HAVING filters groups aft aggregation. Use WHERE for conditions specified arsenic metropolis equals Mumbai and HAVING for conditions specified arsenic full income greater than 1 lakh.
When should I usage a subordinate alternatively of a subquery?
Use a subordinate erstwhile you request columns from aggregate related tables aliases erstwhile the subordinate expresses the narration clearly. Use a subquery aliases CTE erstwhile it improves readability, isolates logic, aliases represents a filtering information naturally.
What are the main types of SQL joins?
The modular subordinate types are INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN, CROSS JOIN, and SELF JOIN. NATURAL JOIN besides exists successful immoderate databases, but it should beryllium utilized cautiously because it depends connected same-named columns.
What is an scale successful SQL?
An scale is simply a database building that helps the motor find rows faster, akin to an scale successful a book. Indexes amended galore publication operations but adhd retention overhead and tin slow down inserts, updates, and deletes.
What are ACID properties?
ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties picture really transactions support information correct during failures, concurrent access, and multi-step changes.
What is the biggest SQL correction successful interviews?
The biggest correction is penning a query that looks syntactically correct but ignores duplicates, NULL values, subordinate cardinality, aliases aggregation level. Interviewers often attraction much astir correct reasoning than a clever one-line query.
Interview Preparation
SQL question and reply questions trial some syntax and reasoning. Strong answers explicate information relationships, statement counts, copy handling, NULL behavior, constraints, and capacity trade-offs earlier presenting the last query.
Conceptual Questions
- Why is SELECT classified separately from DML successful galore textbooks? SELECT sounds information but does not modify stored rows, truthful it is commonly classified arsenic DQL. INSERT, UPDATE, DELETE, and MERGE alteration information and beryllium to DML.
- What is the quality betwixt PRIMARY KEY and UNIQUE? A superior cardinal uniquely identifies each statement and cannot incorporate NULL values. A UNIQUE constraint prevents copy values, but NULL handling depends connected the database system.
- Why tin indexes make writes slower? Every INSERT, UPDATE, aliases DELETE whitethorn besides update 1 aliases much scale structures. More indexes tin velocity sounds but summation constitute costs and retention usage.
- What is the quality betwixt RANK and DENSE_RANK? RANK assigns the aforesaid rank to ties and leaves gaps aft ties. DENSE_RANK besides assigns the aforesaid rank to ties but continues without gaps.
Applied / Problem-Solving Questions
- How would you find customers pinch nary orders? Use a LEFT JOIN from customers to orders and select rows wherever the bid cardinal is NULL. This shape preserves each customers and identifies missing matches.
- How would you get the second-highest net aliases score? Use DENSE_RANK complete the worth successful descending bid and select rank equals two. This handles ties amended than a elemental MAX little than MAX pattern.
- How would you forestall double spending successful a wallet system? Use a transaction, cheque capable equilibrium successful the debit update, fastener aliases isolate competing updates appropriately, and perpetrate debit and in installments together. Also enforce database constraints to forestall antagonistic balances wherever possible.
- How would you optimize a slow study query? Start pinch the execution plan, verify filters and subordinate conditions, region unnecessary columns, cheque indexes, and corroborate array statistics. Avoid guessing; measurement earlier and aft each change.
Key Takeaways
SQL mastery depends connected 5 actual skills: classifying commands correctly, modeling information pinch keys and constraints, penning joins and aggregations astatine the correct grain, utilizing transactions for consistency, and applying indexes only erstwhile entree patterns warrant them.
For GATE and interviews, the astir tested points are bid categories, subordinate outputs, WHERE versus HAVING, superior cardinal versus overseas key, normalization forms, ACID properties, isolation anomalies, and RANK versus DENSE_RANK. Practise explaining the consequence style earlier penning syntax.
The earthy adjacent measurement is revising Rank() usability successful SQL, because ranking questions are communal successful analytics, product, and placement interviews.
Further Reading
- What Is SQL Stored Procedure? How To Create One?, Learn really reusable database-side procedures are created and used.
- Cursor successful SQL, Understand row-by-row processing for cases wherever set-based SQL is not enough.
English (US) ·
Indonesian (ID) ·