Experienced

QA and Software Testing | 232 questions | 2026

QA interview questions for experienced

Questions for candidates with 2 to 5 years of experience, by topic. Tap a question to see the model answer.

Manual Testing

ExperiencedMost askedScenarioFree with sign-in
Answer

Walk me through a project on your CV and your testing role in it.

Use a short structure: context, your role, what you did, results, what you learned.

ExperiencedMost askedFree with sign-in
Answer

How do you integrate automated tests into a CI/CD pipeline?

  1. Make the tests run from a single command (npx playwright test, pytest, mvn test). Take config from environment variables.
  2. Add a pipeline stage (GitHub Actions, GitLab CI, Jenkins). It installs dependencies and browsers, deploys or points to the test environment, and runs the suite headless.
  3. Split the...
ExperiencedMost askedScenarioFree with sign-in
Answer

A critical bug is found one day before release. What do you do?

  1. Reproduce the bug and collect evidence. Check the impact: who is affected, how often, is there a workaround, is there data loss or a security risk.
  2. Tell the product owner, dev lead and release manager right away. Do not only write it in the ticket.
  3. Show the options: fix and retest, release with a workaround...
ExperiencedMost askedFree with sign-in
Answer

What is shift-left testing and why does it matter?

Shift-left means moving testing earlier in the life cycle. Practices:

  • QA reviews requirements and acceptance criteria.
  • Test cases are written before the code is finished.
  • Developers write unit and API tests.
  • Static analysis and linting run on each commit.
  • Automated tests run in CI on every pull request.
ExperiencedMost askedScenarioFree with sign-in
Answer

How would you plan testing for a large e-commerce site?

Start with risk and scope:

  1. Analyse: key flows (browse, search, product, cart, checkout, payment, orders, returns), integrations (payment gateway, shipping, email), and expected traffic.
  2. Strategy: functional, API, compatibility (browsers, mobile), performance (sale peaks), security (auth, payments),...
ExperiencedMost askedFree with sign-in
Answer

How do you use AI tools in your testing workflow?

Use AI as an assistant, not as the final judge:

  • Draft test cases and edge cases from a requirement, then review and fix them
  • Generate test data and SQL or JSON payloads
  • Summarise logs and failures, and suggest likely root causes
  • Draft bug reports from rough notes, and help with triage and finding duplicates
  • Help write and clean up automation scripts
ExperiencedMost askedFree with sign-in
Answer

What are fixtures in Playwright and how do you use them?

Fixtures give isolated, reusable setup that tests ask for by name. Built-in ones are page, context, browser, request. You can add your own (logged-in page, API client, seeded data). They also clean up automatically.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you build a test automation framework from scratch?

Steps:

  1. Choose a stack that fits the team and the app. For example Playwright or Selenium, a test runner (Playwright Test, pytest, TestNG), reporting (Allure or HTML) and an assertion library.
  2. Structure: tests, page objects, fixtures and helpers, test data, config per environment, and utilities (API...
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you design a performance test with JMeter and which metrics do you report?

  1. Set goals and workload from real data: key transactions, user count, think time, ramp-up, duration and SLAs (for example p95 under 2 seconds).
  2. Build a test plan: Thread Group, HTTP Request samplers, config elements (headers, cookies, CSV data), timers, assertions, and correlation for dynamic tokens.
  3. Run in non-GUI mode, in an environment like production, with separate load generators.
  4. At the same time, watch server CPU, memory, database and connections.
ExperiencedMost askedScenarioFree with sign-in
Answer

What are unstable tests (tests that pass sometimes and fail other times) and how do you deal with them?

An unstable test passes and fails on the same code. Common causes: timing and hard waits, shared or leftover test data, and tests that depend on order. Others are an unstable environment, async UI, and calls to third-party services.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test when requirements are missing or unclear?

  • Ask: talk to the product owner, BA and developers. Clear up doubts and write down your assumptions
  • Learn from similar features, current behavior, competitor products and user stories
  • Use exploratory testing with charters. Test against common sense, standards and consistency
  • Draft test scenarios and share them for review, so gaps show up
  • Log questions as defects or notes against the requirement
  • Confirm your findings and update the documents afterward
ExperiencedMost askedScenarioFree with sign-in
Answer

What would you do if a developer rejects your bug saying it is not a defect?

Stay factual and keep it non-personal. Read the requirement or acceptance criteria again. Check the steps again on the latest build. Share evidence (steps, logs, video) and talk in person or on a quick call. If you still disagree, ask the product owner or BA to decide the expected behavior. If it turns out to be as designed, update the test case. Also ask whether the requirement or UX should change. The aim is the right product, not winning the argument.

ExperiencedMost askedScenarioFree with sign-in
Answer

What do you do when you cannot finish all the planned testing before the deadline?

Reprioritize by risk. Run critical-path and high-impact tests first. Drop or delay low-risk ones. Tell stakeholders early, with numbers (tests run, tests left, open defects) and the risk of what stays untested. Ask for help or more time. Automate where you can, and use exploratory sessions on high-risk areas. Write down the untested scope and get clear acceptance of the risk. Never quietly mark tests as passed.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a defect leakage and defect density?

Defect leakage is the share of defects found after release (by customers) out of all defects: leaked / (found in testing + leaked) x 100. It measures how well testing works. Defect density is defects per size unit, such as per 1,000 lines of code or per module. It shows which parts of the code have the most problems. Use leakage to judge the QA process. Use density to decide where to focus effort.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you decide whether a release is ready? What goes into QA sign-off?

Sign-off is a risk decision based on evidence, not a feeling:

  • Planned test cases are run, with the pass rate and any blocked tests explained
  • No open critical or high-severity bugs. Remaining medium and low bugs are reviewed and accepted
  • Regression and smoke suites pass on the release candidate
  • Non-functional checks are done (performance, security basics) where in scope
  • UAT is approved
  • Rollback plan and monitoring are ready
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test a third-party integration end to end (payment gateway, shipping, EDI)?

  • Read the integration contract: endpoints, message formats, auth, error codes, retry rules.
  • Use the vendor sandbox with test credentials. Mock or stub the dependency for unit and API tests, so they are fast and give the same result every time.
  • Test the happy path, declined cases and timeouts. Test duplicate...
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you use AI to triage bugs and draft bug reports?

Give the tool cleaned inputs: raw notes, error logs, stack traces and the failing test output. Ask it to do four things. (1) Draft a title, steps, expected result and actual result. (2) Group similar failures and spot likely duplicates. (3) Suggest the likely component and severity. (4) Shorten a long log to the first failing line and the probable cause.

ExperiencedMost askedFree with sign-in
Answer

How do you perform basic security testing as a QA engineer?

Do manual checks and tool-assisted checks on the OWASP Top 10 themes:

  • Authentication: weak passwords, lockout, session expiry, logout makes tokens invalid
  • Authorization: reading other users' data by changing IDs (IDOR), role escalation
  • Input handling: SQL injection and XSS payloads in fields and URLs
  • Sensitive data: HTTPS only, no secrets in URLs or logs, secure cookie flags
  • Headers and wrong settings, error messages that show stack traces
  • File upload limits
ExperiencedMost askedFree with sign-in
Answer

What is risk-based testing?

Risk-based testing sets the order of work by risk. Risk = chance of failure x business impact. Find the risks with stakeholders (complex code, new technology, past defects, money or legal exposure). Score them. Then test high-risk areas deeper and earlier, and give low-risk areas lighter coverage. It is a sensible way to test when time is short. It also makes release decisions easy to explain.

ExperiencedMost askedFree with sign-in
Answer

What are the key metrics you track in QA?

  • Test execution progress and pass, fail and blocked rates
  • Defects by severity, status, module and age; defect leakage; defect removal efficiency
  • Requirement and test coverage; automation coverage
  • Mean time to fix and retest
  • Rate of unstable tests (tests that pass sometimes and fail other times) and how long the automation suite takes
  • Reopen rate (shows the quality of fixes)
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you mentor junior testers and onboard them?

Give a clear start: a product walkthrough, access to environments, a glossary and a buddy. Begin with small, real tasks (retest bugs, run regression, write cases for a simple story). Review their work and give specific feedback. Then widen the scope to exploratory sessions and API tests. Pair with them on a first bug report and a first automation script. Share checklists and templates. Encourage questions. Hold a weekly one-to-one on growth goals. Praise good catches in public.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a test environment and production, and why should you not test in production?

A test or staging environment copies production but uses test data and can be reset. Production holds real users and real data. Testing there can damage data, send real emails or payments, and show users unstable behavior. Staging must be like production (same versions, configuration and data shape) to give results you can trust. Controlled checks in production are fine as a final safety net. Examples are smoke tests after release, canary releases and monitoring.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a test driver, stub and mock?

  • Driver: calls the code under test when the real caller does not exist yet.
  • Stub: a fake replacement for a dependency that returns fixed answers.
  • Mock: a stub that also records calls, so the test can check how it was used.
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you handle a blocker bug that stops you from testing?

A blocker stops further testing of a feature or build. For example, login is broken, so no other flow can be reached. Report it right away with high priority. Tell the developer and the lead directly. Mark dependent test cases as Blocked, not failed. Meanwhile, test other areas that are not affected. Once it is fixed, retest it and continue with the blocked cases.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you introduce and drive the adoption of AI tools in a QA team?

I would start small, measure the benefit and keep humans responsible for quality.

ExperiencedFree with sign-in
Answer

What extra testing does a mobile app need compared to a website?

A mobile app needs these extra checks:

  • Many devices and OS versions
  • Screen sizes and orientation
  • Interruptions (calls, notifications, low battery)
  • Network changes (offline, 2G, wifi to mobile data)
  • Permissions (camera, location)
  • Install, upgrade and uninstall
  • App store rules
  • Gestures
  • Background and foreground behavior
  • Battery and memory use
  • Deep links

Test Case Writing

ExperiencedMost askedScenario
Answer

Write test cases for a signup (registration) form.

Assume these fields: name, email, password, confirm password, terms checkbox.

Positive

  • Valid data creates the account and sends a verification email
  • The verification link turns the account on

Negative and validation

  • Each required field left empty
  • Wrong email formats; an email that is already registered (show a clear message, but follow the policy on not revealing which emails exist)
  • Password shorter than the minimum, or missing an uppercase letter, number or symbol that the rules need
  • Confirm password does not match
  • Terms box not ticked: submit is blocked
  • Name with digits, emoji or very long input

Boundary

  • Password at exactly the minimum length, and one less; at the maximum length, and one more
  • Name with 1 character, and with the maximum length

Other

  • Double click on Submit creates only one account
  • Expired or already used verification link
  • Password is stored as a hash (check the database) and is not in the logs

What they are checking: Field-level validation and boundary thinking

ExperiencedMost askedScenario
Answer

Write test cases for a search feature.

Positive

  • An exact keyword returns the right results; a partial keyword works (if the product supports it)
  • Search is not case-sensitive; multiple words work; the best matches come first
  • Result count and pagination are correct; clicking a result opens the right item
  • Suggestions (autocomplete) show while typing

Negative

  • Empty search or only spaces: show a message or do nothing
  • No match: show a friendly "no results" page with suggestions
  • Special characters, quotes, %, <script>, SQL pieces: no error and no injection
  • Very long text (1,000 characters)

Other

  • Filters and sorting work together with search; the URL can be shared
  • Search with a typo or accented letters
  • Performance: results come in under 2 seconds for a large catalog
  • Recent searches, a clear button, and the "Search" key on a mobile keyboard

What they are checking: Covers both normal use and hard cases

ExperiencedMost askedScenario
Answer

Write test cases for a shopping cart.

  • Add one item; adding the same item again raises the quantity (or adds a second line, as the spec says)
  • Change the quantity: 1, the maximum allowed, 0 (removes the item), negative, decimal, not a number
  • Remove an item; an empty cart shows a message and checkout is disabled
  • Price math: line total, subtotal, tax, shipping and discount, rounded to 2 decimals
  • Item goes out of stock or stock drops after adding: show a warning at the cart or checkout
  • Price changed since the item was added: the cart shows the latest price
  • The cart stays after a refresh, after logout and login, and across devices for logged-in users
  • A guest cart joins the account cart after login
  • Apply a valid, expired and invalid coupon; a coupon used with sale items
  • Update the cart in two tabs at the same time
  • Mobile layout and quantity buttons

What they are checking: Thinking about business rules and calculations

ExperiencedMost askedScenario
Answer

Write test cases for the checkout flow of an online store.

Flow: cart -> address -> shipping -> payment -> review -> confirmation.

  • Happy path as a guest and as a logged-in user; order number and confirmation email
  • Address checks: required fields, postcode format, saved addresses, different billing and shipping address
  • Shipping options change the total and the delivery estimate
  • The order summary matches the cart (items, tax, discount, shipping)
  • Payment methods: card, wallet, cash on delivery
  • Back button or refresh in the middle of checkout keeps the data and does not create a second order
  • Double click on "Place order" creates one order
  • Stock drops to zero during checkout: show a clear error and do not charge
  • Session expires on the payment page
  • The order shows in "My orders", stock goes down, and the invoice is correct
  • Failure paths: payment declined, gateway timeout, email service down

What they are checking: The full flow from start to end, with failures handled

ExperiencedMost askedScenario
Answer

Write test cases for a payment page (card payment).

Positive

  • Valid card, expiry and CVV: payment succeeds, and the receipt and status update
  • Different card types (Visa, Mastercard) are found from the number

Negative

  • Wrong card number (fails the Luhn check), expired card, wrong CVV length, past expiry date
  • Not enough money, card declined, 3-D Secure failed or cancelled
  • Empty fields, letters in number fields

Edge

  • Gateway timeout: the user is not charged twice, and the order stays "pending" until it is checked against the bank record
  • Double click or refresh after submit: the request is idempotent (running it twice gives the same result), so there is one charge
  • Amount and currency sent to the gateway match the order
  • Browser Back after success does not send the payment again

Security

  • Card details are not logged or stored, the page uses HTTPS, the CVV is hidden
  • Changing the amount in the request is rejected on the server

What they are checking: Handling money safely, idempotency and security

ExperiencedMost askedScenario
Answer

Write test cases for a file upload feature.

Positive

  • Upload allowed types (jpg, png, pdf) within the size limit; preview and download work
  • Many files, drag and drop, replace a file and delete a file

Negative

  • Types that are not allowed, a renamed extension (.exe renamed to .jpg), a file with zero bytes
  • A file 1 byte over the limit, and a file exactly at the limit
  • A very long file name or one with special characters; the same name twice
  • Cancel the upload half way, network drops, resume or retry

Security

  • Files with harmful content, a script inside an SVG, path traversal in the file name (../../x): all rejected
  • File links cannot be guessed; downloads need permission

Other

  • Progress bar and error messages
  • Upload on a slow network; upload from a mobile camera; a large file does not freeze the screen

What they are checking: Limits, checks and security of uploads

ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for OTP verification.

  • Positive: the correct OTP within its valid time (for example 5 minutes) completes the login
  • Wrong OTP: an error shows, attempts are counted, and the user is locked out after the limit (say 3 or 5)
  • Expired OTP: rejected, with a "Resend" option
  • Resend: the new OTP makes the old one invalid; the...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a fund transfer in a banking app.

Positive

  • Valid receiver and an amount within the balance: debit and credit happen once, with a reference number and an SMS or email confirmation
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test a form with 20 fields without writing hundreds of test cases?

Use test design techniques to cut the number of tests:

  • Equivalence partitioning and BVA (boundary value analysis) for each field: one valid group, invalid groups, and the boundaries.
  • Group fields by type: use one reusable checklist for all text fields, all number fields, all date fields.
  • **Decision...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a search filter and sort on a product listing page.

  • Each filter alone (category, brand, price range, rating) shows only matching products and the right count
  • Different filters combine with AND; values in the same group (two brands) combine with OR
  • Price range: min greater than max, min equal to max, negative, empty, not a number
  • Clear filters resets the list;...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a coupon or promo code feature.

  • A valid code lowers the total correctly (percentage and fixed amount), rounded to 2 decimals
  • Wrong code, expired, not active yet, already used, wrong letter case, spaces around the code
  • Minimum cart value, only some categories or products, sale items left out
  • One use per user vs unlimited use; total usage...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a ticket booking system (movie or bus).

  • Search by date or route, choose seats, pay, and get a ticket with a unique ID or QR code
  • Seat map: booked seats cannot be chosen; a maximum number of seats per booking; select and unselect
  • Two users choose the same seat at the same time: one succeeds and the other sees a clear message
  • A seat hold timer (for...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a chat or messaging application.

  • Send and receive text in real time; delivery ticks (sent, delivered, read)
  • An empty message is blocked; a very long message; emoji, links, code, text in many languages
  • Media: image, file, voice; size limits; preview and download
  • Group chat: add or remove members, admin rights, messages seen only by members -...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a ride-booking app (like a taxi app).

  • Set pickup and drop; fare estimate; choose a vehicle type; a driver is assigned with a live arrival time
  • Invalid location, same pickup and drop, location not available, outside the service area
  • GPS permission denied; poor accuracy; the map and driver position update
  • Cancel before and after a driver is...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a REST login endpoint (POST /login).

  • 200 and a token for valid credentials; the response has no password hash
  • 400 for missing or bad JSON or empty fields; 401 for a wrong password or unknown user, with the same message
  • 415 or 400 for the wrong content type; extra or unexpected fields are ignored
  • Token expiry, format and claims are correct; the...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a user role and permission system (admin, editor, viewer).

Build a table of roles and actions, and test each cell.

  • Admin: create, edit and delete users, change settings. Editor: edit content but cannot manage users. Viewer: read only
  • A direct URL or API call to a forbidden action returns 403, even if the button is hidden in the UI
  • A role change works without a new login...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a download statement (PDF or CSV export) feature.

  • Download for a chosen date range; the file opens correctly; the file name has the date range
  • Contents match the screen and the database: totals, dates, currency format, order
  • An empty range gives a file with only a header, or a message
  • A very large range (100,000 rows): it finishes, or runs as a background job...
ExperiencedMost askedScenarioFree with sign-in
Answer

Write test cases for a notification feature (push, email, in-app).

  • An event triggers the notification once, with the right content, link, time and user
  • Channels: push, email, SMS, in-app badge; each follows user preferences and opt-out
  • Read and unread state, mark all as read, the badge count is right
  • An offline device gets it later; old notifications are dropped
  • Repeated...
ExperiencedScenarioFree with sign-in
Answer

Write test cases for a QR code scanner or QR-based payment.

  • Scan a valid code: the right merchant and amount show, and payment is confirmed
  • Invalid, damaged, blurred, expired, or non-payment QR: show a clear message
  • Low light, angle, distance; flashlight button; scan from a gallery image
  • Camera permission denied or blocked: guide the user to settings
  • Static QR with...

API Testing

ExperiencedMost askedFree with sign-in
Answer

What are the types of API authentication you have tested?

  • Basic auth: base64 username:password in the header. Use it only over HTTPS.
  • API key: a header or query parameter that identifies the client app
  • Bearer / JWT: a signed token in Authorization: Bearer <token>. The server keeps no session (stateless).
  • OAuth 2.0: access for another app using access and refresh tokens (authorization code and client credentials flows)
  • Session cookies: a session ID kept on the server
  • mTLS / HMAC signing: used between services
ExperiencedMost askedScenarioFree with sign-in
Answer

What negative tests would you write for a POST /users endpoint?

  • Missing required fields, one at a time, and an empty body
  • Wrong types (age as a string, email as a number) and nulls
  • Invalid formats (bad email, bad date), very long strings, limit values
  • Duplicate unique value (email already exists): 409
  • Broken JSON, wrong Content-Type (415), unsupported method (405) -...
ExperiencedMost askedFree with sign-in
Answer

How do you automate API tests with REST Assured?

REST Assured is a Java library with a Given-When-Then style. It is usually used with JUnit or TestNG.

ExperiencedMost askedFree with sign-in
Answer

How do you automate API tests with Python requests and pytest?

import requests, pytest

BASE = "https://api.example.com"

@pytest.fixture(scope="session")
def headers():
    r = requests.post(f"{BASE}/login", json={"email": "[email protected]", "password": "secret"}, timeout=10)
    assert r.status_code == 200
    return {"Authorization": f"Bearer {r.json()['token']}"}

def...
ExperiencedMost askedScenarioFree with sign-in
Answer

An API works in Postman but fails from the front end. How do you investigate?

  1. Open the browser dev tools and the Network tab. Compare the failing request with the Postman one (URL, method, headers, body, cookies).
  2. Check the Console for CORS errors. Look at the preflight OPTIONS response.
  3. Look for a missing or different Authorization, Content-Type, or cookie setting (SameSite,...
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you validate API data against the database?

Call the API, then query the database for the same record and compare field by field (grey box testing).

ExperiencedMost askedFree with sign-in
Answer

What is Newman and how do you use it in CI?

Newman is the command line runner for Postman collections. It runs API tests without the GUI, for example in Jenkins or GitHub Actions.

ExperiencedMost askedFree with sign-in
Answer

What is a JWT and what would you test about it?

A JSON Web Token has three base64url parts: header, payload (claims such as sub, exp, role) and signature. The server checks the signature, so it can trust the payload without a database lookup. The payload is encoded, not encrypted.

ExperiencedMost askedFree with sign-in
Answer

How do you validate a JSON response schema?

Define the contract (types, required fields, formats, allowed values) and check every response against it. This catches missing fields and type changes that value checks miss.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test rate limiting in an API?

Find the documented limit (for example 100 requests per minute per key). Then:

  1. Send requests in a loop until you pass the limit. Confirm 429 Too Many Requests.
  2. Check the response headers: Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset.
  3. Wait for the time window to end and...
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test an API when the backend is not ready?

Use the API contract (OpenAPI/Swagger) and a mock server. Postman mock servers, WireMock, Mockoon or json-server return example responses. Testers can then write requests, checks and schema tests. Frontend developers can also work at the same time. Design test cases from the contract, including error responses. When the real service is ready, point the same collection at it by changing the baseUrl environment variable. Then fix any differences between the mock and the real behavior.

ExperiencedMost askedFree with sign-in
Answer

What does idempotency mean and how do you test it?

An operation is idempotent when repeating the same request gives the same final state as running it once. GET, PUT and DELETE are idempotent. POST usually is not.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test an API for security vulnerabilities?

Cover the themes of the OWASP API Security Top 10:

  • Broken object-level authorization (IDOR): change IDs in the path or body to read another user's data
  • Broken authentication: weak tokens, no lockout, token reuse after logout
  • Too much data in responses: password hashes or internal fields appear in the...
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you measure and test API performance?

Measure response time (average and percentiles p90/p95/p99), throughput, error rate and resource use. Tools: JMeter, k6, Gatling, and Postman monitors for simple checks.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you debug a failing API test in CI that passes locally?

First compare the environments: base URL, versions, config and secrets. Then check the test data. Was it already created? Do tests depend on each other or on order? Do parallel runs share data?

ExperiencedMost askedFree with sign-in
Answer

How do you test pagination, filtering and sorting in an API?

  • Default page size and a custom limit/page. Also try limit=0, a negative value, and a value above the maximum.
  • First, middle and last page. A page after the last returns an empty list or 404, as the spec says.
  • Total count and links (next, prev) are correct. No rows repeat or go missing across pages when...
ExperiencedMost askedFree with sign-in
Answer

What is the difference between synchronous and asynchronous APIs, and how do you test an async one?

A synchronous API returns the final result in the same response. An asynchronous API accepts the job and returns quickly. It often sends 202 Accepted with a job ID or status URL. The result comes later through polling or a webhook (callback).

ExperiencedMost askedFree with sign-in
Answer

How do you parametrize API negative tests in pytest?

Use pytest.mark.parametrize to run one test body against a table of invalid inputs and expected codes.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between 400 and 422?

400 Bad Request means the server cannot understand the request. Examples are broken JSON, wrong syntax or a missing parameter. 422 Unprocessable Entity means the request is well formed but fails validation or business rules. Examples are an invalid email value or an age below the minimum. Many APIs use 400 for both. The key is to follow the API's documentation in the same way every time. Also return a structured error body (field, message, code).

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you test a file upload API?

  • Upload allowed types with multipart/form-data: expect 201, and the stored file can be fetched
  • Wrong type, fake extension, empty file, file over the size limit (and exactly at the limit)
  • Missing file part, wrong field name, many files
  • Auth is required, and a user cannot read other users' files
  • File name...
ExperiencedMost askedFree with sign-in
Answer

What is CORS and how does it affect API testing?

CORS (Cross-Origin Resource Sharing) is a browser rule. A web page from origin A can call an API on origin B only if the API allows it with headers such as Access-Control-Allow-Origin. For non-simple requests, the browser first sends a preflight OPTIONS request.

ExperiencedMost askedFree with sign-in
Answer

How do you handle dynamic values such as tokens, timestamps and IDs in API assertions?

Do not check values that change. Check the type, the format or the link between values. Take IDs from the response that created them and reuse them. For timestamps, check a regex or check that the value is close to now:

ExperiencedMost askedFree with sign-in
Answer

What is API versioning and what would you test?

Versioning lets an API change without breaking existing clients. The version can be in the URL (/v1/users), a header or the media type. What to test:

  • Each supported version returns its documented contract.
  • Old clients keep working after a new release (backward compatibility, regression).
  • Old versions return deprecation headers and end dates.
  • New fields do not break old clients.
  • Unknown versions return a clear error.
ExperiencedMost askedFree with sign-in
Answer

What is contract testing and how is it different from integration testing?

Contract testing checks that a service provider and its consumers agree on the request and response format. Both do not need to run together. Tools like Pact record what the consumer expects. They then check the provider against it in CI. Integration tests run the real services together. They are slower and fail for many unrelated reasons. Contract tests catch breaking API changes early and cheaply. They work well with a few end-to-end tests.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you test a webhook?

A webhook is an HTTP callback. The system sends it to your URL when an event happens.

  • Set up a receiver (webhook.site, a local server with a tunnel, or a mock) and trigger the event.
  • Check the payload fields, the headers, and the signature (HMAC). The receiver uses the signature to trust the sender.
  • The receiver...
ExperiencedMost askedScenarioFree with sign-in
Answer

Explain how you would test an API that depends on another service.

Use mocks to test your own logic in a fast and reliable way. Mock these cases: a normal response, a slow response, error codes (4xx/5xx), a broken body, a timeout, and a partial outage. Add a small set of integration tests against the real sandbox to confirm the contract.

Selenium

ExperiencedMost askedScenario
Answer

Your Selenium tests are unstable (they pass sometimes and fail other times). How do you investigate and fix them?

I would treat unstable tests as a defect, not as noise. First I find the category.

  1. Collect evidence: rerun the failing test 20 times. Capture screenshots, page source, browser console and network logs. Note the pass rate for each environment.
  2. Find the cause:
    • Timing: missing waits, animations, async rendering. Fix with explicit conditions, not sleeps.
    • Test data: shared accounts, order dependence, leftover state. Create data for each test and clean it up.
    • Locators: unstable ids, stale elements.
    • Environment: slow CI, shared test server, third-party calls. Mock external services.
    • A real race condition in the product. Report it as a bug.
  3. Fix the root cause. Then put any still-unstable test in quarantine with a tag so it stops blocking the pipeline. Keep a list of quarantined tests.
  4. Prevent it: run new tests many times before merging. Track the failure rate on a dashboard.

Automatic retries only hide the problem. I allow one retry at most while the root cause is being fixed.

What they are checking: Whether you have a clear method and do not hide unstable tests with retries

ExperiencedMost askedScenarioFree with sign-in
Answer

Tests pass on your machine but fail in CI. How do you find the cause?

I compare the two environments and make the CI failure easy to see.

ExperiencedMost askedFree with sign-in
Answer

What is the Actions class and when do you use it?

Actions builds complex user actions: hover, drag and drop, right click, double click, key combinations and click-and-hold.

ExperiencedMost askedFree with sign-in
Answer

How do you use pytest with Selenium, and what are fixtures?

A pytest fixture creates and cleans up a resource such as the driver. Tests ask for it by argument name.

ExperiencedMost askedFree with sign-in
Answer

What is JavascriptExecutor and when would you use it?

JavascriptExecutor runs JavaScript in the page. Use it when WebDriver commands are not enough:

  • Scroll: driver.execute_script("arguments[0].scrollIntoView(true);", el).
  • Click an element that WebDriver says is blocked (last resort, because it skips real user behaviour).
  • Read values that the DOM gives only through JS, or set a value on a read-only date input.
  • Get page state, for example return document.readyState.
ExperiencedMost askedFree with sign-in
Answer

Explain the architecture of Selenium Grid 4.

Grid 4 lets you run tests on many machines and browsers at the same time. It has three modes: Standalone (one process), Hub and Node, and fully distributed.

ExperiencedMost askedFree with sign-in
Answer

How do you run Selenium tests in parallel?

Two things are needed: a runner that runs tests in parallel, and safe driver handling for each thread.

ExperiencedMost askedScenarioFree with sign-in
Answer

A click fails with ElementClickInterceptedException. What do you do?

It means another element covers the target at the click point. Examples are a cookie banner, spinner, sticky header or modal.

ExperiencedMost askedScenarioFree with sign-in
Answer

What causes ElementNotInteractableException and how do you resolve it?

The element is in the DOM but cannot take the action. It may be hidden, zero size, disabled, off-screen, or not yet drawn.

ExperiencedMost askedFree with sign-in
Answer

How do you implement data-driven testing in Selenium?

Keep the test logic apart from the test data. Run the same test with many rows of data.

ExperiencedMost askedFree with sign-in
Answer

How do you run Selenium tests in a CI/CD pipeline?

Run them headless in a clean environment that you can repeat, on each pull request or merge.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your Selenium regression suite takes three hours. How would you cut the time?

I would measure first. Then I would fix the biggest costs.

ExperiencedMost askedFree with sign-in
Answer

How do you make the WebDriver instance thread-safe in parallel tests?

A WebDriver instance is not thread-safe, so each thread needs its own.

In Java, use a ThreadLocal:

ExperiencedMost askedScenarioFree with sign-in
Answer

After clicking Save, your assertion on the success message fails intermittently. How do you fix it?

The assertion runs before the page finishes updating. So the test races the application.

ExperiencedMost askedFree with sign-in
Answer

How do you run Selenium tests in headless mode?

Pass a headless flag through the browser options.

ExperiencedMost askedFree with sign-in
Answer

How do you capture a screenshot when a test fails?

Use get_screenshot_as_file (or TakesScreenshot in Java) in a failure hook.

In pytest, a hook in conftest.py can attach it:

ExperiencedMost askedFree with sign-in
Answer

How do you handle file upload and download in Selenium?

Upload: if there is an <input type='file'>, send the absolute path with send_keys. You do not need to use any dialog.

ExperiencedMost askedFree with sign-in
Answer

How do you handle elements inside a Shadow DOM?

Selenium 4 supports shadow roots directly. Find the host element, get its shadow root, then search inside it.

ExperiencedMost askedFree with sign-in
Answer

How do you approach cross-browser testing with Selenium?

Make the browser a setting in the driver factory. Run the same suite on each browser.

ExperiencedMost askedFree with sign-in
Answer

What is Selenium Manager and how did driver management change?

Before Selenium 4.6, you downloaded chromedriver by hand or used a library like WebDriverManager. The driver version had to match the installed browser.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you handle CAPTCHA, OTP and two-factor authentication in automated tests?

You do not automate the CAPTCHA itself. You remove it from the test path.

ExperiencedMost askedFree with sign-in
Answer

What are relative locators in Selenium 4?

Relative locators find elements by their position next to another element. They use with_tag_name and above, below, to_left_of, to_right_of, near.

ExperiencedMost askedFree with sign-in
Answer

How can you use Chrome DevTools Protocol in Selenium 4?

Selenium 4 gives access to the DevTools Protocol for Chromium browsers (Chrome, Edge). It lets you do things WebDriver cannot:

  • Intercept and mock network requests, or block resources.
  • Capture console logs and JavaScript errors.
  • Copy device sizes, geolocation and slow networks.
  • Collect performance numbers.
ExperiencedMost askedScenarioFree with sign-in
Answer

When would you recommend moving from Selenium to Playwright, and how would you migrate?

I would recommend it when the team has unstable tests (tests that pass sometimes and fail other times) and slow suites on modern JavaScript apps. It also fits when the team needs built-in tracing, network mocking, and fast parallel runs, and is happy with Chromium, Firefox and WebKit only.

Playwright

ExperiencedMost askedScenario
Answer

How do you reuse login state across tests with storageState?

Log in once, save the cookies and storage to a file, and load that file in every test context. This removes the login screen from most tests and saves minutes.

// auth.setup.ts
import { test as setup, expect } from '@playwright/test';
setup('authenticate', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.USER_EMAIL!);
  await page.getByLabel('Password').fill(process.env.USER_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL(/dashboard/);
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

In playwright.config.ts, define a setup project. Make the browser projects depend on it with use: { storageState: 'playwright/.auth/user.json' }. Add the .auth folder to .gitignore. For different roles, save one file per role. Keep one separate test that uses the real login form.

What they are checking: Whether you can speed up a suite by reusing login

ExperiencedMost asked
Answer

How do you do API testing with Playwright?

Use the request fixture (APIRequestContext). It sends HTTP calls with no browser.

import { test, expect } from '@playwright/test';

test('create and fetch a post', async ({ request }) => {
  const created = await request.post('https://jsonplaceholder.typicode.com/posts', {
    data: { title: 'hello', body: 'world', userId: 1 },
  });
  expect(created.status()).toBe(201);
  const body = await created.json();
  expect(body.title).toBe('hello');

  const res = await request.get('https://jsonplaceholder.typicode.com/posts/1');
  await expect(res).toBeOK();
  expect((await res.json()).id).toBe(1);
});

Set baseURL and extraHTTPHeaders (for auth tokens) in the config. A good pattern is to prepare data through the API and check the result in the UI. You can also check status codes, schema, headers and error cases (401, 404, 422).

What they are checking: Whether you can mix API checks with UI work

ExperiencedMost asked
Answer

How do you integrate Playwright tests with GitHub Actions?

name: e2e
on: [pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22, cache: npm }
      - run: npm ci
      - run: npx playwright install --with-deps
      - run: npx playwright test
        env:
          BASE_URL: ${{ secrets.STAGING_URL }}
      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 14

Tips: set retries: 1 and trace: 'on-first-retry' on CI. Use forbidOnly: !!process.env.CI. Cache the browsers. Use a matrix to shard the tests for speed. Keep secrets in repository secrets.

What they are checking: Whether you can run tests in CI from start to finish

ExperiencedMost askedScenarioFree with sign-in
Answer

Your Playwright tests are unstable on CI (they pass sometimes and fail other times). How do you handle it?

Find the cause before you add retries.

ExperiencedMost askedFree with sign-in
Answer

How do you mock network requests in Playwright?

Use page.route to catch a request. Then you can answer it, change it or block it.

ExperiencedMost askedFree with sign-in
Answer

What is the Playwright Trace Viewer and how do you use it?

A trace is a recording of a test run. It holds DOM snapshots before and after each action, a timeline, network calls, console logs, source code and screenshots. You open it with npx playwright show-trace trace.zip or from the HTML report.

ExperiencedMost askedFree with sign-in
Answer

How does parallel execution work in Playwright?

Test files run in parallel across workers. Each worker is a separate process with its own browser. Tests inside one file run in order in the same worker, unless you set fullyParallel: true.

ExperiencedMost askedFree with sign-in
Answer

What are project dependencies and global setup in Playwright?

Both run work before the tests, such as adding data or logging in.

ExperiencedMost askedScenarioFree with sign-in
Answer

A Playwright test fails locally and you do not know why. How do you debug it?

Start with simple tools and move to detailed ones.

ExperiencedMost askedScenarioFree with sign-in
Answer

You get a strict mode violation error. What does it mean and how do you fix it?

The locator matched more than one element. For actions like click or fill, Playwright will not guess which one you mean.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you combine API calls and UI actions in one test?

Use the API for setup and checking. Use the UI only for what you are testing. This makes tests faster and less fragile.

ExperiencedMost askedScenarioFree with sign-in
Answer

A third-party service (payment or maps) is slow and breaks your tests. How do you handle it?

Keep the test apart from that dependency.

ExperiencedMost askedFree with sign-in
Answer

How would you design a scalable Playwright framework structure?

A practical layout:

ExperiencedMost askedFree with sign-in
Answer

How do you handle iframes and Shadow DOM in Playwright?

Iframes: use page.frameLocator.

ExperiencedMost askedFree with sign-in
Answer

What are soft assertions and expect.poll or toPass in Playwright?

  • Soft assertions (expect.soft(...)) record a failure but let the test go on. So you see all failures in one run. The test still fails at the end. They are good for checking many fields on a page.
  • expect.poll retries a function that returns a value until the assertion passes. It is useful for data that...
ExperiencedMost askedFree with sign-in
Answer

How do you do visual comparison testing in Playwright?

Use await expect(page).toHaveScreenshot('home.png'), or call it on a locator. The first run saves a baseline image. Later runs compare pixels and fail if the difference is above a limit (maxDiffPixelRatio). Update baselines with --update-snapshots.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a Locator and an ElementHandle?

A Locator is a lazy description of how to find an element. It looks in the DOM again on every action and waits automatically. So it still works after the page re-renders. An ElementHandle is a live link to one specific DOM node. It can go stale, and it does not wait in the same way.

ExperiencedMost askedScenarioFree with sign-in
Answer

When would you use getByTestId instead of getByRole?

Use getByRole and getByLabel first. They test what users and assistive tools (like screen readers) see, and they also catch accessibility problems. Use getByTestId when:

  • The element has no accessible role or name (a canvas, a chart, an icon button that cannot be named).
  • The text changes with language or A/B experiments.
  • Many identical elements need a stable handle.
ExperiencedMost askedFree with sign-in
Answer

How do you test a dynamic table, such as filtering and sorting rows?

Chain locators and use filter. Use count assertions, because they retry.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you migrate a Cypress or Selenium suite to Playwright?

Move step by step. Do not rewrite everything at once.

ExperiencedMost askedFree with sign-in
Answer

How do you run accessibility checks with Playwright?

Use the @axe-core/playwright package to scan a page for WCAG (web accessibility rules) violations.

ExperiencedMost askedFree with sign-in
Answer

How do you shard Playwright tests across multiple CI machines?

Split the suite with --shard=x/y. Run each shard as a matrix job, then merge the reports.

ExperiencedMost askedFree with sign-in
Answer

How would you test a multi-user feature such as chat in Playwright?

Create two independent browser contexts in one test. Log each one in as a different user.

Automation Framework

ExperiencedMost askedScenario
Answer

How would you design a test automation framework from scratch?

I would start from goals, not tools.

  1. Clarify scope: app type (web, API, mobile), team skills, release speed, environments, and what must run on each pull request.
  2. Choose a stack that fits the team. For example, Playwright with TypeScript, or Selenium with Java and TestNG. Add a runner and an assertion library.
  3. Define layers: tests, page objects or API clients, shared helpers, config, and test data factories.
  4. Build in common needs from day one. These are environment config, secrets handling, logging and a retry policy. Add reporting (Allure or HTML), screenshots and traces on failure, and tags for smoke and regression.
  5. Set up CI with a fast smoke suite on each PR and a nightly regression. Run them in parallel in containers.
  6. Write coding rules. Review tests like production code. Document how to add a test.
  7. Start with a small suite of high-value tests. Prove it is stable, then grow it.

Success means people trust the results: few unstable tests (tests that pass sometimes and fail other times), quick feedback and low maintenance cost.

What they are checking: Whether you design for easy maintenance and team use

ExperiencedMost asked
Answer

How do you integrate automated tests into a CI/CD pipeline?

Run the tests automatically at the right stage, and give fast feedback.

  • Trigger: on pull request (smoke, API and key UI tests). Also on merge or on a schedule (full regression).
  • Stages: build, unit tests, deploy to a test environment, API tests, UI tests, report.
  • Run headless in containers, in parallel, with the same image every time.
  • Make the quality gate real. The pipeline fails when a test fails or coverage drops. A failed run blocks the merge.
  • Publish reports, screenshots and traces. Tell the team.
  • Keep secrets in the CI secret store. Manage test data with setup steps or API seeding.

Keep the PR suite under about 10 minutes. If it is slower, developers will find ways to skip it.

What they are checking: Whether you know pipeline stages, gates and speed

ExperiencedMost asked
Answer

How do you manage test data in automation?

Tests must create or control their own data. Then they can run in parallel and in any order.

  • Prefer to create data for each test through APIs, factories or database seeds. Use unique values (timestamps or UUIDs).
  • Clean up afterwards. Or use disposable environments and database snapshots.
  • Keep fixed reference data in JSON or CSV files under version control.
  • Never use real personal data from production. Use masked or made-up data.
  • Keep data separate for each environment. Keep credentials in a secret store.
  • Avoid tests that depend on data left behind by another test.

After timing problems, bad data management is the second biggest cause of unstable tests (tests that pass sometimes and fail other times).

What they are checking: Whether you can keep tests independent

ExperiencedMost askedScenario
Answer

How do you deal with unstable tests (tests that pass sometimes and fail other times) in an automation suite?

I measure, find the cause, fix and prevent.

  1. Measure: track how often each test fails and passes from CI history. Mark the unstable tests. Do not guess.
  2. Find the root cause. It may be timing and waiting problems, shared or old data, or tests that depend on order. It may be an unstable environment or third-party services. It may also be a real product bug that appears only sometimes.
  3. Fix the cause: waits based on conditions, unique data per test, mocks for unstable services, stable locators, and isolation.
  4. Quarantine (set aside) tests that cannot be fixed quickly, so the pipeline stays trusted. Give each one an owner and a deadline.
  5. Prevent: review new tests. Run them many times (for example 20) before merging. Allow at most one retry.

If the team ignores unstable tests, people learn to ignore red builds.

What they are checking: Whether you treat unstable tests as an engineering problem

ExperiencedMost asked
Answer

How do you use AI tools in your QA workflow?

I use AI as an assistant that I check. I do not treat it as an authority.

  • Test design: ask it for edge cases, equivalence classes and negative scenarios from a requirement. Then I remove weak ideas and verify the rest.
  • Test code: create the first version of page objects, data builders and repeated setup code. Ask it to explain failing stack traces.
  • Test data: make realistic made-up datasets (never real customer data).
  • Bug reports: turn rough notes into clear steps, expected result and actual result.
  • Triage: summarise logs and group similar failures.

Safety rules: do not paste secrets or private data into outside tools. Always run and review generated code. Check every claim against the real application. AI makes drafts faster, but the tester still judges the risk.

What they are checking: Whether you use AI in a practical and safe way

ExperiencedMost askedScenarioFree with sign-in
Answer

Tell me about a project you led and your responsibilities.

Use a clear structure: context, your role, actions, result.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you plan testing for a large e-commerce website?

I would use a risk-based plan, ordered by business impact.

ExperiencedMost askedFree with sign-in
Answer

Show a basic CI pipeline for running automated tests in GitHub Actions and Jenkins.

GitHub Actions:

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you use AI to triage bugs and draft bug reports?

I would use AI to reduce routine work. A person confirms the decisions.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you mentor and onboard junior testers?

I give structure, early wins and feedback.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you decide on release sign-off?

Sign-off is a risk decision based on evidence. The team agrees the exit criteria (the conditions to release) in advance.

ExperiencedMost askedFree with sign-in
Answer

How do you test the database layer?

Test data integrity, structure and behaviour.

ExperiencedMost askedFree with sign-in
Answer

What is shift-left testing?

Shift-left means testing earlier in the lifecycle. Then bugs are found when they are cheap to fix.

ExperiencedMost askedFree with sign-in
Answer

What QA metrics do you track and which are misleading?

Useful metrics:

  • Defect leakage (bugs found in production divided by all bugs).
  • Defect detection percentage, and the time to find and fix bugs.
  • Automation pass rate, rate of unstable tests, and suite run time.
  • Requirement or risk coverage.
  • Mean time to restore test environments.
ExperiencedMost askedScenarioFree with sign-in
Answer

The UI changes often and your automation keeps breaking. What do you do?

Reduce how much the tests depend on UI details.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your regression suite fails on every build and the team stops trusting it. What do you do?

Win back trust first, then improve.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you decide what to test when time before release is short?

Use risk-based priorities.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you test a third-party integration end to end?

I would test at several levels, because I do not control the other system.

ExperiencedMost askedFree with sign-in
Answer

How do you test for security as a QA engineer?

I cover the common risks and work with security specialists for deeper checks.

ExperiencedMost askedFree with sign-in
Answer

What is contract testing and when is it useful?

Contract testing checks that a service consumer and a provider agree on the shape of requests and responses. You do not need to run both together. With Pact, the consumer writes its expectations, and these create a contract. The provider checks the contract in its own pipeline.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you choose between tools, for example Selenium, Playwright or Cypress, for a new project?

I decide using criteria, then I run a short proof of concept.

Criteria: app type and browser needs, team language skills, stability and speed, parallel runs and CI fit, and debugging tools. Also community and long-term support, cost, and fit with existing reporting.

ExperiencedMost askedFree with sign-in
Answer

How do you review test code and keep coding standards in a QA team?

Treat test code like production code.

ExperiencedMost askedFree with sign-in
Answer

What is a test environment strategy and what problems does it solve?

It defines which environments exist, what each one is for, and how to keep them reliable. A typical set: local, short-lived CI environments, shared test/QA, staging (like production), and production monitoring.

Cypress

ExperiencedMost askedScenario
Answer

Compare Cypress, Selenium and Playwright. Which would you pick for a new web project and why?

There is no single best tool. Pick by your constraints.

  • Selenium: the widest language and browser support (including real Safari and old browsers). It has a huge ecosystem. But you build the waits, runner, reporting and parallel runs yourself.
  • Cypress: the best developer experience for front-end teams. It has time-travel debugging, automatic retries and built-in network stubbing. Limits: JavaScript/TypeScript only, one tab per test, cross-origin needs cy.origin, and parallel runs are easiest with Cypress Cloud.
  • Playwright: many languages (JS/TS, Python, Java, .NET). It supports Chromium, Firefox and WebKit, multiple tabs and contexts, built-in parallel runs and tracing, and free sharding (splitting tests across machines).

For a new JS/TS web project I would pick Playwright and Cypress as the two finalists. Then I would run a one-week trial on the three hardest flows (login with SSO, file upload, multi-tab). If the app needs multi-tab or multi-user flows, or testers who do not write JS, Playwright wins. If the team is front-end heavy and likes component testing and the interactive runner, Cypress is a good fit.

What they are checking: Decisions based on trade-offs and a test plan, not loyalty to one tool

ExperiencedMost asked
Answer

What is retry-ability in Cypress, and which commands retry?

Retry-ability means Cypress keeps re-running a query and the assertions after it. It stops when they pass or when the command timeout (4 seconds by default) ends.

  • Retried: queries such as get, find, contains, its, invoke (read-only), eq, filter, and the assertions chained after them (.should, .and).
  • Not retried: actions such as click, type, check, select, and .then() callbacks. Actions do wait until the element is ready (visible, not covered, not disabled, not moving) but they run once.
// Retries the whole chain until the list has 3 items
cy.get('.todo').should('have.length', 3);
// Anti-pattern: assertion inside .then does not retry
cy.get('.todo').then(($els) => expect($els.length).to.eq(3));

Since Cypress 12, the whole chain of queries before the assertion is run again. This fixes stale-element problems. A good rule: put what you wait for in a .should. Do not use .then. Do not use a fixed cy.wait(2000).

What they are checking: Whether you know why Cypress tests are stable and what breaks that

ExperiencedMost asked
Answer

How do you stub or spy on network calls with `cy.intercept()`?

cy.intercept(method, url, response?) matches requests at the proxy. With no response, it only watches (spy). With a fixed response or a handler, it replaces the real reply (stub).

// Spy and wait
cy.intercept('GET', '/api/orders*').as('orders');
cy.visit('/orders');
cy.wait('@orders').its('response.statusCode').should('eq', 200);

// Stub with a fixture
cy.intercept('GET', '/api/orders*', { fixture: 'orders.json' });

// Force an error to test the UI
cy.intercept('POST', '/api/orders', { statusCode: 500, body: { message: 'Server error' } });

// Modify the real response
cy.intercept('GET', '/api/user', (req) => {
  req.continue((res) => { res.body.plan = 'pro'; });
});

Register the intercept before the action that triggers it. Use stubs for error, empty, slow (delay) and rare states that are hard to get with real data. Keep a few tests without stubs to prove the real systems work together.

What they are checking: A core Cypress strength: control of network state

ExperiencedMost askedScenario
Answer

Why is `cy.wait('@alias')` better than `cy.wait(5000)`? A test fails at random on a slow data table. How do you fix it?

A fixed cy.wait(5000) is a guess. It is too short on a slow day and wastes time on a fast day. cy.wait('@alias') waits exactly until one request finishes, then goes on at once.

Fix for the unstable table test (it passes sometimes and fails other times):

cy.intercept('GET', '/api/customers?*').as('getCustomers');
cy.visit('/customers');
cy.wait('@getCustomers');
cy.get('[data-cy="row"]').should('have.length.greaterThan', 0);

Steps I would take:

  1. Find the request that fills the table. Give it an alias before you open the page.
  2. Wait for the alias. Then assert on the DOM, so Cypress retries until the page has finished drawing.
  3. If the page shows a spinner, assert cy.get('[data-cy=spinner]').should('not.exist').
  4. Remove all fixed waits. Keep one only when there is no signal to watch, and add a comment to say why.

What they are checking: Replacing sleeps with waits that give the same result every time

ExperiencedMost asked
Answer

What is `cy.session()` and why use it?

cy.session(id, setup, options) saves and restores cookies, localStorage and sessionStorage between tests. So you log in once, not in every test.

Cypress.Commands.add('loginBySession', (user: string, pass: string) => {
  cy.session(['login', user], () => {
    cy.request('POST', '/api/login', { email: user, password: pass });
  }, {
    validate() {
      cy.request('/api/me').its('status').should('eq', 200);
    },
    cacheAcrossSpecs: true,
  });
});

beforeEach(() => { cy.loginBySession('[email protected]', 'secret'); cy.visit('/'); });

Key points:

  • The id (plus args) names the saved session. Use a different id for each role.
  • validate runs the setup again if the session has expired.
  • Test isolation is on by default since Cypress 12. The page and storage are cleared before each test. So cy.session is the supported way to keep a login.
  • Visit a page after restoring. The restore step leaves a blank page.

What they are checking: Knowing how to make logins faster in modern Cypress

ExperiencedMost askedScenario
Answer

Your suite takes too long because every test logs in through the UI. How do you speed it up?

Treat login as setup, not as the thing you test. Test the login form in one or two special specs. Skip it everywhere else.

  1. Log in with cy.request to the auth endpoint, which sets the cookie. Or put the token in localStorage.
  2. Wrap it in cy.session, so it is saved across tests and specs.
  3. Add a validate step, so an expired session logs in again by itself.
  4. Use one test user per role, with known data. Create them with a seed script or an API.
cy.session('admin', () => {
  cy.request('POST', '/api/auth', { user: 'admin', pass: Cypress.env('ADMIN_PASS') })
    .then(({ body }) => window.localStorage.setItem('token', body.token));
});
cy.visit('/dashboard');

This usually saves several seconds per test. It also removes a common cause of unstable tests. Keep passwords in environment variables or CI secrets, never in the repo.

What they are checking: Practical ways to make a test suite faster

ExperiencedMost askedScenario
Answer

A Cypress test passes on your machine but fails, or passes sometimes and fails other times, in CI. How do you debug it?

Work from evidence, not guesses.

  1. Reproduce: run without a visible browser, in the same browser and screen size as CI. Run the single test in a loop (--spec and a repeat loop) to measure how often it fails.
  2. Read the artifacts: failure screenshot, video, Cypress Cloud or console logs, and the network log. Use the time-travel snapshots in cypress open.
  3. Find the type of cause:
    • Timing: asserting before data loads, fixed waits, animations. Fix with cy.intercept aliases and a retrying .should.
    • Shared state: tests depend on order or leftover data. Make each test add and clean its own data.
    • Selectors: changing classes, duplicate elements, detached DOM.
    • Environment: slower CI, different data, third-party scripts.
  4. Fix the root cause. Do not just add retries. Use retries: { runMode: 2 } only as a safety net, and track retried tests as unstable.
  5. If a test cannot be fixed quickly, quarantine it (tag it, or skip it with a ticket). Then it does not block the pipeline.

What they are checking: A clear method for unstable tests, the most common QA automation question

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you run Cypress in CI and parallelise it?

Run without a visible browser, with a fixed Node and Cypress version and a built app.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your Cypress suite passes on your machine but fails only in CI. What do you check?

I compare environment, timing and data, in that order.

ExperiencedMost askedScenarioFree with sign-in
Answer

The Cypress suite now takes 40 minutes and blocks releases. How would you cut it down?

Measure first, then remove waste.

ExperiencedMost askedFree with sign-in
Answer

Explain the Cypress architecture. Where does the test code run?

Cypress has two parts: a Node.js process and the browser.

ExperiencedMost askedFree with sign-in
Answer

Why can't you use async/await with Cypress commands the way you do in normal JavaScript?

Cypress commands do not return promises that give you values. They add work to an internal command queue and return a chainable object. The queue runs later, after your spec function has finished.

ExperiencedMost askedFree with sign-in
Answer

Page Object Model versus app actions: which would you use in Cypress and why?

Page objects wrap UI steps in classes. App actions skip the UI and set the state directly (an API call, a store update, a cookie).

ExperiencedMost askedFree with sign-in
Answer

How do you handle iframes in Cypress?

Cypress has no built-in iframe command. But you can reach the iframe's document yourself.

ExperiencedMost askedScenarioFree with sign-in
Answer

Can Cypress handle multiple browser tabs or windows? What are the workarounds?

No. Cypress controls a single tab and cannot switch to a new one. Common workarounds:

  • Remove the target attribute so the link opens in the same tab:
ExperiencedMost askedFree with sign-in
Answer

How do you manage environment-specific configuration and secrets in Cypress?

Keep settings out of specs and secrets out of git.

ExperiencedMost askedFree with sign-in
Answer

What is `cy.origin()` and when do you need it?

By default, Cypress allows one superdomain per test. Say a flow leaves it, for example login on auth.example.com and then back to app.example.com. Then the commands on the other origin must run inside cy.origin().

ExperiencedMost askedFree with sign-in
Answer

What is Cypress component testing and how is it different from E2E testing?

Component testing mounts one component in the real browser with Cypress. It tests that component alone, without the whole app or the backend.

ExperiencedMost askedFree with sign-in
Answer

What is `cy.task()` and when do you use it?

cy.task(name, arg) calls a Node.js function that you define in setupNodeEvents in the config. Use it for anything the browser cannot do: adding data to a database, reading files, sending emails, calling internal services.

ExperiencedMost askedScenarioFree with sign-in
Answer

What is conditional testing and why is it discouraged in Cypress?

Conditional testing means choosing a path based on the current DOM (if element exists, click it). It is discouraged because the DOM changes over time. Checking at one moment creates a race condition. The test then gives different results on different runs.

ExperiencedMost askedFree with sign-in
Answer

How do you test time-dependent behaviour, such as timers or dates, in Cypress?

Use cy.clock() to freeze or control time. Use cy.tick() to move it forward. This replaces real waiting.

ETL Testing and Data QA

ExperiencedMost asked
Answer

How do you perform source-to-target validation?

Compare the source and target at several levels, from cheap to deep.

  1. Counts: row counts per table and per partition or date.
  2. Totals: SUM, MIN, MAX, AVG on number columns. Distinct counts on keys.
  3. Set comparison: find missing and extra rows with EXCEPT/MINUS or an anti-join, on the business key.
  4. Column-level comparison: join on the key. Apply the documented transformation, then compare each mapped column.
  5. Hash/checksum comparison for wide tables.
  6. Sampling with business review for complex rules.
-- rows in source but not in target
SELECT order_id, customer_id, amount FROM src.orders
EXCEPT
SELECT order_id, customer_id, amount FROM dw.fact_orders;

Run it in both directions. Allow for known differences in the expected result, such as rejected rows, filtered statuses and type casts. Otherwise the comparison has too much noise.

What they are checking: A layered method, not just 'compare counts'.

ExperiencedMost asked
Answer

Give an example of transformation testing and how you verify a business rule.

Rule: 'customer_tier is GOLD when lifetime spend is at least 10000, SILVER at least 5000, otherwise BRONZE. NULL spend counts as 0.'

Approach: work out the expected value on your own from the source. Then compare it with the target.

WITH expected AS (
  SELECT customer_id,
         CASE WHEN COALESCE(SUM(amount), 0) >= 10000 THEN 'GOLD'
              WHEN COALESCE(SUM(amount), 0) >= 5000  THEN 'SILVER'
              ELSE 'BRONZE' END AS tier
  FROM src.orders GROUP BY customer_id
)
SELECT e.customer_id, e.tier AS expected, d.customer_tier AS actual
FROM expected e
JOIN dw.dim_customer d ON d.customer_id = e.customer_id
WHERE d.customer_tier <> e.tier;

Zero rows means the rule holds. Add test data at the boundaries (4999.99, 5000, 9999.99, 10000, NULL) and negative cases. Never copy the developer's SQL as the expected result. Write the expectation from the requirement.

What they are checking: An independent expected result, and boundary test design.

ExperiencedMost askedFree with sign-in
Answer

How do you test an SCD Type 2 dimension load?

Prepare a changed record in the source. Run the load. Then check the old and new rows.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test incremental loads?

An incremental load processes only the records that are new or changed since the last run. It usually uses a watermark (a timestamp or id) or change data capture.

ExperiencedMost askedScenarioFree with sign-in
Answer

A dashboard shows a different number than the source system. How do you find the cause?

Trace the number backwards, layer by layer. Split the problem in half each time.

ExperiencedMost askedFree with sign-in
Answer

How would you automate data validation with Python?

Use pandas or SQLAlchemy with pytest for repeatable checks. Run them in CI after each load.

ExperiencedMost askedScenarioFree with sign-in
Answer

The row counts match between source and target, but the business says some values are wrong. What do you do?

Matching counts only prove the number of rows. Move to row-level and column-level comparison.

ExperiencedMost askedScenarioFree with sign-in
Answer

After the daily load, duplicates appear in the fact table. How do you investigate?

Find what is duplicated, then find out why.

  1. Define the duplicate. Is it the same business key, or a whole-row copy?
ExperiencedMost askedScenarioFree with sign-in
Answer

The ETL job shows 'success' but yesterday's data is missing in the report. What do you check?

A green job does not prove the data is correct. Work outward from the symptom.

ExperiencedMost askedFree with sign-in
Answer

How do you use checksums or hashes to compare large tables?

Compute a hash of each row's relevant columns on both sides and compare them. This is faster than comparing every column by hand.

ExperiencedMost askedFree with sign-in
Answer

Write SQL to remove duplicates but keep the latest record per key.

Number the rows within each key, newest first. Then delete everything except row 1.

ExperiencedMost askedFree with sign-in
Answer

How do you test referential integrity in a data warehouse?

Check that every foreign key in a fact table points to a dimension row that exists. Also check that unknown values are handled by design.

ExperiencedMost askedFree with sign-in
Answer

What is data reconciliation and how do you do it?

Data reconciliation means confirming that the data in two systems or layers agrees for the same business scope. You must also explain every difference.

ExperiencedMost askedFree with sign-in
Answer

Write SQL to reconcile daily totals between a source table and a warehouse table.

Total both sides by day and join them. Flag any difference.

ExperiencedMost askedFree with sign-in
Answer

What is idempotency in ETL, and how do you test it?

An idempotent pipeline gives the same final result whether a run executes once or many times for the same input. This makes retries and backfills (reloading old data) safe.

ExperiencedMost askedFree with sign-in
Answer

How do you test error handling and rejected records in an ETL job?

Feed in bad data on purpose. Check that the pipeline behaves as specified.

ExperiencedMost askedFree with sign-in
Answer

What is Great Expectations and how do you use it for data testing?

Great Expectations (GX) is an open-source Python framework. You write data quality checks, called Expectations, and run them. It gives readable validation reports.

ExperiencedMost askedFree with sign-in
Answer

What are dbt tests and how do you write them?

dbt tests are SQL checks that run with dbt test. A test passes when its query returns zero rows.

Generic tests are declared in YAML:

ExperiencedMost askedFree with sign-in
Answer

How do you test AI or LLM features whose outputs are non-deterministic?

You cannot assert an exact string. So test the properties of the output and measure quality with statistics.

ExperiencedMost askedScenarioFree with sign-in
Answer

What is data migration testing and what do you validate?

Migration testing checks that data moved from an old system to a new one is complete, correct and usable.

ExperiencedMost askedFree with sign-in
Answer

How do you test masking and protection of PII or PHI in a data pipeline?

Check that sensitive data is protected wherever it is stored, moved or shown.

ExperiencedMost askedScenarioFree with sign-in
Answer

A source system adds a column and changes a data type without notice, and the pipeline breaks or silently loads wrong data. How do you test for and prevent this?

This is schema drift. Approach:

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you compare two large tables in different databases efficiently?

Do not pull everything into one place. Compare summaries first. Look closely only where they differ.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test timeliness and late-arriving data?

Timeliness: data must be available by the SLA time.

  • Check the latest load time and compare it with now. Alert if the lag is above the limit.
  • Test the job's start and end time against the time window with realistic volume.
ExperiencedMost askedFree with sign-in
Answer

How would you validate coded healthcare or finance fields, for example ICD-10 diagnosis codes, in a dataset?

Check the format with a pattern. Check validity against the official reference table.

Format check (ICD-10-CM codes look like E11.9: a letter, two characters, an optional dot and up to four more):

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you handle testing when the source data keeps changing during your test run?

You need a stable snapshot that you can compare against.

Performance Testing

ExperiencedMost asked
Answer

What is correlation in JMeter and how do you do it?

Correlation means capturing a changing value from one response and using it in later requests. Examples are a session id, CSRF token, order id or auth token. Without it, replayed requests fail because the recorded values are old.

Steps:

  1. Record or build the flow. Compare two runs to spot values that change.
  2. Add a post-processor to the sampler that returns the value: JSON Extractor ($.access_token), Regular Expression Extractor (name="csrf" value="(.+?)"), or CSS/JQuery Extractor.
  3. Store it in a variable, for example token.
  4. Use it later as ${token}, for example in a header Authorization: Bearer ${token}.
  5. Add a Response Assertion to confirm the extractor found a value.

k6 uses the same idea. You read the response and pass the value to the next call.

What they are checking: Can you handle values that change?

ExperiencedMost askedScenario
Answer

How do you design and run a performance test with JMeter, and what metrics do you report?

I follow a repeatable process:

  1. Define goals: critical transactions, user counts and targets (for example p95 under 500 ms, error rate under 1 percent, 300 requests per second).
  2. Build a workload model from production analytics: transaction mix, peak users and think times.
  3. Prepare a production-like environment and test data. Make sure the load generator is not the bottleneck.
  4. Script in JMeter: samplers, correlation, parameterisation, assertions and timers.
  5. Run a smoke test, then baseline, load, stress and soak runs in non-GUI mode.
  6. Monitor servers, application and database (CPU, memory, GC, connection pools, slow queries).
  7. Analyse and report.

Metrics to report: throughput, average and p90/p95/p99 response times per transaction, error rate and error types, active users over time, and server resource use. Also add what you saw, the bottlenecks found, risks and advice.

What they are checking: Can you plan and report a complete test?

ExperiencedMost asked
Answer

How do you plan a performance test and define the workload model?

Planning starts with non-functional requirements and real usage.

  • Gather goals: business-critical flows, expected users, peak periods, growth, and agreed service level objectives.
  • Use production logs and analytics to learn concurrent users, requests per second, transaction mix and think times. A mix could be 60 percent browse, 25 percent search, 10 percent cart, 5 percent checkout.
  • Choose test types: baseline, load at expected peak, stress, spike and soak.
  • Environment: as close to production as possible in size, data volume and configuration. Note any differences.
  • Data: realistic volumes and unique users.
  • Monitoring, entry and exit criteria, schedule, risks, and who is on call.

The output is a test plan and a workload table. Stakeholders approve them before scripting.

What they are checking: Do you plan from requirements and real traffic?

ExperiencedMost askedScenarioFree with sign-in
Answer

Response time increases sharply as load grows. How do you find the bottleneck?

I work from the symptom down to the layer.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you prepare an e-commerce site for a big sale event?

Plan capacity from the expected peak and test beyond it.

ExperiencedMost askedScenarioFree with sign-in
Answer

CPU is low but throughput stops increasing under load. What could be happening?

Low CPU with a throughput ceiling means the system is waiting, not computing. Likely causes:

  • Connection pool exhausted (database or HTTP client), so threads queue.
  • Thread pool or worker count too small, with requests waiting in the server.
  • Lock contention, synchronised sections, or a single-threaded component. -...
ExperiencedMost askedScenarioFree with sign-in
Answer

During a soak test memory keeps growing over hours. What do you do?

That pattern suggests a memory leak or a cache with no size limit.

ExperiencedMost askedFree with sign-in
Answer

What kinds of database problems show up in performance tests?

  • Slow queries: missing indexes, full table scans, inefficient joins, SELECT *.
  • N+1 query patterns from the application.
  • Lock contention and deadlocks under many writes at once.
  • Connection pool exhaustion or too many connections.
  • Large transactions, missing pagination, or growing tables.
  • Poor cache hit rates, and replication lag on read replicas.
ExperiencedMost askedScenarioFree with sign-in
Answer

Error rate rises above the threshold during a load test. How do you analyse it?

First, sort the errors into types.

ExperiencedMost askedFree with sign-in
Answer

How do stages, thresholds and executors work in k6?

  • Stages ramp virtual users up and down over time to set the shape of the load.
ExperiencedMost askedScenarioFree with sign-in
Answer

The business expects 500 requests per second at peak. How many virtual users do you need?

Use Little's Law with the full user cycle.

  • Requests per second per user = 1 / (response time + think time).
  • Say the average response time is 0.4 s and think time is 3.6 s. A cycle is 4 s, so one user makes 0.25 requests per second.
  • Users needed = 500 / 0.25 = 2000 virtual users.
ExperiencedMost askedScenarioFree with sign-in
Answer

Why does the test environment matter, and what if it is smaller than production?

Performance results are valid only if the environment is like production. This covers hardware, configuration, database size, network and third-party setup.

ExperiencedMost askedFree with sign-in
Answer

How do you handle authentication and tokens in a load test?

Do not log in on every iteration, unless login is what you are testing.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you performance-test a microservices application?

Test at several levels. The slowest service or dependency often limits the whole chain.

ExperiencedMost askedScenarioFree with sign-in
Answer

A release fails its performance SLA a day before go-live. What do you do?

Stay calm, put numbers on the problem and give options.

ExperiencedMost askedFree with sign-in
Answer

How do you run distributed load tests in JMeter?

One load generator is limited by its CPU, memory and network. For higher load, use a controller and several workers.

ExperiencedMost askedFree with sign-in
Answer

What is Little's Law and how is it used in performance testing?

Little's Law: N = X x R. N is the average number of users (or requests) in the system. X is throughput. R is the average time each one spends in the system (response time plus think time).

ExperiencedMost askedFree with sign-in
Answer

What is connection pool or thread pool exhaustion and how do you spot it?

A pool has a fixed number of connections or threads. When all are busy, extra requests wait in a queue or fail. Latency grows while CPU can stay low.

ExperiencedMost askedFree with sign-in
Answer

How do you include performance tests in a CI/CD pipeline?

Use layers: small checks on every build, bigger tests on a schedule.

ExperiencedMost askedFree with sign-in
Answer

How do you measure front-end performance, and how is it different from load testing?

Load testing measures how servers behave under many users. Front-end performance measures how fast a single page feels in a browser.

Tools: Lighthouse and PageSpeed Insights, WebPageTest, Chrome DevTools performance panel, and real user monitoring.

ExperiencedMost askedFree with sign-in
Answer

What are the open and closed workload models, and what is coordinated omission?

  • Closed model: a fixed set of virtual users. Each one sends a request, waits for the response, thinks, then repeats. If the server slows down, the request rate drops by itself.
  • Open model: requests arrive at a fixed rate, even when responses are slow. This is like real internet traffic. If the server slows down, requests pile up.
ExperiencedMost askedFree with sign-in
Answer

How do you test the performance of database queries and APIs with large data?

Use production-sized, realistic data. Queries that are fast on 1000 rows may be slow on 50 million.

ExperiencedFree with sign-in
Answer

What is the effect of caching and CDN on performance testing results?

Caches can make test results look much better than real life if the test reuses the same data.

SQL for Testers

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test a database? What is database testing?

Database testing checks that the data layer is correct and reliable:

  • Data integrity: values are stored correctly, there are no orphan rows, and the FK, PK, unique, check and NOT NULL rules work
  • Data mapping: actions in the UI or API change the right tables and columns. Check insert, update and delete with...
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you validate that data shown on the UI matches the database?

  1. Do the action or open the page. Note the values you see and the record ID.
  2. Query the database for the same record. Join the tables the page reads from.
  3. Compare field by field. Allow for formatting: dates, currency, rounding, trimmed spaces, and status codes like 1 = Active.
  4. Check counts and totals....
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you find rows in one table that do not exist in another (for example a data migration check)?

Compare the source and the target by key.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you test a data migration?

  • Before: study the source data (row counts, nulls, duplicates, min and max, different values). Read the mapping document. Take a backup. Test on a copy.
  • After: row counts match. Checksums or sums of number columns match. Sample records match field by field. Keys and relationships (FK) are intact, with no...
ExperiencedMost askedFree with sign-in
Answer

What is the difference between a clustered and a non-clustered index? Why are indexes used?

An index is a data structure (usually a B-tree) that makes lookups faster. The cost is more storage and slower writes. A clustered index sets the physical order of the table rows. So a table has only one. It is often the primary key (in InnoDB and SQL Server). A non-clustered (secondary) index is a separate structure that points to the rows. A table can have many.

ExperiencedMost askedFree with sign-in
Answer

Write a query to fetch employees whose salary is above the average salary of their department.

Window function version:

SELECT name, dept_id, salary
FROM (
  SELECT name, dept_id, salary,
         AVG(salary) OVER (PARTITION BY dept_id) AS dept_avg
  FROM employees
) t
WHERE salary > dept_avg;

Join version:

SELECT e.name, e.dept_id, e.salary
FROM employees e
JOIN (SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id) d
  ON d.dept_id = e.dept_id
WHERE e.salary > d.avg_sal;
ExperiencedMost askedFree with sign-in
Answer

Write a query to get the top 3 salaries in each department.

SELECT dept_id, name, salary
FROM (
  SELECT dept_id, name, salary,
         DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS r
  FROM employees
) t
WHERE r <= 3
ORDER BY dept_id, salary DESC;

Use ROW_NUMBER() to get exactly 3 rows per department. Use DENSE_RANK() to include ties. Window...

ExperiencedMost askedFree with sign-in
Answer

What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

Take the salaries 90, 80, 80, 70, ordered from high to low:

ExperiencedMost askedFree with sign-in
Answer

What is a transaction and how do COMMIT and ROLLBACK work? How would you test them?

A transaction puts several statements into one unit of work.

START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;      -- or ROLLBACK to undo everything since START

Tests to run:

  • Force an error after the first update...
ExperiencedMost askedScenarioFree with sign-in
Answer

How would you find and fix a slow SQL query?

  1. Reproduce the problem and measure it. Then run EXPLAIN (or EXPLAIN ANALYZE). It shows full table scans, row estimates and join order.
  2. Add or fix indexes on columns used in WHERE, JOIN and ORDER BY. Put the columns of a composite index in the right order.
  3. Avoid SELECT *, functions on indexed columns,...
ExperiencedMost askedScenarioFree with sign-in
Answer

What is SQL injection and how do you test for it?

SQL injection happens when user input is joined into a query as plain text. An attacker can then change what the query means. An example is ' OR '1'='1 in a login field.

ExperiencedMost askedFree with sign-in
Answer

Write a query to delete duplicate rows but keep one.

Keep the smallest id for each email.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a view and a table? Between a stored procedure and a function?

A table stores data. A view is a saved query that works like a virtual table. It has no data of its own, unless it is materialized (the result is stored). It makes queries simpler and can limit access. A stored procedure is a named block of SQL logic. It can do actions (INSERT, UPDATE, transactions) and...

ExperiencedMost askedFree with sign-in
Answer

What is a self join? Give an example.

A self join joins a table to itself, using aliases (short names). It helps with hierarchies and with comparing rows. Example: list employees with their manager.

ExperiencedMost askedFree with sign-in
Answer

How do you find the total sales per month and per customer, and only show customers above a threshold?

SELECT c.name,
       DATE_FORMAT(o.order_date, '%Y-%m') AS month,   -- PostgreSQL: TO_CHAR(o.order_date, 'YYYY-MM')
       SUM(o.total) AS monthly_sales
FROM orders o
JOIN customers c ON c.id = o.customer_id
GROUP BY c.id, c.name, DATE_FORMAT(o.order_date, '%Y-%m')
HAVING SUM(o.total) > 1000
ORDER BY month,...
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you check data consistency between two systems (for example the API and the database) using SQL?

Export or fetch the API data. Load it into a staging table, or compare IDs and key fields with a query on the database side. Check counts first. Then check totals (SUM(amount)). Then find row differences with LEFT JOIN ... IS NULL in both directions. Group the differences by type: missing, extra, or changed values. Put the checks in a script that runs after each deployment and reports mismatches. Look for timing causes (replication lag, caching) before you log a bug.

ExperiencedMost askedFree with sign-in
Answer

What are the isolation levels and what problems do they prevent?

LevelDirty readNon-repeatable readPhantom read
Read Uncommittedpossiblepossiblepossible
Read Committedpreventedpossiblepossible
Repeatable Readpreventedpreventedpossible (MySQL InnoDB mostly prevents it)
Serializablepreventedprevented...
ExperiencedMost askedScenarioFree with sign-in
Answer

How do you verify that a bug fix did not corrupt data? Which checks do you run in the database?

Take a snapshot before the fix. Save row counts, checksums or sums of key columns, and a copy of some rows. Apply the fix, run the scenario, then compare. Check these points:

  • Only the rows you meant to change were changed. Compare by primary key and by timestamp columns like updated_at.
  • Related tables and FK relations are still correct.
  • Totals still add up.
  • No new NULLs or duplicates appeared.
  • Audit or history tables recorded the change.
ExperiencedMost askedFree with sign-in
Answer

What is the difference between SQL and NoSQL databases, and what changes for testing?

SQL (relational) databases use tables, a fixed schema, joins and ACID transactions (MySQL, PostgreSQL). NoSQL covers document stores (MongoDB), key-value stores (Redis), column stores and graph stores. They have a flexible schema and can grow by adding more servers. They often use eventual consistency (data becomes the same everywhere after a short delay).

ExperiencedFree with sign-in
Answer

Write a query to get the running total of sales by date.

SELECT order_date,
       SUM(total) AS daily_total,
       SUM(SUM(total)) OVER (ORDER BY order_date) AS running_total
FROM orders
GROUP BY order_date
ORDER BY order_date;

The inner SUM(total) is the total for each day. The outer SUM(...) OVER (ORDER BY ...) adds the days up as it goes. Check that the...

ExperiencedFree with sign-in
Answer

How do you get the count of orders by status in a single query, with each status as a separate column?

Use conditional aggregation (a pivot):