Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a sql command
```
SELECT A.*,
K1.AD CONTACTAD,
K1.SYD CONTACTSYD,
KR.AD KURUM,
K2.AD SUPERVISORAD,
K2.SYD SUPERVISORSOYAD,
K3.AD REQUIRERAD,
K3.SYD REQUIRERSOYAD
FROM
TD_ACTIVITY A,
KK_KS K1,
KK_KS K2,
KK_KS K3,
KK_KR KR
WHER... | Use `||` for concatenating in oracle
```
SELECT A.*,
K1.AD || K1.SYD as CONTACT,
KR.AD KURUM,
K2.AD SUPERVISORAD,
K2.SYD SUPERVISORSOYAD,
K3.AD REQUIRERAD,
K3.SYD REQUIRERSOYAD
FROM
TD_ACTIVITY A,
KK_KS K1,
KK_KS K2,
KK_KS K3,
KK_KR KR
WHE... | Use [Oracle concatenation operator](http://docs.oracle.com/cd/B19306_01/server.102/b14200/operators003.htm)
```
SELECT A.*,
K1.AD || ' ' || K1.SYD CONTACT
KR.AD KURUM,
K2.AD SUPERVISORAD,
K2.SYD SUPERVISORSOYAD,
K3.AD REQUIRERAD,
K3.SYD REQUIRERSOYAD
FROM TD_ACTIVITY A,
... | Sql combining two column into one variable | [
"",
"sql",
"oracle",
""
] |
I was using the primary key (`TicketID`) as an `identity` column which was auto incrementing on every time a ticket is generated. Everything was going smoothly and then I started seeing that my `TicketID` jumps from 5,6 to like 1007, 1008.
Upon googling, I found about this design-by in SQL Server 2012:
<http://connec... | I have just solved my problem using a AFTER INSERT trigger.
Here it is what I did.
```
ALTER TRIGGER [dbo].[tid2]
ON [dbo].[tblPrac2]
AFTER INSERT
AS
declare @nid int;
set @nid = ( select MAX(TicketID) from [tblPrac2] );
if(@nid is null)
begin
set @nid = 1;
end
... | Create you own autoincrement mechanism is a bad idea.
Look at SEQUENCE object <http://technet.microsoft.com/en-us/library/ff878091.aspx>
But if you still want to do this, **one possible solution is**
```
CREATE TABLE dbo.TicketNumber
(
Number INT NOT NULL
)
INSERT INTO dbo.TicketNumber(Number) VALUES(0)
CREATE... | Auto Generate Unique column in SQL database | [
"",
"sql",
"sql-server",
""
] |
I imported a few xml files into my database. I have multiple survery ID's and multiple varname's per survey each with a value.
I have been able to get the results i need but i am not sure if i am doing this correctly.
I am not entirely sure how i would write a query to select out desired survey ids..
```
where varnam... | ```
SELECT *
FROM TableName
WHERE SURVEY_ID IN (SELECT SURVEY_ID
FROM TableName
WHERE VARNAME = 'age'
AND VALUE > 18)
```
Or a more efficient way will be
```
SELECT *
FROM TableName t
WHERE EXISTS (SELECT 1
FROM TableName
WHERE ... | Extending @M.Ali answer to actually answer your question - add as many exists as you need for all field conditions:
```
SELECT *
FROM TableName t
WHERE EXISTS (SELECT 1
FROM TableName
WHERE SURVEY_ID = t.SURVEY_ID
AND VARNAME = 'age'
AND VALUE > 18)
and EXISTS (SELECT 1
... | sql where clause query | [
"",
"sql",
"sql-server",
""
] |
I have a text column in my DB that stores a list of house names and numbers and when i order by ASC it outputs like this:
```
"Name No 1"
"Name No 12"
"Name No 14"
"Name No 5"
"Name No 7"
```
Is there an easy way of ordering it in the actual order like:
```
"Name No 1"
"Name No 5"
"Name no 7"
"Name No 12"
"Name No 1... | `ORDER BY LENGTH(colname) ASC, colname ASC`
This is probably as close as you're going to get to a "proper order". | Try this
```
SELECT
col1
FROM
Table1
ORDER BY
LENGTH(col1), col1
``` | Order by text and number | [
"",
"mysql",
"sql",
""
] |
all with the same column headings and I would like to create one singular table from all three.
I'd also, if it is at all possible, like to create a trigger so that when one of these three source tables is edited, the change is copied into the new combined table.
I would normally do this as a view, however due to con... | If the creation of the table is a one time thing you can use a `select into` combined with a `union` like this:
```
select * into TableD from
(
select * from TableA
union all
select * from TableB
union all
select * from TableC
) UnionedTables
```
As for the trigger, it should be easy to set up a `after ins... | If IDs are not duplicated it ill be easy to achieve it, in another case you can must add a OriginatedFrom column. You also can create a lot of instead off triggers (not only for insert but for delete and update) but that a lazy excuse for not refactoring the app.
Also you must pay attention for any reference for the d... | How to combine three tables into a new table | [
"",
"sql",
"sql-server",
""
] |
I'm look for any help to concatenate an integer.
Example:
In a company a employee as a employee number.
And is number is 140024.
Now, the number 14 is the year (depending on the date), and it needs to be assigned automatically. The other number 0024 is my problem. I could get the number 24 but how can I add the 00 o... | ```
DECLARE @Your_Number INT = 24;
SELECT CAST(RIGHT(YEAR(GETDATE()), 2) AS NVARCHAR(2))
+ RIGHT('000000000' + CAST(@Your_Number AS NVARCHAR), 4) --<-- This 4
RESULT: 140024
```
The Number `4` Decides how many Total digits you want after the Year Digits. | you have two choice : working with varchar or int itself.
Example :
```
select cast(14 as char(2)) + right('0000' + cast(24 as varchar(4)),4)
```
or with int
```
select 14 * 10000 + 24
```
Where 10000 of course is the number you can have max. It could be 100, 1000 or more. But your number of digit is probably fixe... | SqlServer - Concatenate an integer | [
"",
"sql",
"sql-server",
""
] |
Every query has a final row with an asterisk beside it and null values for every field? Why does this show up? I cant seem to find an explanation for it. Even putting a WHERE clause doesnt seem to get rid of it. Is this only happening to the MySQL implementation alone? | It is for inserting a new row, you enter the values there. | Are you sure it's not just the data entry row. Usually when viewing the table data in something like Workbench or SQLYog, it will display the rows of data, plus a blank row at the end that is used for adding new data. It will show NULL for each column if that is the default value for that columns data type | Why does SQL workbench always return a row full of null values in every query? | [
"",
"mysql",
"sql",
"null",
"mysql-workbench",
""
] |
I'm a newbie at web development, so here's a simple question. I've been doing a few tutorials in Django, setting up an SQL database, which is all good. I have now come across the JSON format, which I am not fully understanding. The definition on Wikipedia is: *It is used primarily to transmit data between a server and ... | JSON is data markup format. You use it to define what the data is and means. eg: This car is blue, it has 4 seats.
```
{
"colour": "blue",
"seats": 4
}
```
SQL is a data manipulation language. You use it to define the operations you want to perform on the data. eg: Find me all the green cars. Change all the r... | They are 2 completely different things.
**SQL** is used to communicate with databases, usually to Create, Update and Delete data entries.
**JSON** provides a *standardized* object notation/structure to talk to web services.
**Why standardized?**
Because JSON is relatively easy to process both on the front end (with... | Difference between JSON and SQL | [
"",
"sql",
"json",
""
] |
if i have a table as such:
```
CREATE TABLE IF NOT EXISTS users (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
username varchar(255) COLLATE utf8_unicode_ci NOT NULL,
password varchar(255) COLLATE utf8_unicode_ci NOT NULL,
email varchar(255) COLLATE utf8_unicode_ci NOT NULL,
phone varchar(255) COLLATE utf8_unicode_ci ... | The dates need to be quoted as well, and you forgot the `VALUES` keyword.
Also, because you are not inserting values for every column, you need to specify which columns you are inserting in. So your statement would become:
```
INSERT INTO users(
username,
password,
email,
phone,
name,
created_at,
update... | Date values should have quotes:
```
INSERT INTO users (username,password,email,phone,name,created_at,updated_at)
VALUES ('john',
'johndoe',
'johndoe@gmail.com' ,
'123456',
'John',
'2013-06-07 08:13:28',
'2013-... | INSERT INTO php MyAdmin | [
"",
"mysql",
"sql",
""
] |
I am trying to get count of a rows with specific values in a table, and if the count is 0, then add a value in the table. This count is a local variable in stored procedure.
I am building the SQL dynamically and storing SQL statement into a `nvarchar` variable.
Then, using `EXEC` I am running this SQL as follows hopi... | If you are building the query dynamically, you need `sp_executesql`. Try something like
```
-- building @qry will result as follows
@qry = 'SELECT @count = COUNT(*) FROM aTable WHERE (col1 = @col1 AND ...)'
EXEC sp_executesql @qry, N'@count INT OUTPUT', @count OUTPUT;
--Do whatever you want with @count...
```
**Sour... | In your sql ,why you are execute your query through EXEC because of your required output is already in @count variable so it is not need in your case.
Please refer below syntax.
```
DECLARE @qry Numeric
DECLARE @count INT
-- building @qry will result as follows
SELECT @count = COUNT(*) FROM aTable WHERE (col1 = @col1... | Build select statement dynamically and use it to populate a stored procedure variable | [
"",
"sql",
"stored-procedures",
""
] |
I have this table:
```
+----+---------------------+---------+---------+
| id | date | amounta | amountb |
+----+---------------------+---------+---------+
| 1 | 2014-02-28 05:58:41 | 148 | 220 |
+----+---------------------+---------+---------+
| 2 | 2014-01-20 05:58:41 | 50 | 285 |
+-... | You can use date functions, [`QUARTER()`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_quarter) and [`YEAR()`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_year)
```
SELECT
SUM(amounta),
SUM(amountb)
FROM
t
WHERE
YEAR(`date`)=2014
AND
QUARTER... | try this
```
SELECT SUM(amounta) FROM `your_table`
WHERE date LIKE '2014-01-%' OR date LIKE '2014-02-%' OR date LIKE '2014-03-%'
``` | MySQL: Select * from table up to this date and sum the column amounts | [
"",
"mysql",
"sql",
""
] |
My table has many columns, among them `attendance` and `register`
* if employee present its to update day1 = '1' and
* if employee present its to update day2 = '1' and
* if employee absent its to update day3 = '2' and etc.,
* if Sunday its to update day5='0'
Here my table:
```
Employee id | Month | day1 | day2 | day... | You can try using `Decode` function
```
select Decode(day1, 1, 1, 0) + -- <- treat 1 as 1, all other values as 0
Decode(day2, 1, 1, 0) +
Decode(day3, 1, 1, 0) +
...
Decode(day31, 1, 1, 0) as PresentCount,
Decode(day1, 2, 1, 0) + -- <- treat 2 as 1, all other values as 0
Deco... | Use `UNPIVOT` to transform columns to rows. For more information on this see [the article](http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html). Below is example of usage for your case:
```
with t as (
select 1234 emp_id,
'Feb' mon,
2 day1,
1 day2,
2 day3,
1 day4,
... | How to get count repeated data in row in sql? | [
"",
"sql",
"oracle",
"row",
""
] |
I’m newbie. I’m designing schema of database and I’m stuck at this place.
I have rooms table and one is rooms\_Items such that each room has many room\_Items.
The problem is that I need different fields in room\_items according to room type
**Room**
```
Id name
1 LG-12FG
2 LG-31FG
```
**Room\_item**
```
Id... | The preferred (normalized) solution would be to create a separate table for each item type (table Windows, table Doors,table Walls). This will make selecting data harder since you will have to do multiple joins.
Alternatively you can create single table containing all attributes of your items:
```
item_id, room_id, t... | I think this would be more comprehensible if you had a table for each of the entities in the room since this is the unit on which you want to make distinctions between data-values.
Since a Door is not a Wall in your case you can make both these separate tables, then you can use room\_items as a table in between.
```
... | database schema : how to make dynamic table according to type? | [
"",
"mysql",
"sql",
"database",
"oracle",
"database-schema",
""
] |
First of all I am really rusty on Oracle PLSQL, and I have seen several folks say this cannot be done and others that say it can, and I am just not able to make it happen. Any help would be greatly appreciated.
I am trying to read the value of a column in a record type dynamically.
I have a message with tokens and I ... | Using an [ASSOCIATIVE ARRAY](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/composites.htm#CHDEIDIC) just like Maps in Java
```
DECLARE
type my_record_map
IS
TABLE OF VARCHAR2(30) INDEX BY VARCHAR2(30);
type my_record
IS
record
(
my_members my_record_map );
type final_map
IS
TABLE OF my_record INDEX... | I don't think it can be done with a record type. It may be possible with an object type since you could query the fields from the data dictionary, but there isn't normally anywhere those are available (though there's an 11g facility called [PL/Scope](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/whatsnew.htm#LN... | PLSQL getting value of property in record dynamically? | [
"",
"sql",
"oracle",
"dynamic",
"plsql",
"plsqldeveloper",
""
] |
```
Edit Copy Delete 119 anand a f 1957-05-08 5678 s yyyy anand_abc@gmail.com 2014-02-17 11:42:39 1
Edit Copy Delete 120 gangadhar m 1952-02-04 495 c xxxx gang_v@yahoo.com 2014-02-17 12:02:16 3,4
Edit Copy Delete 124 ganesh r m 1991-09-04 9840 ... | You need to account for the fact that your `date_time` column *has* a time component, as does `GETDATE()`. Assuming SQL Server 2008 or later:
```
SELECT *
FROM stud_enq
WHERE date_time >= CONVERT(date,GETDATE()) and
date_time < CONVERT(date,DATEADD(day,1,GETDATE()))
```
Selects all values which have today... | Try this..
```
SELECT top 2 *
FROM stud_enq
WHERE convert(varchar(20),date_time,101) = convert(varchar(20),GETDATE(),101)
order by date_time desc
``` | How can i fetch data based on current date? | [
"",
"sql",
"sql-server",
""
] |
I have this small query
```
SELECT
MAX(myDate) AS DateToUser
FROM
blaTable
```
I'm getting this result "2011-05-23 15:18:01.223"
how can I get the result like 05/23/2011 "mm/dd/yyyy" format? | ```
SELECT
convert(varchar, MAX(myDate), 101) AS DateToUser
FROM
blaTable
```
For more Date Format Parameters: [**Click Here**](http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/) | Try this
**[FIDDLE DEMO](http://sqlfiddle.com/#!6/d41d8/15422)**
```
SELECT
convert(varchar,MAX(myDate),101) AS DateToUser
FROM blaTable
```
**[CONVERT](http://msdn.microsoft.com/en-us/library/ms187928.aspx)**
If you are using SQL SERVER 2012 then Simple use **FORMAT**
```
SELECT
FORMAT(MAX(myDate),'MM/dd... | Change the date format in SQLServer | [
"",
"sql",
"sql-server",
"date-format",
""
] |
```
---------------------------------- Lead MASTER TABLE
Create table leads
(
pk_lead_id int primary key identity,
lead_name varchar(50),
lead_mobile varchar(50)
)
insert into leads
select 'AK','9876543210'
insert into leads
select 'AK1','9876543210'
--....
insert into leads
se... | I agree with Gary Walker's logic of APPLY being the best way to do this, however I don't agree with the application. I think your query should be:
```
SELECT *
FROM Leads L
OUTER APPLY
( SELECT TOP 1 *
FROM Lead_tr tr
WHERE tr.fk_lead_id = l.pk_lead_id
O... | First, you should add an index to lead\_tr on fk\_lead\_id
Recommend you try cross apply
E.g., you can probably use something similar to this
```
select L.*, XL.*
from Leads L
cross apply (
select max(pk_leadtr_id) as tr_id
from lead_tr TR
where TR.fk_lead_id = L.pk_lead_id
) XL
```
Cr... | How to avoid using Sub query & optimize below mentioned query? | [
"",
"sql",
"sql-server",
"optimization",
"indexing",
"subquery",
""
] |
I run `EXEC sp_who2 78` and I get the following [results](https://stackoverflow.com/q/2234691/1501497):

How can I find why its status is suspended?
This process is a heavy `INSERT` based on an expensive query. A big `SELECT` that gets data from s... | SUSPENDED:
It means that the request currently is not active because it is waiting on a resource. The resource can be an I/O for reading a page, A WAITit can be communication on the network, or it is waiting for lock or a latch. It will become active once the task it is waiting for is completed. For example, if the que... | I use sp\_whoIsActive to look at this kind of information as it is a ready made free tool that gives you good information for troubleshooting slow queries:
[How to Use sp\_WhoIsActive to Find Slow SQL Server Queries](http://www.brentozar.com/archive/2010/09/sql-server-dba-scripts-how-to-find-slow-sql-server-queries/)
... | How to find out why the status of a spid is suspended? What resources the spid is waiting for? | [
"",
"sql",
"sql-server",
"optimization",
"query-optimization",
"sql-tuning",
""
] |
I have a woocommerce installation that uses ajax to add products to cart, however it takes a really long time to add a product to the cart (7-10 seconds).
I started logging and realized that there are hundreds of SQL queries that are run each time a product is added to cart, and that is what takes all the time. It sho... | Managed to find the solution after many hours, the problem was that woocommerce did a GET for the index page after adding to cart, which was taking all the time to load. I commented out the redirect and it works superfast now.
in woocommerce-functions.php
```
if ( $was_added_to_cart ) {
$url = apply_filters( 'ad... | In my case, I am using a modal popup with the variable product details, and needed to get the add-to-cart button to work via AJAX instead of being redirected to the product page. Since I'm fairly new to extending WooCommerce's functionality, I used daklock's code from above to derive my solution:
```
// AJAX Add To Ca... | Slow ajax add to cart for variable products Woocommerce | [
"",
"jquery",
"sql",
"ajax",
"wordpress",
"woocommerce",
""
] |
I created a trigger for my application that will allow me to keep a history of records that are edited in my grid.
I get the error: Invalid object name 'dbo.trgAfterUpdate'. and not sure why.
Here is my trigger:
```
USE [TestTable]
GO
/****** Object: Trigger [dbo].[trgAfterUpdate] Script Date: 2/25/2014 6:31:25 ... | Just confirm the table exists first. Try this:
```
use [TestTable]
GO
select * from [dbo].[summary]
```
If you get a message that the table doesn't exist, then you know what the problem is :) | My issue was that I didn't refresh local cache.
So I
> Ctrl + Shift + R
and voilà. | Invalid object name 'dbo.trgAfterUpdate' - Trigger Error | [
"",
"sql",
"sql-server",
"triggers",
""
] |
I have table called `Master` and i need all the possible records of all matching date as per user Input between `@FromDate` and `@Todate`....
**Master Table:**
```
ID FromDate ToDate
1 18/03/2014 18/03/2014
2 01/03/2014 05/03/2014
3 06/03/2014 08/03/2014
```
**My Query:**
```
select ID
from m... | I Got The Solution:
```
SELECT ID
FROM master M
WHERE ((M.FromDate BETWEEN '10/03/2014' AND '17/03/2014')
OR (M.ToDate BETWEEN '10/03/2014' AND '17/03/2014'))
```
parenthesis is Very Important in Sequel Server..... | try this
```
select ID from master M where (M.FromDate>='10/03/2014' M.FromDate<'17/03/2014') or (M.ToDate>='10/03/2014' and M.ToDate<'17/03/2014');
``` | Between Two Date Condition in Sql Server | [
"",
"sql",
"sql-server",
"date",
""
] |
I've a problem with the following sql select query. The columns are not aggregated by the group by command.
```
SELECT
Dept.Name AS DeptName, COUNT (T.Id) AS TotalServiceNumber,
(Case when SS.Status <> 'Resolved' then COUNT (T.Id) end) AS UnresolvedNumber,
(Case when T.FixTime < '120' then COUNT(T.FixTim... | try this query:
```
SELECT
Dept.Name AS DeptName, COUNT (T.Id) AS TotalServiceNumber,
sum(Case when SS.Status <> 'Resolved' then 1 else 0 end) AS UnresolvedNumber,
sum(Case when T.FixTime <= '120' then 1 else 0 end) AS ResolvedLessThanTwoHoursNumber,
sum(Case when T.FixTime > '120' then 1 else 0 end)... | Try this
```
SELECT TotalServiceNumber, SUM(UnresolvedNumber), SUM(ResolvedLessThanTwoHoursNumber), SUM(ResolvedMoreThanTwoHoursNumber)
FROM (
SELECT
Dept.Name AS DeptName, COUNT (T.Id) AS TotalServiceNumber,
(Case when SS.Status <> 'Resolved' then COUNT (C.Id) end) AS UnresolvedNumber,
(... | Columns in sql query are not grouped | [
"",
"sql",
"sql-server",
""
] |
I have a series of records containing some information (product type) with temporal validity.
I would like to meld together adjacent validity intervals, provided that the grouping information (the product type) stays the same. I cannot use a simple `GROUP BY` with `MIN` and `MAX`, because some product types (`A`, in t... | This is a gaps-and-islands problem. There are various ways to approach it; this uses `lead` and `lag` analytic functions:
```
select distinct product,
case when start_date is null then lag(start_date)
over (partition by product order by rn) else start_date end as start_date,
case when end_date is null then lea... | It seems like there should be an easier way, but a combination of an analytical query (to find the different gaps) and a hierarchical query (to connect the rows that are continuous) works:
```
with data as (
select 'A' product, to_date('7/1/2013', 'MM/DD/YYYY') start_date, to_date('7/31/2013', 'MM/DD/YYYY') end_da... | Joining together consecutive date validity intervals | [
"",
"sql",
"oracle",
"oracle11g",
"gaps-and-islands",
""
] |
I have a query like the following:
```
SELECT
COUNT(*) AS `members`,
CASE
WHEN age >= 10 AND age <= 20 THEN '10-20'
WHEN age >=21 AND age <=30 THEN '21-30'
WHEN age >=31 AND age <=40 THEN '31-40'
WHEN age >=41 AND age <= 50 THEN '41-50'
WHEN age >=51 AND age <=60 THEN '51-60'
WHEN age >=61 ... | The rows you wish for are not displayed because there's no data for them. Outer join (left or right) all possibilities and they will be displayed:
```
SELECT
COUNT(members.whatever_column_best_would_be_primary_key) AS `members`,
ages.age_range
FROM `members`
RIGHT JOIN (
SELECT '10-20' as age_range
UNION A... | you may use coalsce !
try this
```
SELECT
COALESCE(COUNT(*),0) AS `members`,
CASE
WHEN age >= 10 AND age <= 20 THEN '10-20'
WHEN age >=21 AND age <=30 THEN '21-30'
WHEN age >=31 AND age <=40 THEN '31-40'
WHEN age >=41 AND age <= 50 THEN '41-50'
WHEN age >=51 AND age <=60 THEN '51-60'
WHEN age >=61 AND age <=70 THEN '... | Give every "empty" age band 0 | [
"",
"mysql",
"sql",
""
] |
Is it possible to truncate or flush out a table variable in SQL Server 2008?
```
declare @tableVariable table
(
id int,
value varchar(20)
)
while @start <= @stop
begin
insert into @tableVariable(id, value)
select id
, value
from xTable
where id = @start
... | just delete everything
```
DELETE FROM @tableVariable
``` | No, you cannot `TRUNCATE` a table variable since it is not a physical table. Deleting it would be faster. See this answer from [Aaron Bertrand](https://stackoverflow.com/a/11621024/2908279). | Truncate/Clear table variable in SQL Server 2008 | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am trying to solve Exercise 14.on <http://www.sql-ex.ru/>. The query asks for :
> Find out makers who produce only the models of the same type, and the
> number of those models exceeds 1. Deduce: maker, type
The database schema is as follows:
```
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, pric... | Try this query...
```
SELECT DISTINCT maker, type
FROM product
WHERE maker IN
(SELECT DISTINCT maker
FROM product
GROUP BY maker HAVING COUNT(distinct type) = 1
AND count(model) > 1)
``` | Claudiu Haidu answer is correct, though there's an even shorter answer:
```
SELECT maker,MIN(type)
FROM product
GROUP BY maker
HAVING COUNT(distinct type) = 1 AND COUNT(model) > 1
``` | SQL-ex.ru Execise 14 | [
"",
"sql",
""
] |
My table in this issue has three columns: Player, Team and Date\_Played.
```
Player Team Date_Played
John Smith New York 2/25/2014
Joe Smith New York 2/25/2014
Steve Johnson New York 2/25/2014
Steph Curry Orlando 2/25/2014
Frank Anthony Orlando 2/26/2014
Brian Smith ... | This query has been tested in Access 2010:
```
SELECT Team, Count(Date_Played) AS Count
FROM
(
SELECT DISTINCT Team, Date_Played
FROM NBAGameLog
) AS whatever
GROUP BY Team
``` | A bit less code:
```
SELECT Team, Count(distinct Date_Played) AS Count
FROM NBAGameLog
GROUP BY Team
```
It does Show the same execution plan as the first answer. | SQL Distinct Count with Group By | [
"",
"sql",
"ms-access",
"distinct",
""
] |
I need to select a row from a table which must satisfy the following conditions:
* It needs to match a quite complex WHERE clause
* It needs to have the minimum value in column X
Thus far, the only working solution I have is this:
```
SELECT <columns>
FROM <table>
WHERE <complex WHERE clause>
AND <columnX> = (SELECT... | Turned out the easiest solution was ordering...
```
SELECT TOP 1 <columns>
FROM <table>
WHERE <complex WHERE clause>
ORDER BY <ColumnX> ASC
``` | Correct me if I'm wrong, I would use a CTE (Common Table Expression) to write the complex query and have the where clause reference to it.
Hope that helps. | How to select the row which matches a complex WHERE clause and has the minimum value in a given column? | [
"",
"sql",
"sql-server",
"select",
"where-clause",
""
] |
I have a table name "a"
```
Id name
1 abc
2 xyz
3 mmm
4 xxx
```
and Other table name is "b"
```
Id suId
3 2
3 1
```
My requirement is get detail from "a" table from "b" table where id=3. Any help? | ```
SELECT a.Id, a.name, b.Id, b.suId FROM b JOIN a ON b.suId = a.Id WHERE b.Id = 3;
``` | I wont recommend join for this kind of scenarios(you want all details from Table A whose ids are in Table B suId column, where Table B id should be 3., Its bad English but hope you got me and may be i got you too.)
```
SELECT a.name FROM a
WHERE
a.id IN(SELECT b.suId FROM b WHERE b.id = 3);
```
If you want to use jo... | Getting data from one table to another table using join | [
"",
"sql",
"database",
""
] |

This is the output of a select \* from table1, I have a doubt with count function... I want to count that NULL, in order to do that the proper option is to do this:
select count(\*) from table1 where fecha\_devolucion is null --> This gives me the proper answer counting ... | From the documentation (<http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions032.htm>):
> If you specify expr, then COUNT returns the number of rows where expr
> is not null. ...
>
> If you specify the asterisk (\*), then this function returns all rows...
In other words, COUNT(fecha\_devolucion) counts non... | This is the another way how you can get the count :
```
SELECT SUM(NVL(fecha_devolucion,1)) FROM table1 WHERE fecha_devolucion IS NULL;
``` | Oracle SQL Developer - Count function | [
"",
"sql",
"oracle",
""
] |
I need to `delete` all `rows` in some `table` `where` value is empty string.(I have multiple table which got similar name).
I tryed to execute those sql statement which is in string:
```
DECLARE @sql AS NVARCHAR(MAX)
DECLARE @emptyValue AS NVARCHAR(1) =''
set @sql = N'DELETE FROM SampleTable WHERE Value='+@emptyV... | Instead of doing string concatenation, [parameterize](http://technet.microsoft.com/en-us/library/ms175170%28v=sql.105%29.aspx) the call to `sp_executesql`, for Sql Injection and other reasons (including caching of query plans, and not having to worry about escaping quotes :-):
```
DECLARE @sql AS NVARCHAR(MAX);
DECLAR... | You have two quotes:
```
set @sql = N'DELETE FROM SampleTable WHERE Value='+@emptyValue+''
```
Change it to:
```
set @sql = N'DELETE FROM SampleTable WHERE Value='+@emptyValue
```
<http://sqlfiddle.com/#!3/ce8e3/4> | Incorrect syntax near '=' sp_executesql | [
"",
"sql",
"sql-server",
"t-sql",
"sp-executesql",
""
] |
I have a table named `Car`
```
Table car ( id int NOT NULL, plate int NOT NULL, sent_to_server bit NOT NULL );
```
I want to select all Cars which are not sent to server yet
```
SELECT *
FROM car
WHERE sent_to_server = 0;
```
Then I should update my DB
```
UPDATE car
SET sent_to_server = 1
WHERE sent_to... | As long as you are using SQL Server 2005 or later you can make use of `OUTPUT` in a single query.
```
UPDATE Car
SET sent_to_server = 1
OUTPUT Inserted.id, Inserted.plate
WHERE sent_to_server = 0;
```
This will update the rows where `sent_to_server` is zero and return the modified rows. No need for a transaction... | I think you need to use transaction.
Place your both queries in below code
```
BEGIN TRANSACTION
select * from car where sent_to_server = 0;
update car set sent_to_server = 1 where sent_to_server = 0;
COMMIT TRANSACTION
```
By default tansaction will lock the table to read for other connection, so other thread will... | How to select and update selected rows in a single sql query? | [
"",
"sql",
"t-sql",
"transactions",
"petapoco",
""
] |
i have a table that contains a
user: ID,Name,UserName
and a table that contains an
event:ID,AskerID,DoerID,EventName
I need to get the name of the Asker using AskerID but I already have a left outer join
that get the doer one
I'm not very good with sql ...a little help is always welcome | You can like one table to other tables based on different ChildKeys (AskerID, DoerID).
```
Select
a.Name as Asker
, d.Name as Doer
, e.EventName
from event as e
left outer join user as a
on e.AskerID = a.ID
left outer join user as d
on e.DoerID = d.ID
``` | Assuming the table with the user is called `Users` and the table with the event is called `Events`:
```
select e.ID
e.AskerID
a.Name as AskerName
e.DoerID
d.Name as DoerName
e.EventName
from Events e
left join Users a
on e.AskerID = a.ID
left join User... | SQL Select with 2 foreign key referencing on the same table | [
"",
"sql",
"sql-server",
"select",
""
] |
Hi i have this query but its giving me an error of Operand should contain 1 column(s) not sure why?
```
Select *,
(Select *
FROM InstrumentModel
WHERE InstrumentModel.InstrumentModelID=Instrument.InstrumentModelID)
FROM Instrument
``` | according to your query you wanted to get data from instrument and instrumentModel table and in your case its expecting "from table name " after your select \* .when the subselect query runs to get its result its not finding table instrument.InstrumentModelId inorder to fetch result from both the table by matching you ... | You can use a join to select from 2 connected tables
```
select *
from Instrument i
join InstrumentModel m on m.InstrumentModelID = i.InstrumentModelID
``` | Nested SELECT SQL Queries Workbench | [
"",
"mysql",
"sql",
"subquery",
""
] |
I was asked this question the other day in a phone screen and I had trouble with it. Suppose I have the following table. This is a table of employees, and more than one employee can have the same supervisor.
```
+------------+--------------+------+
| Field | Type | Null |
+------------+--------------+----... | You would use something like this (assuming your `supervisor` column is not a reference to another table)
```
select supervisor, count(name)
from employees
group by supervisor ;
``` | ```
select supervisor, count(*) as cnt
from emp
group by supervisor
``` | Returning a list and a count in SQL | [
"",
"mysql",
"sql",
""
] |
**Background**
My application is backed up by an SQL Server (2008 R2), and have quite a few SP, triggers etc..
My goal is to make sure upon program start that all of those objects are still valid.
For example, if I have a stored procedure `A` which calls stored procedure `B`, If someone changes the the name of `B... | Assuming that all of your dependencies are at least schema qualified, it seems like you could use [`sys.sql_expression_dependencies`](http://technet.microsoft.com/en-us/library/bb677315.aspx). For instance, running this script:
```
create proc dbo.B
as
go
create proc dbo.A
as
exec dbo.B
go
select OBJECT_SCHEMA_NAME(re... | You can try this. It may not be 100% for schema (it has owner name below) as it was based more when I worked with SQL Server 2000, but I tested it 2008, it basically runs alter statement on all the procs, functions, views. Comment out the PRINT @objName + ' seems valid.' to see only invalid procs, functions, views... F... | Validating that all Stored procedures are valid | [
"",
"sql",
"sql-server",
"validation",
"stored-procedures",
"sql-server-2008-r2",
""
] |
I'm trying to get records that have the highest value in one particular column ("version"). I'm using the base\_id to get rows, and there may be more than one row with the same base\_id, but they will then have different version numbers. So the point of the statement is to only get the one with the highest version. And... | Well, I think I found the answer myself. As far as I can understand, a query like this will take a lot of time, and instead the database needs to be modified. I found this:
[How to version control a record in a database](https://stackoverflow.com/questions/323065/how-to-version-control-a-record-in-a-database)
The sug... | Given your own answer, your question was basically the same as in the link you supplied. Since you had some sub-questions I'll try to give you some additional help there.
*If you want to have some kind of version control in your database, then you basically extend your primary key by some version column(s). I'd vote f... | SQL max value in one column | [
"",
"mysql",
"sql",
"max",
"greatest-n-per-group",
""
] |
I have a table which records every status change of an entity
```
id recordTime Status
ID1 2014-03-01 11:33:00 Disconnected
ID1 2014-03-01 12:13:00 Connected
ID2 2014-03-01 12:21:00 Connected
ID1 2014-03-01 12:24:00 Disconnected
ID1 2014-03-01 12:29:00 Connected
ID2 2014-03-01 12:40:00 Disconnect... | The special difficulty is not to miss the time spans to the outer time frame.
Assuming that the next row for any given `id` always has the opposite status.
Using the column name `ts` instead of `recordTime`:
```
WITH span AS (
SELECT '2014-03-01 13:00'::timestamp AS s_from -- start of time range
, '201... | This is how I understand your question [SQL Fiddle](http://sqlfiddle.com/#!15/b36ef/1)
```
select id, sum(diff) as inactive
from (
select
recordtime,
recordTime -
lag(recordTime, 1, recordTime)
over(
partition by id
order by recordTime
... | Sum of time difference between rows | [
"",
"sql",
"postgresql",
"aggregate-functions",
"window-functions",
""
] |
Table A records are
```
id | email
1 | abc@abc.com
2 | xyx@xy.com
3 | kkdk@kk.com
4 | 333@abc.com
```
Table B records are
```
id | email
1 | abc@abc.com
3 | kkdk@kk.com
```
Now result should be
```
id | email
2 | xyx@xy.com
4 | 333@abc.com
```
How to do this using joins ? | try something like:
```
SELECT
t1.*
FROM tableA as t1
LEFT JOIN tableB t2 ON t1.email=t2.email
WHERE t2.id IS NULL
``` | Try this:
```
select distinct(a.id), a.email from table1 a inner join table2 b
on a.id not in (select id from table2)
```
[fiddle](http://sqlfiddle.com/#!2/8f18a/5) | Display all table A records which are not in table B using mysql joins concept | [
"",
"mysql",
"sql",
""
] |
How do i get a list of all id/primary key for a table. Say i have this table:
```
class Blog(models.Model)
title = models.CharField()
body = models.CharField()
author = models.ForeignKey(Author)
```
assume the field *author* is an Author object. I want to get all the ids of Blog where author=author
i know i ca... | You can do this using [`values_list`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#values-list) method.
```
blogs = Blog.objects.filter(author=author).values_list('id', flat=True)
```
See more at the [Django queryset documentation](https://docs.djangoproject.com/en/stable/ref/models/querysets/#value... | ```
Blog.objects.filter(author=author).values_list('id', flat=True)
```
`values_list()` gives a list of rows, each row a tuple of all of the fields you specify as arguments, in order. If you only pass a single field in as an argument, you can also specify `flat=True` to get a plain list instead of a list of tuples. | django models: get list of id | [
"",
"sql",
"django",
"django-models",
""
] |
This is my table structure
```
create table #t(id int identity(1,1),street varchar(100))
insert into #t values('#100 church street'),('#102 vitalFinaly street'),('#101 teriyakei street')
```
I need output like this: (6 characters after integer)
```
id (No column name)
1 church
2 vitalF
3 teriya
```
I tried ... | **[Use Charindex](http://technet.microsoft.com/en-us/library/ms186323.aspx)**
```
select id,substring(street,charindex(' ',street)+1,6) from #t
```
**[SEE DEMO](http://www.sqlfiddle.com/#!6/d41d8/15459)** | Please try:
```
select
id, LEFT(SUBSTRING(Street, PATINDEX('%[A-Z]%', Street), LEN(Street)), 6)
from #t
``` | selecting values after integer using substring | [
"",
"sql",
"sql-server",
""
] |
I have queries from two different tables that group their respective data (count) by yyyy-mm. I would like to take the count results from both queries and display them together. Following are my two queries:
QUERY 1:
```
DECLARE @ThisMonth DATETIME
SET @ThisMonth = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', G... | You can just join them together as subqueries. I chose `INNER JOIN` below but feel free to change it to a different type of join.
```
DECLARE @ThisMonth DATETIME
SET @ThisMonth = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101')
select t1.[MONTH], t1.[NCRs], t2.[RUNS]
from
(
select cast(cast(Tran... | If both queries will return the same Month ranges, you can join them together with an Inner Join. Otherwise, I would create a table variable containing all the months you want to display. Let me know if I can help you with that.
```
DECLARE @ThisMonth DATETIME
SET @ThisMonth = DATEADD(MONTH, DATEDIFF(MONTH, '1900... | SQL joining queries from two databases | [
"",
"sql",
"sql-server",
""
] |
Assuming I have the following table :
```
Table Files
id
size
```
In pseudo SQL I need this king of processing :
```
select id
where
size < S1 and (limit this clause to N1 results)
or
size > S2 and (limit this clause to N2 results)
```
I know Oracle defines rownum keyword to limit results.
But in my case, that d... | Use a `UNION`:
```
SELECT *
FROM (
SELECT 'low' AS "which", "id"
FROM Files
WHERE "size" < S1)
WHERE ROWNUM <= N1
UNION
SELECT *
FROM (
SELECT 'high' AS "which", "id"
FROM Files
WHERE "size" >= S1)
WHERE ROWNUM <= N2
```
[DEMO](http://www.sqlfiddle.com/#!4/fc7e9/7) | Assuming the clauses are *independent* (which they are for your example), you can do this with `union all`:
```
select id
. . .
where size < S1 and rownum <= N1
union all
select id
. . .
where size > S1 and rownum <= N2
```
If you don't want to repeat the `from` clause (because it is complex for instance), you can us... | SQL limit results in where clause | [
"",
"sql",
"oracle",
""
] |
I want to calculate date time difference between two dates but the minutes should be in .100 scale i.e if date time difference is `2.30 (2 Hours 30 Minutes)` i want it in format `2.50`
30 minutes = 0.50
i wrote a query for it but it does not work well when minutes are in range of `01 - 09`
Case 1 : Wrong Output
```... | 60 minutes = 60/60 = 1.0
30 minutes = 30/60 = 0.5
4 minutes = 4/60 = `0.066`, not `0.10`
0.10 = 6 minutes, not 4 minutes difference as in your first example.
If we temporarily remove the seconds to reduce complexity, then you simply divide the seconds by 3600.00:
```
Declare @Start DateTime='02-03-2014 14:25:00'
D... | It seems in `STR(DateDiff(MINUTE,@Start,@End)%60/0.6)` 0.6 should be replaced with 6.0
The above solution would round off upto 1 place after decimal.
If you want to `ROUND` off to 2 places after decimal you can try the below snippet:
```
SELECT CAST(CAST(ROUND(DateDiff(MINUTE,@Start,@End)%60/0.6) AS NUMERIC(12,2)) A... | convert datediff minutes to 100 base format in sql | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
```
INSERT into LibraryTable(ID, Artist, Name, Rating, PlayCount) VALUES(
Select MIN(a.ID + 1)
From LibraryTable A
Left Join LibraryTable B
On A.ID = B.ID - 1
Where B.ID Is NULL, 'eg', 'eg', 1, 1)
```
im getting a syntax error at "Select" and the "," after null. im a beginner so any helpful tips would be greatly appre... | You want `insert . . . select`:
```
INSERT into LibraryTable(ID, Artist, Name, Rating, PlayCount)
Select MIN(a.ID + 1), 'eq', 'eq', 1, 1
From LibraryTable A Left Join
LibraryTable B
On A.ID = B.ID - 1
Where B.ID Is NULL;
```
The `values` keyword is not used for this form of the `insert`.... | TRY this:
```
INSERT into LibraryTable(ID, Artist, Name, Rating, PlayCount)
Select MIN(a.ID + 1) as ID, 'eg' as Artist, 'eg' as Name, 1 as Rating, 1 as PlayCount
From LibraryTable A
Left Join LibraryTable B
On A.ID = B.ID - 1
Where B.ID Is NULL
``` | Syntax Error but not sure why (SQL Server) | [
"",
"sql",
"sql-server",
"database",
""
] |
Let's say we are to normalize a database into 3rd normal form using the requirement:
> I need a movie ticket registry program that can remember customers and
> the tickets that they've purchased.
We might end up with a database like this:
```
ticket
id
movie_name
price
customer
id
first_name
```... | As Jordan says, the point of breaking data out into a separate table is to avoid redundant data.
As you apparently realize, we do NOT want to lay out our tables like this:
```
WRONG!!!
ticket
customer_name
movie_name
```
That would mean that the customer\_name is repeated for every movie he watches, and the mov... | Your first approach is not correct. If you think about the problem, there are three entities:
* Movie
* Customer
* Ticket
The connection between `Movie` and `Customer` is really the `Ticket` table, so this is an example of an association or junction table that has additional information.
I wouldn't think of the prob... | A different (less redundant) approach to Normalization | [
"",
"sql",
"database",
"database-normalization",
""
] |
I have a column which I need to set to true or false based on a condition, is this possible to do as part of an existing update?
Example:
```
UPDATE i
SET i.Outstanding = i.Total - @Payments,
i.Paid = @Payments ,
i.Closed = (i.Total <= @Payments) -- THIS DOESNT WORK :(
FROM Invoice i
JOIN [Transact... | You can use `CASE` statement
```
UPDATE i
SET i.Outstanding = i.Total - @Payments,
i.Paid = @Payments ,
i.Closed = CASE WHEN i.Total <= @Payments THEN 1 ELSE 0 END
FROM Invoice i
JOIN [Transaction] t ON t.Invoice_Id = i.Id
WHERE i.Id = @InvoiceId
``` | You can use simple case statement like below
```
UPDATE i
SET i.Outstanding = i.Total - @Payments,
i.Paid = @Payments ,
i.Closed = CASE WHEN i.Total <= @Payments THEN 'Your value' ELSE 'your value' END
FROM Invoice i
JOIN [Transaction] t ON t.Invoice_Id = i.Id
WHERE i.Id = @InvoiceId
``` | How can I set a column based on a condition in SQL Server? | [
"",
"sql",
"sql-server",
""
] |
I'm studying this SQL statement :
```
SELECT * FROM Customers
ORDER BY Country,CustomerName;
```
[From this](http://www.w3schools.com/sql/sql_orderby.asp)
How does it work that it orders by both country and CustomerName ? In my mind it just doesn't seem intuitive, i.e you order by either Country OR CustomerName but ... | It orders by Country, but if some rows have the same Country, it orders them by CustomerName. | It orders by country first. If the countries match, then it orders by customer name. It sorts the customers alphabetically but groups them by country, so English customers come before French ones. | How do SQL order-by with multiple-columns work? | [
"",
"sql",
""
] |
How to Delete Duplicate records from Table in SQL Server ? | ```
WITH CTE AS(
SELECT [col1], [col2], [col3], [col4], [col5], [col6], [col7],
RN = ROW_NUMBER()OVER(PARTITION BY col1 ORDER BY col1)
FROM dbo.Table1
)
DELETE FROM CTE WHERE RN > 1
```
[Example](http://sqlfiddle.com/#!6/fae73/1/0) | To delete rows where the combination of columns `col_1, col_2, ... col_n` are duplicates, you can use a common table expression;
```
WITH cte AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY col1, ..., col_n ORDER BY col_1) AS rn
FROM table_1
)
DELETE FROM cte WHERE rn<>1;
```
Since the rows are classifi... | How to Delete Duplicate records from Table in SQL Server? | [
"",
"sql",
"sql-server",
""
] |
i have two different database schemas
First Structure is :
```
table 1 : country_master
Column name: id(primary key) country_name
table 2: State_master
Column name: id(primary key) State_name Country_id(foreign key of country_master)
table 3: City_Master
Column name: id(primary key) city_name State... | The second structure gonna be create more issue regarding performance point of view.
As the child table have all references, it is difficult to maintain. Consider the scenario, where you need to mark for the "capital" of each state having the crores of data, then what would you do to add one more column into existing t... | You could probably achieve the same performance by adding the right indices on the tables.
For ex: if one if your queries is search for all states in a country you would need to create an index on the master and sub id of the sub table in the second structure. | best structure of my table in Perfomance way: | [
"",
"mysql",
"sql",
"sql-server",
"sql-server-2008",
"sqlite",
""
] |
I have millions of records in a table with following columns:
```
id, item_id, customer_id, date
```
I want to find `customer_id` for a specific month which are inserted first time in the table in that month.
What is best and simple query for this.
Thanks | ```
select customer_id , min(date) as min_date
from theTable
group by customer_id
having min_date>=<the desired date>
``` | try something like:
```
SELECT
date_format(date,"%M") month,group_concat(customer_id ORDER BY customer_id) customer_ids
FROM
<table_name>
GROUP BY month;
``` | MySQL Query: Get new customers in the month | [
"",
"mysql",
"sql",
""
] |
**I have created three tables**
create table employee1 (eid int, ename varchar(25),email varchar(15));
create table accounts1 (eid int, accno int,atype varchar(2),bal int);
create table trans1(cid int, accno int, atype varchar(2), accounts int, bal int);
**using alter command I have added primary key and foreign ke... | You need to drop the constraints in the following order(Which is the reverse of the order in which you created the keys):
* Foreign keys in the table `trans1`
* Primary keys in the table `accounts1`
* Foreign key in the table `accounts1`
* Primary key in the table `employee1`
[fiddle](http://sqlfiddle.com/#!2/f5195) | I think,You need to **first remove** the foreign key of table **trans1**.Then remove foreign key of table **accounts1**.Then try to remove primary key of table **accounts1**.then remove primary key of table \**employee1 \**. | Usage of Alter command to drop Primary key and Foreign Key | [
"",
"mysql",
"sql",
"database",
"primary-key",
"alter-table",
""
] |
Hi i am looking for a way to write a SQL statement which will come out with the following results :-
Lets say we have Dept & Emp ID i would like to generate like records from Dept 3 for the first two rows then followed by Dept 2 with one row then continue Dept 3 and so on :
```
DEPT EMPID
----- ------
... | You could use something like this
```
SELECT
DEPT,
EMPID
FROM (
SELECT
*,
ceil((row_number() OVER (PARTITION BY dept ORDER BY EMPID ))/ 2::numeric(5,2)) AS multiple_row_dept,
row_number() OVER (PARTITION BY dept ORDER BY EMPID ) AS single_row_dept
FROM
test_data2
) ... | First order a table by empid in a subquery,
then calculate a remainder of rowids divided by 3,
then depending on a result of calculation, return 2 or 3, using `case` expression,
like this
```
SELECT
CASE REMAINDER( rownum, 3 )
WHEN 0 THEN 2
ELSE 3
END As DeptId,
empid
FROM (
SELEC... | Oracle SQL to generate interleaved SQL results | [
"",
"sql",
"oracle",
""
] |
Assume that i have three field in my database like this :
```
ID Title MaxVisited
1 hi 6
2 bye 8
3 How? 9
4 News! 8
5 Hey 3
6 Thanks 9
```
now i want to select Title three of max value of MaxVisited.. the result which i want:
```
Thanks ... | Just select the top 3 and order by `MaxVisited` and (if necessary) the `Id` column
```
SELECT TOP 3 Title from [TableName]
order by MaxVisited, Id desc
``` | Try this
```
SELECT TOP 3 Title
From [TableName]
order by MaxVisited,Title desc
``` | Selecting three of Max() values of a field in sql server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have 4 tables here, their relationship is like the following:

For 'band' table, I have 4 columns: id, band\_name, first\_name, last\_name. (first\_name and last\_name refer to columns in 'independent artist' table).
For 'independent artist' I have... | Here's my suggestion:
Band table:
* band\_id PK
* band\_name
Artist table:
* artist\_id PK
* first\_name
* last\_name
Band\_members table:
* band\_id FK
* artist\_id FK
Acts table:
* act\_id PK
* band\_id FK
Music table:
* music\_id PK
* song\_name
* release\_year
Act\_Contents table:
* act\_id FK
* music\_... | You probably want to have a one-to-many relation between `band` and `artist` where a band may reference one or more artists (by id or artist). That way the first name, and last name stay in the `artist` table and are not duplicated in the `band` table.
As for the other problem that you are having - you can't reference... | How to make a single column refers to multiple tables | [
"",
"mysql",
"sql",
"database-design",
""
] |
I have a CLOB type column (called xml) that stores an xml document. The xml document has a tag called `<productionDate>`.
What i want to do is search the table and retrieve any row that contains an xml document that has productionDate between two dates.
I know how to read the xml tag as a value:
```
Select
xmltype(... | ## Poor-Man's Method for Optimizing Queries for File-Based Data Types
There are a number of ways to optimize storage and retrieval of file-based data types (CLOB/XML). If you're anchored to a relational database solution such as Oracle, here's some simple suggestions that use out-of-the-box functionality without havin... | You're getting the value as a string, so you should just be able to use use `to_date` or `to_timestamp`:
```
Select
to_timestamp(xmltype(xml).extract('//product/productionDate/text()').getStringVal(),
'YYYY-MM-DD HH24:MI:SS.FF "UTC"')
from myTable
```
[SQL Fiddle demo](http://sqlfiddle.com/#!4/d41d8/26159).
Y... | Oracle SQL - Selecting a date from an XML tag and casting it to a DATE type to allow comparison of the dates | [
"",
"sql",
"xml",
"oracle",
"xpath",
"oracle11g",
""
] |
So I have a mulitple select statement that goes like this.
The problem is when one of the sub select does not exist if will not return a result.
How can I make it that if it does not exist it will be null.
```
SELECT agent,
percentage1,
percentage2,
percentage3,
percentage4,
percen... | The following query changes your multiple joins to conditional aggregations. This will fix the problem that if one of the conditions is not met, then you will still get results. Doing a `cross join` in your `from` clause will result in no record if any of the queries have no rows.
I also fixed the logic in a couple of... | Try this instead
```
select agent,IsNull(p1.percentage,0.0) as Percentage1,
IsNull(p2.percentage,0.0) as Percentage2,
IsNull(p3.percentage,0.0) as Percentage3,
IsNull(p4.percentage,0.0) as Percentage4,
IsNull(p5.percentage,0.0) as Percentage5
from
(select 'Agent 01' as agent) as Agent
left join (select percentage as p... | multiple select statement return a result even if one does not exist | [
"",
"sql",
"sql-server",
""
] |
I performing an aggregation on a table, below is a snap shot of the Job table I am querying.

my query is similar to below. In reality the above derived table will have many more columns as results of multiple joins.
```
select Attribute
from Job... | Grouping this way won't give you desired result :
```
Group by Attribute, JobID
```
with that, `JobID = 34` and `JobID = 39` will be in separate group. One of several possible ways is using `INNER JOIN` and subquery to achieve that "*expected result*" picture :
```
select j.Attribute, j.JobID
from Job j
inner... | You can use aggregates with window functions so that the original rows are preserved but you can reason about the aggregate value. You need to compute the aggregate in a subquery or CTE though:
```
;With Totals as (
select *,SUM(Cost) OVER (PARTITION BY Attribute) as TotalCost
from Job
where Description = ... | Aggregation result with a unique column in SQL Server | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
Currently I am working with grails and MySQL.i want to execute my own query example "SELECT fullName from User" while clicking an anchor tag.
its my example that i worked out
```
class InsertDataController {
def index() { }
def sample() {
InsertData insertData=new InsertData();
insertData.show();
}
}
```
Do... | Instead of using `def sql = new Sql(dataSource)` in domain class,
use `def sql = Sql.newInstance(dataSource)`
Your Domain class can be modified as
```
import groovy.sql.Sql
class InsertData {
def dataSource
def show(){
def sql = Sql.newInstance(dataSource)
sql.eachRow("SELECT fullName from ... | The InsertData class would be a service (InsertDataService) and that would inject into the controller InsertDataController. The class User would be a domain class.
Controller class would then look like:
```
class InsertDataController {
def insertDataService
def index() { }
def sample() {
insertDa... | How to pass sql query in grails | [
"",
"sql",
"grails",
"grails-2.0",
"gsp",
""
] |
I've got two tables, which contain customer ages and heights.
```
Table: Ages
+-----------+------------+
|customerId | age |
+-----------+------------+
| 1 | 15 |
| 2 | 24 |
| 3 | 21 |
| 4 | 62 |
| 6 | 57 |
| 7 | 32 ... | One way to go (they are others, as always)
```
select customerId, max(age), max(height)
from
(
select customerId, age, 0 as height from Ages
UNION
select customerId, 0 as age, height from heights
) s
group by customerId;
```
see [SqlFiddle](http://sqlfiddle.com/#!2/3ca57/2) | MySql doesn't have full outer joins, but you can [simulate one](https://stackoverflow.com/questions/4796872/full-outer-join-in-mysql) with a `LEFT JOIN`, followed by a `RIGHT JOIN`, combined with a `UNION`, which will combine + eliminate duplicates:
```
SELECT Ages.age, COALESCE(Heights.height, 0)
FROM Ages
LEFT OUTE... | How can I make an SQL query that handles missing records? | [
"",
"mysql",
"sql",
"select",
"records",
""
] |
I need to obtain the rows which having same column value from the following table, I tried it the following way, but it gives me a single row only.
```
select *
from employee e
group by e.empsalary
having count(e.empsalary) > 1
```
**Table employee**
 > 1
) B ON A.empsalary = B.empsalary
``` | MySQL Select the rows having same column value | [
"",
"mysql",
"sql",
""
] |
I have a web form which several `date` fields in it, I am using `Ajax` calender for the user to enter the date, I want to restrict the user from typing in extra info other than the date or even not being able to type anything in the textbox apart the value from the calender extender. I am using ASP.NET, VB.NET and SQL ... | First you'll need to set the textbox as 'read only' in code behind, usually in Page\_Load event like this:
```
TxtDate.Attributes.Add("readonly","readonly");
```
Next, modify the design of the textbox to be like this in markup:
```
<asp:TextBox ID="TxtDate" runat="server" Width="150px"></asp:TextBox>
<a href... | Don't set `ReadOnly = True` or `Enabled = False` that will prevent the value from being posted back. You need to only prevent user interaction while allowing value to be updateable otherwise. One way is to prevent field from obtaining focus, try adding this attribute:
```
onfocus = "this.blur();"
```
For more take a ... | Textbox should only accept date | [
"",
"asp.net",
"sql",
"vb.net",
"sql-server-2008",
""
] |
how can I update 1 record based on some field? I've already created a cursor to loop through records with the same ID, but I need to update the activeFlag for the record with the most current startDate.
```
someID startDate endDate activeFlag
6 2011-07-25 9999-12-31 0
6 2013-09-22 9999-12-31... | If you order by the `startDate` you can limit the update to the first record
```
update your_table
set activeFlag = 1
order by startDate desc
limit 1
``` | If I'm understanding your criteria correctly, you can use an update query with a sub query to grab the latest (or maximum) start date value.
```
UPDATE myTable
SET activeFlag = 1
WHERE startDate = (SELECT MAX(startDate) FROM myTable);
```
However, if there are multiple rows with the same startDate, they'll all get up... | Evaluate Like Records | [
"",
"sql",
""
] |
```
SELECT wavelength,
(LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength)/
(LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance)
AS reflectance
FROM grassland1
```
It shows error like this in Postgresql
```
ERROR: division by zero
********** Error **********
ER... | Try this:
```
SELECT wavelength,
(LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength)/
(CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = O THEN 1
ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) END)
AS reflectance
FROM grassland1
``` | Use `case` then
```
SELECT wavelength,
case when (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance)=0
then 0
else ((LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength)/
(LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance))
end reflectance
FROM grassland1
``` | PostgreSQL division by zero when ordering column | [
"",
"sql",
"postgresql",
""
] |
I found many stackoverflow QnAs about consecutive days.
Still answers are too short for me to understand what's going on.
For concreteness, I'll make up a model (or a table)
(I'm using postgresql if it makes a difference.)
```
CREATE TABLE work (
id integer NOT NULL,
user_id integer NOT NULL,
arrived_... | Here is my solution to this problem using `CTE`
```
WITH RECURSIVE CTE(attendanceDate)
AS
(
SELECT * FROM
(
SELECT attendanceDate FROM attendance WHERE attendanceDate = current_date
OR attendanceDate = current_date - INTERVAL '1 day'
ORDER BY attendanceDate DESC
LIMIT 1
) tab
UNI... | You can create an aggregate with the range types:
```
Create function sfunc (tstzrange, timestamptz)
returns tstzrange
language sql strict as $$
select case when $2 - upper($1) <= '1 day'::interval
then tstzrange(lower($1), $2, '[]')
else tstzrange($2, $2, '[]') end
... | consecutive days in sql | [
"",
"sql",
"postgresql",
""
] |
The company I work for has started a new initiative in HL7 where we are trading both v2X and v3 (CDA specifically) messages. I am at the point where I am able to accept, validate and acknowledge the messages we are receiving from our trading partners and have started to create a data model for the backend storage of sa... | I would under no circumstances attempt to model anything using the HL7 v3 RIM. The reason is that this schema is very generic, deferring much of the metadata to the message itself. Are you familiar with an EAV table? The RIM is like that.
On the other hand, HL7 v2 should be a fairly simple basis for a DB schema. You c... | HL7 is not a "tight" standard inputs and expected outputs vary depending on the system you are talking to. In this case the adding in a broker such as Mirth, Rhaposdy or BizTalk is a very good idea.
What ever solution you employ make sure you can cope with "non standard" input and output as you will soon find things v... | HL7 v2X and v3 data modeling | [
"",
"sql",
"sql-server",
"hl7",
"hl7-cda",
"hl7-v2",
""
] |
I have `SQL` statement as follows:
```
Select TableB.section
from TableA left join TableB on TableA.fk = TableB.pk
group by TableB.section
```
Since this is `left join`, there is a chance that `TableB.Section` can return a *null* because a row of `TableA.fk` could be *null* and so the group by clause will return *n... | For *oracle* use `NVL()` as:
```
Select NVL(TableB.section, 'nice text')
from TableA left join TableB on TableA.fk = TableB.pk
group by NVL(TableB.section, 'nice text')
```
For *SQL Server* you can use `ISNULL(TableB.section, 'nice text')` or `COALESCE(TableB.section, 'nice text')`
I suppose there is also `IFNULL()... | You need to Apply `NVL()`/`COALESCE()` in `GROUP BY` Clause as well!
Else it would be a Syntax Error itself
```
Select NVL(TableB.section, 'No Value')
from TableA left join TableB on TableA.fk = TableB.pk
group by NVL(TableB.section, 'No Value')
``` | Giving null values a label in SQL | [
"",
"sql",
"oracle",
""
] |
Having this kind of SQL Statement, how can I remove milliseconds from the 'date\_created' column?
```
SELECT sales.id,
sales.filename,
account.description customer,
sales.uploaded,
sales.date_created
FROM account
JOIN salesStore sales
ON sales.customer_id = account.id
... | Try this
```
DATE_TRUNC('second', sales.date_created);
```
See the docs for [DATE\_TRUNC](http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC).
[postgresql doc](http://www.postgresql.org/docs/current/interactive/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC) | [The manual:](https://www.postgresql.org/docs/current/datatype-datetime.html)
> `time`, `timestamp`, and `interval` accept an optional precision value *`p`*
> which specifies the number of fractional digits retained in the
> seconds field. By default, there is no explicit bound on precision.
> The allowed range of *`p... | Remove milliseconds in SQL commands | [
"",
"sql",
"postgresql",
"timestamp",
""
] |
I have a table called `branch`
It looks something like.
```
+----------------+--------------+
| branch_id | branch_name |
+----------------+--------------+
| 1 | TestBranch1 |
| 2 | TestBranch2 |
+----------------+--------------+
```
I've set the `branch_id` as primary key.
Now my ... | > I'd like to know if I need to create a primary key for my item table?
You always1 need a key2, whether the table is involved in a relationship3 or not. The only question is what *kind* of key?
Here are your options in this case:
1. Make `{item_id}` alone a key. This makes the relationship "non-identifying" and `it... | Yes you do. The Primary key is what allows the many to one relationship to exist.
This requirement is already catered for by the branch\_id column.
The item\_id column is not required for the one-to-many relationship in your example. | Do I need a Primary Key If I'm using 1 to Many Relationship? | [
"",
"mysql",
"sql",
"database",
"database-design",
"primary-key",
""
] |
I am running a SBS 2008 with SQL Server 2008 R2
MYOB EXONET SQL Database
I am trying to find out how much our top customers are spending per month but the below query will not return a zero value if the customer has not spent, I imagine that it does not give me a zero result as there is nothing to add up in the datab... | You need `left outer join` so you get all customers:
```
SELECT DR.ACCNO,
COALESCE(SUM(Analytics_SaleInvoice.SalesValueTaxExclusive), 0) as Total
FROM DR_ACCS DR LEFT OUTER JOIN
Analytics_SaleInvoice Analytics_SaleInvoice
ON Analytics_SaleInvoice.AccountNumberAnalysis = DR.ACCNO AND
Analytic... | Try a `LEFT JOIN` instead:
```
SELECT
DR.ACCNO,
ISNULL(SUM(Analytics_SaleInvoice.SalesValueTaxExclusive), 0)
FROM DR_ACCS DR
LEFT JOIN Analytics_SaleInvoice Analytics_SaleInvoice
ON (Analytics_SaleInvoice.AccountNumberAnalysis = DR.ACCNO)
AND (Analytics_SaleInvoice.AgePeriod = 5)
WHERE (DR.X_TOPC... | Display zero value in place of null in SQL Server 2008 R2 | [
"",
"sql",
"sql-server-2008-r2",
""
] |
Here's the sceanrio...
Table CLIENT
```
CLIENT NAME
------ ----
123 Smith
456 Jones
```
Table CLIENT\_ADDRESS
```
CLIENT ADDRESS
------ -------
000 100 MAIN ST (this is a default address)
123 999 ELM ST
```
I want my result set to look like this...
```
CLIENT NAME ... | Not in a single join, but with two joins, and coalesce
```
SELECT A.CLIENT, A.NAME,
coalesce(b.ADDRESS, d.Address) Address
FROM CLIENT A
LEFT JOIN CLIENT_ADDRESS B
ON A.CLIENT = B.CLIENT
LEFT JOIN CLIENT_ADDRESS D
ON d.CLIENT = '000'
``` | You'll need another join:
```
SELECT
A.CLIENT
,A.NAME
,COALESCE(B.ADDRESS, C.ADDRESS)
FROM CLIENT A
LEFT JOIN CLIENT_ADDRESS B
ON A.CLIENT = B.CLIENT
LEFT JOIN CLIENT_ADDRESS C
ON C.CLIENT = '000'
``` | Can I do a "conditional" join in SQL | [
"",
"sql",
"db2",
""
] |
Hi I am looking to carry out a query were i have 3 different countries specified and id like to make a where statement find all attributes where the country is no = United Kingdom. Any ideas how to do this? | ```
SELECT *
FROM mytable
WHERE country <> 'United Kingdom'
``` | You can use `NOT IN`:
```
SELECT *
FROM country
WHERE name NOT IN('United Kingdom')
``` | SQL Query WHERE is not | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
I can calculate future pay dates with the following, knowing that 1/3/2013 was a pay day, and that we are paid every two weeks. This code tells me that 12/20/2013 was a payday. That's accurate.
```
declare @StartDate datetime = '1/4/13'
declare @FromDate datetime = '12/15/' + cast(year(getdate()) - 1 as char(4))
sele... | considering that it will always be either the last friday or the penultimate friday of the year, this should work:
```
declare @startdate datetime='20140110'
declare @lastdayofyear datetime='20141231'
select
case datediff(WEEK,@startdate,dateadd(day,6-datepart(w,@lastdayofyear)-7,@lastdayofyear)) % 2
when 0 then
date... | This could be done fairly easily with a [date dimension table](http://michaelmorley.name/how-to/create-date-dimension-table-in-sql-server). Using the example in the link, a query would look like this:
```
SELECT TOP 1 [Date] FROM DimDate
WHERE DATEPART(dw, [Date]) = 6 --is Friday
AND DATEPART(wk, [Date]) % 2 = 0-... | T-SQL Getting the Last Friday Payday of the year | [
"",
"sql",
"sql-server",
""
] |
I have data in database as follows:
```
+---------------------+-------------+
| CloseTime | Count |
+---------------------+-------------+
| 10.2.2014 13:19 | 1 |
| 5.12.2014 13:19 | 1 |
| 4.2.2014 13:19 | 1 |
| 2.1.2014 13:19 | 1 |
| 4.12.20... | OK, this worked for me:
```
WITH HM (HELP_MONTH) AS (
SELECT DATENAME(MONTH,DATEADD(MONTH,-1,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-2,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-3,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-4,G... | Use the same query by adding HAVING clause will gonna add records having 0 count also.
```
SELECT DATENAME(MONTH, CLOSETIME) AS CLOSEMONTH, COUNT(*) as CNT
FROM TABLE
WHERE CLOSETIME >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE())-7, '19000101')
AND CLOSETIME < DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETD... | Count for months with no records | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have the following situation 3 tables, person, job, category.
Person has a job and Job has a category. How do I get the person records from the same category.
```
public List<Person> findPplByCategory(Category category) {
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
... | ```
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<Person> e = cq.from(perdon.class);
cq.where(cb.equal(e.get("idCompany").get("i... | This is easy to do using a JPQL query
```
String query = "select P from Person P join P.job J join J.category C where C = :cat"
List<Person> = entitiyManager.createQuery(query, Person.class).setParameter("cat", myCategory).getResultList();
```
Some assumptions:
* One Person has one Job
* One Job has one Category
* ... | JPA How to build a join criteria query | [
"",
"mysql",
"sql",
"jpa",
"eclipselink",
""
] |
Every question I search for about the warning
> Warning: Null value is eliminated by an aggregate or other SET operation.
Typically people want to treat the NULL values as 0. I want the opposite, how do I modify the following stored procedure to make it return NULL instead of 1?
```
CREATE PROCEDURE TestProcedure
A... | The `sum()` function automatically ignores `NULL`. To do what you want, you need an explicit checK:
```
select (case when count(foo) = count(*) then sum(foo) end)
from #tmp;
```
If you want to be explicit, you could add `else NULL` to the `case` statement.
The logic behind this is that `count(foo)` counts the number... | Looking for a null value with `EXISTS` may be the fastest:
```
SELECT
CASE WHEN EXISTS(SELECT NULL FROM tmp WHERE foo IS NULL)
THEN NULL
ELSE (SELECT sum(foo) from tmp)
END
``` | Change aggregate functions to output NULL when a element is NULL | [
"",
"sql",
"sql-server",
"stored-procedures",
"null",
"sql-server-2012",
""
] |
I have month and year in separate columns, i want to take records between two points (ie, a start date and end date). I have month and year alone. One solution i have found is convert date,month combination into date .Say i have
```
Start month : 3 Start year : 2010
End month : 6 End year : 2013
```
I want to convert... | As **Marc B** said, End month will be hard since you need to figure out what the last day of the specified year/month is.
Try this
```
DECLARE @StartMonth INT = 3
DECLARE @StartYear INT = 2010
DECLARE @EndYear INT = 2013
DECLARE @EndMonth INT = 6
SELECT Dateadd(year, @StartYear - 2000,Dateadd(month, @StartMonth ... | SqlServer 2012 onward supports **DATEFROMPARTS**(). It can be done this way :
```
DECLARE @Month as int, @Year as int
SET @Month = 8
SET @Year = 2018
SELECT DATEFROMPARTS(@Year,@Month,'01')
```
To get last date of month you can use **EOMONTH**() as below :
```
SELECT EOMONTH(DATEFROMPARTS(@Year,@... | Convert month and year combination to date in SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I would like to display the modules in a program, along side the program as one row, instead of having multiple rows of modules for each program.
```
SELECT program.program_title as program, course_module.title as unit
FROM program_module
INNER JOIN program
ON program_module.program_id = program.id... | ```
select p.program_title,
listagg(m.module_title,',') within group (order by m.module_id) as module_title
from program_module pm
inner join program p on pm.program_id = p.program_id
inner join module m on pm.module_id = m.module_id
group by p.program_title
```
sqlfiddle here <http://sqlfiddle.com/#!4/d3652/5> | If you want separate columns, rather than a single comma-separated column, you could use a pivot. From 11g there is a built in pivot command; or you can do it the old-fashioned way:
```
SELECT program,
MAX(CASE WHEN pos = 1 THEN unit END) AS unit1,
MAX(CASE WHEN pos = 2 THEN unit END) AS unit2,
MAX(CASE WH... | Data in column instead of row | [
"",
"sql",
"oracle",
""
] |
I am working with SQL Server, I have successfully converted a table's rows into comma-separated values, now I want to convert that string of comma-separated values back to table's rows.
I have this string (`Varchar`)
```
DECLARE @str AS varchar(Max)
SET @str = '0.00,0.00,1576.95,0.00,4105.88,1017.87,0.00,6700.70'
```... | Create a function:
```
CREATE FUNCTION [dbo].[Split](@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000))
AS
BEGIN
DECLARE @Index INT
DECLARE @Slice nvarchar(4000)
-- HAVE TO SET TO 1 SO IT DOESN’T EQUAL ZERO FIRST TIME IN LOOP
SELECT @Index = 1
WHILE @Index !=0... | This question is a duplicate of a few others, but some of the accepted answers are still the inefficient WHILE loops or recursive CTEs. There are three ways to accomplish a split that won't kill performance:
* Numbers / Tally Table:
<http://www.sqlservercentral.com/articles/Tally+Table/72993/> (free
registration r... | Comma-separated String into Table's Column in SQL Server | [
"",
"sql",
"sql-server-2008",
"csv",
""
] |
I have two columns, Name and Date
```
Name Date
John 2/21/2014
Joe 2/21/2014
Sue 2/22/2014
Joe 2/22/2014
Steve 2/23/2014
John 2/23/2014
```
I need a statement that selects every Date that does NOT have a certain person.
So, for example, I need a list of dates that don't ha... | You can use `NOT IN`:
```
SELECT DISTINCT Date
FROM Table
WHERE Date NOT IN
(
SELECT Date FROM Table where Name = 'John'
)
``` | You can use a `GROUP BY` and `HAVING`:
```
SELECT Date
FROM Table1
GROUP BY Date
HAVING MAX(CASE WHEN Name = 'John' THEN 1 END) IS NULL
```
Syntax may need to be adjusted for Access.
SQL Server demo: [SQL Fiddle](http://sqlfiddle.com/#!6/53595/2/0) | SQL Select Rows Where Does not Exist | [
"",
"sql",
"ms-access",
""
] |
I have a table `EMP` with following definition:
```
EMP_ID NOT NULL NUMBER(6)
EMP_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY N... | Try like this,
```
CREATE OR REPLACE
FUNCTION count_emp(emp_nm IN VARCHAR)
RETURN NUMBER
IS
cnt NUMBER;
BEGIN
SELECT count(*)
INTO cnt
FROM emp
WHERE ename NOT IN(
SELECT regexp_substr (emp_nm, '[^,]+', 1, ROWNUM)
FROM dual
CONNECT BY LEVEL <= LE... | You can try dynamic sql:
```
CREATE OR REPLACE FUNCTION count_emp(emp_nm IN varchar)
RETURN number
IS
cnt NUMBER;
BEGIN
Execute immediate 'SELECT count(*) FROM emp WHERE emp_name NOT IN(' || emp_nm || ')' returning into cnt;
RETURN cnt;
END;
``` | pl/sql function- pass multiple varchar2 values dynamically for SELECT ... NOT IN() | [
"",
"sql",
"oracle",
"plsql",
""
] |
I've been having a bit of trouble thinking this problem through. I can't seem to define a SELECT query which is accurate enough to give me the result I want.
I am storing shift patterns in a table. These shift patterns don't have any restrictions on when they can start and finish (except that they cannot overlap each ... | You can do this with simple logic. If `StartTime < EndTime`, then you want to test for times between the two values. If `Startime > EndTime`, then you want to test for times *not* between the two values. So this solves the time problem:
```
SELECT *
FROM webreportshiftsetup
WHERE (StartTime < EndTime and time(now()) b... | If your shifts are one-day (i.e. you need to select only current day) you can do something like
```
SELECT * FROM shifts
WHERE startWeekDay = DATE_FORMAT(CURDATE(),'%W') AND NOW() BETWEEN startTime AND endTime
```
Otherwise, if your shift starts on Monday and finishes on Wednesday, and today is Tuesday, you will have... | SQL SELECT logic | [
"",
"mysql",
"sql",
""
] |
Ok, I have a complicated query to get all article details, each article has many versions. I have a need to get details of article with latest version only (ie take the max version). Here is the table:
```
+------------+-----------+----------+
| ArticleID | Detail | Version |
+------------+-----------+----------+... | I would use a CTE to create a table that contains the article id and the version id, then use that in my main query to filter down to the most recent version.
```
with latest as
(
select articleId, max(version) as version from articleTb
)
select ....
from articleTb a
inner join latestl on a.articleid = l.articleid ... | To improve performance, remove the unnecessary inline view, e.g.
```
SELECT tb1.*
FROM articleTb tb1
JOIN ( SELECT b.articleID
, MAX(b.version) AS maxversion
FROM articleTb b
WHERE b.Detail LIKE '%3'
GROUP BY b.articleID
) tb2
ON tb1.articleID = tb2.articleI... | Query1 Join with Query2 but Query2 use the result of Query1, How to do that with just 1 query? | [
"",
"mysql",
"sql",
"greatest-n-per-group",
""
] |
I want to update 50 rows in my table to the current date.
I know how to select 50 random results but I don't know how to update them.
This is what I have for the Select code:
```
SELECT TOP 50[ID]
,[Message]
,[Date]
,[Type]
,[Username]
FROM [database].[dbo].[dbTable]
ORDER BY NEWID()
```
If i... | Try this
```
UPDATE [database].[dbo].[dbTable] Set [Date] = GetDate() where [ID] IN
(
SELECT TOP 50 [ID] FROM [database].[dbo].[dbTable] ORDER BY NEWID()
)
```
**Or** else:
```
WITH q AS
(
SELECT TOP 50[ID]
,[Message]
,[Date]
,[Type]
,[U... | Try like this:
```
update [dbo].[dbTable] set date=getdate() where Id in
(
select top 50 id from dbo.dbTable order by NEWID()
)
``` | Update random top 50 rows | [
"",
"sql",
"sql-server",
""
] |
I am using the following code to insert data in an access table from SQL using a recordset. This table is further used for other operations. While this is inserting the data into the table perfectly, the time taken by this huge. Should I use any other method to insert data into the table to reduce the time taken?
```
... | 1. Create a linked table to the SQL table, say it's called `MyLinkedTable`
2. Create an Append query to append to your local Access table from your linked table. It will look something like this: `INSERT INTO MyAccessTable (Field1,Field2...) SELECT Field1,Field2... FROM MyLinkedTable;` | If you could select the data in the SQL `UPDATE` statement instead looping in `VBA` it would take a fraction of the time as all the work would be done by the server side. | Insert into an access table from SQL using recordset | [
"",
"sql",
"ms-access",
"vba",
"ms-access-2010",
""
] |
I have a database which has three tables
Messages - PK = MessageId
Drafts - PK = DraftId
History - FK = RelatedItemId
The History table has a single foreign Key `[RelatedItemId]` which maps to one of the two Primary keys in `Messages` and `Drafts`.
Is there a name for this relationship?
Is it just bad design?
... | Best practice I have found is to create a Function that returns whether the passed in value exists in either of your Messages and Drafts PK columns. You can then add a constraint on the column on the History that calls this function and will only insert if it passes (i.e. it exists).
Adding non-parsed example Code:
C... | In a short description the solution you have used is called:
**Polymorphic Association**
*Objective*: Reference Multiple Parents
*Resulting anti-pattern:* Use dual-purpose foreign key, violating first normal form (atomic issue), loosing referential integrity
*Solution:* Simplify the Relationship
[More ... | Foreign Key column mapped to multiple primary keys | [
"",
"sql",
"database",
"database-design",
""
] |
I am using codeigniter and active record. I am selecting my data over WHERE with array. Any like this. But how can I insert tags '>' and '<'? It is possible?
```
$whereQuery['service.service_end_date'] = $start;
```
Thank you for replies. | <http://ellislab.com/codeigniter/user-guide/database/active_record.html>
```
$whereQuery['service.service_end_date >'] = $start;
$whereQuery['service.service_end_date <'] = $start;
```
You can pass `> < <>` in CI where function
```
$this->db->where('field_name <', "Condition_value");
``` | This might be what you want:
Associative array method:
`$array = array('name' => $name, 'title' => $title, 'status' => $status);`
`$this->db->where($array);`
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
You can include your own operators using this method as well:
`$array = array('na... | Codeigniter active record where array | [
"",
"sql",
"codeigniter",
"activerecord",
""
] |
This is a query that is supposed to get the user's information, their project's information, and a group\_concat of all the image paths that such project is associated to. To add to this, I am only getting the information mentioned from the people the user is following.
This is, however, **only retunring one row.**
`... | > When I try to use group\_concat it just returns me one row and I do not understand why.
Because you have not used the `GROUP BY` clause in your query. When using aggregate functions like `GROUP_CONCAT` you need to tell the database about the column using which you want your data to be combined.
Currently your query... | Just use `group by` clause in your\_query
```
SELECT users.first_name, users.last_name,
users.user_id, projects.project_id,
projects.project_name, projects.project_time,
group_concat(images.image_path)
FROM users, projects, images
WHERE users.user_id = projects.user_id
AND users.user_i... | Query using group_concat is returning only one row | [
"",
"mysql",
"sql",
"database",
""
] |
I already read a lot on that topic but I´m unable to get it to work for my case.
I have the following situation:
* A list of orderitems (the main datasets I want to get)
* Articles which have a 1:1 relation to an order item
* A n:m Jointable "Articlesupplier" which creates a relation between an article and a
partne... | Well, I changed your aliases, and the subquery to which you were joining (I also modified that subquery so it doesn't use implicit joins anymore), though this changes where mostly cosmetics. The actual important change was the use of `OUTER APPLY` instead of `LEFT JOIN`:
```
SELECT OI.id
FROM dbo.IDX_ORDERITEM AS OI
I... | The error is thrown because the below piece of query
```
(SELECT TOP(1) IDX_PARTNER.id, IDX_PARTNER.abbr
FROM IDX_PARTNER, IDX_ARTICLESUPPLIER
WHERE IDX_PARTNER.id = IDX_ARTICLESUPPLIER.partner_id
AND IDX_ARTICLESUPPLIER.article_id=IDX_ARTICLE.id) AS IDX_PARTNER_SUPPLIER
```
cannot be considered as a correlat... | T-SQL Left-Join with 1 row (limi, subselect) | [
"",
"sql",
"sql-server",
"t-sql",
"join",
"left-join",
""
] |
how can i select a column from all selected tables ? like (throws an error):
```
SELECT *.id FROM table1, table2, table3, table4
```
i wouldnt do it like this, because there are a lot of tables, and they will change:
```
SELECT table1.id, table2.id, table3.id, table4.id FROM table1, table2, table3, table4
```
only ... | Why not use `UNION`, like this:
```
SELECT id FROM table1
UNION
SELECT id FROM table2
UNION
SELECT id FROM table3
UNION
SELECT id FROM table4
``` | Use Alias Names like Table and prefix that alias name with the column name
Example : TableName aliasname
then use select t1.columnname from Table1 t1
```
SELECT t1.id, t2.id, t3.id, t4.id FROM table1 t1, table2 t2, table3 t3, table4 t4
``` | MySQL - SELECT column from all tables | [
"",
"mysql",
"sql",
"select",
"join",
""
] |
I have this query
```
SELECT "items".*
FROM
"items"
INNER JOIN
item_mods ON item_mods.item_id = items.id AND item_mods.mod_id = 15
WHERE (items.league_id = 1) AND (items.item_type_id = 11) AND (num_sockets >= 2)
ORDER BY item_mods.total_value DESC
LIMIT 25
```
This is the explain <http://explain.depesz.co... | The reason your query is slow is because there are no indexes for the way you want to return the data.
Notice the "Bitmap Index Scan" where it is saying, I know you have an index but I have to look at the whole table to find the row I need (hence total row scan of up to 301742!). This is probably because of the combin... | This only shortens and cleans the syntax, but doesn't change anything substantially:
```
SELECT i.*
FROM items i
JOIN item_mods m ON m.item_id = i.id
WHERE i.league_id = 1
AND i.item_type_id = 11
AND i.num_sockets >= 2
AND m.mod_id = 15
ORDER BY m.total_value DESC
LIMIT 25;
```
A query like this i... | Ways to improve this SQL query | [
"",
"sql",
"postgresql",
"indexing",
"postgresql-performance",
"sql-limit",
""
] |
I want to compare the current row with a value in the next row. SQL has `LEAD` and `LAG` functions to get the next and previous values but I can not use them because I am using SQL Server 2008.
So how do I get this?
I have table with output
```
+----+-------+-----------+-------------------------+
| Id | ActId | Sta... | In your case, the `id`s appear to be numeric, you can just do a self-join:
```
select t.*
from table t join
table tnext
on t.id = tnext.id - 1 and
t.StatusId = 1 and
tnext.StatusId = 6 and
datediff(second, t.MinStartTime, tnext.MinStartTime) < 60;
```
This isn't quite the same minute... | Just posting a more complex join using two different tables created with Gordon's foundation. Excuse the specific object names, but you'll get the gist. Gets the percentage change in samples from one to the next.
```
SELECT
fm0.SAMPLE curFMSample
, fm1.SAMPLE nextFMSample
, fm0.TEMPERATURE curFMTemp
... | Alternate of lead lag function in SQL Server 2008 | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm fairly new to MSSQL and just have experience with some fairly basic update statements. I was wondering if someone might be able to help me with the correct syntax to do the following:
I have two tables, `F4101` and `F4102` that contain the same item IDs in the columns `IMITM (F4101)` and `IBITM (F4102)`.
Only F41... | ```
UPDATE F4102
SET IBBUYR = 1009
WHERE EXISTS (
SELECT 1
FROM F4101
WHERE IMITM = F4102.IBITM
AND IMSRTX = 'RESIN'
)
``` | ```
Update F4102
Set IBBUYR=1009
From F4102 F2
Inner Join F4101 F1 on F2.IBITM = F1.IMITM
Where F1.IMSRTX='RESIN'
``` | SQL statement to update one table if value present in another | [
"",
"sql",
"sql-server",
""
] |
I want to display information in sections with a specific interval, for example 5, 10, 15, etc. minutes.
But I want to kind of "round up" to the next value of this interval for a given DateTime
e.g.
```
declare @dateTime datetime = '2014-03-05 18:37';
select getNextDateTimeForInterval(@dateTime, 60); --> 2014-03-05... | Seems to work:
```
create function dbo.getNextDateTimeForInterval (@dt datetime, @unit int)
returns datetime
as
begin
return DATEADD(minute,(DATEDIFF(minute,0,@dt)/@unit+1)*@unit,0)
end
go
declare @dateTime datetime = '2014-03-05T18:37:00';
select dbo.getNextDateTimeForInterval(@dateTime, 60); --> 2014-03-05 19:0... | Another approach that returns the correct values for your test cases:
```
CREATE FUNCTION getNextDateTimeForInterval(@param datetime, @roundValue int)
RETURNS datetime
AS
BEGIN
DECLARE @totalMinutes int;
SET @totalMinutes = DATEDIFF(
minute
, CONVERT(date, @param)
, @param);... | Roof a DateTime to next value of a specific minute interval | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
""
] |
How can I assign a selected value to a variable so that I can reuse the value in a nested sql? For example, I may have something that looks like this:
```
select count(user_id), substr(name, 0, 5)
from users
group by substr(name, 5);
```
But in this case, the `substr` value in the select clause may be inconsistent wi... | To avoid the duplication of terms in the select list and `group by` clause, you could use a subquery:
```
select count(user_id), name_alias
from (
select user_id, substr(name, 0, 5) as name_alias
from users
)
group by name_alias;
```
It seems like overkill in this simple example, but it can be useful with complic... | If you wish to assign variables, you need to switch to PL/SQL, since you're saying you try to avoid that, then there's no variables in regular querying,unless you wish to involve server side code.
if you wish to deal with the result as a column instead you could do something like:
```
select count(t.user_id),t.name
f... | Is it possible to assign select values to variables in sql? | [
"",
"sql",
"database",
"oracle",
""
] |
I was looking for the proper SQL queries for retrieving all students enrolled in a certain course, or all courses a certain student has enrolled in, on **Moodle**.
I have found a few solutions from the Internet, and most of them suggest joining these tables:
**context, role\_assignments, course, user, role**
But th... | The first query gives you a list of users who are enroled on the course, whatever role they have assigned to them (it is possible to be enroled on a course and have no role assigned at all).
The second query shows all the users who have role 5 assigned to them at the course level. It is possible (though unusual) to ha... | The following code generates a list of all your courses together with how many students are enrolled in each. Useful to find out if you have any courses with no one enrolled.
My Answer :
```
SELECT cr.SHORTNAME,
cr.FULLNAME,
COUNT(ra.ID) AS enrolled
FROM `MDL_COURSE` cr
JOIN `MDL_CONTEXT` c... | SQL query for Courses Enrolment on Moodle | [
"",
"sql",
"database",
"moodle",
""
] |
I've got 2 tables: members and member\_logs.
Members can belong to groups, which are in the members table. Given a date range and a group I'm trying to figure out how to get the 10 days with the highest number of successful logins. What I have so far is a massive nest of subquery terror.
```
SELECT count(member_id) A... | The first subquery is totally unnecessary because you can filter by dates directly in the current table member\_logs. I also prefer a JOIN for the second subquery. Then what you are missing is grouping by date (day).
A query like the following one (not tested) will do the job you want:
```
SELECT COUNT(ml.member_id) ... | ```
SELECT count(member_id) AS `num_users`,
DATE_FORMAT(`login_date`,'%Y-%m-%d') AS `reg_date`
FROM member_logs
WHERE `login_success` = 1
and `login_date` IN
(SELECT `login_date`
FROM member_logs
WHERE `login_success` = 1
and (DATE_FORMAT(`login_date`,'%Y-%m-%d') BETWEEN '2012-02-25' and '2014... | Unknown Column in 'IN/ALL/ANY' subquery | [
"",
"mysql",
"sql",
"join",
"subquery",
""
] |
SQL 2012
I am trying to restore a Full Backup Database in my local computer. Backup has been taken from a Server Database. I tried both wizard option as well as syntax option.
```
RESTORE DATABASE MyDatabase
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\DB_Backup.bak'
WITH REPLAC... | Try this:
```
RESTORE DATABASE [MyDatabase]
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\DB_Backup.bak'
WITH MOVE 'MyDatabase_Data' TO 'D:\My Path\Data\DB_Backup.mdf',
MOVE 'MyDatabase_Log' TO 'D:\My Path\Data\DB_log.ldf',
REPLACE
```
Also check [DB Restoration Problem](http://... | You need to instruct SQL server to move the files to their correct location on your local machine - something like:
```
RESTORE DATABASE MyDatabase
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\DB_Backup.bak'
WITH REPLACE,
MOVE 'DB_Data' TO 'C:\MyData\MyDatabase_Data.mdf',
... | Database Restore | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a date column in my table i need to generate a unique rowdate for date change.I have used `CONVERT(varchar(50),cast(product as DATE),112)` but i am not getting unique for date.
My Table look likes below.
```
Product
02/22/2014
02/22/2014
02/22/2014
02/22/2014
02/23/2014
02/23/2014
02/23/2014
02/23/2014
02/23/2... | ```
select concat(replace(cast(product as date), '-', ''),
row_number() over(partition by product order by product)) as prod_id
from tbl
```
SQL Fiddle demo: <http://sqlfiddle.com/#!6/0a526/7/0> | You can use ROW\_NUMBER()
```
SELECT ROW_NUMBER() OVER( ORDER BY Product) AS rn, *
FROM your_table
```
The `ROW_NUMBER()` function would generate count starting with 1. In case you want to initialize the count from some arbitrary value say 201402221, then you can add a base count to count column like below:
```
SELE... | How to generate uniqueRowdate number for a datecolumn i? | [
"",
"sql",
"t-sql",
"sql-server-2012",
"row-number",
"date-conversion",
""
] |
I am pretty new in Microsoft **SQL server** and I am not much into databases.
I have the following doubt:
On my database I have a table named **CPE**
This table have a field (a column) named **SourceId** that is the **FOREIGN KEY** of my table.
So I think that this field have to contain the value definied in some f... | You are looking for certainly:
```
sp_help [table_name]
```
or try this query:
```
select t.name as ForeignKeytable, fk.constraint_column_id as ForeignKey_No, c.name as ForeignKeyColumn
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on ... | Try this
**Method 1 :**
```
SELECT
object_name(parent_object_id) ParentTableName,
object_name(referenced_object_id) RefTableName,
name
FROM sys.foreign_keys
WHERE parent_object_id = object_id('Tablename')
```
Or:
**Method 2 :**
```
SELECT
OBJECT_NAME(f.parent_object_id) TableName,
COL_NAME(fc.parent_... | How to discover to which table\field is linked the foreign key of a table? | [
"",
"sql",
"sql-server",
"rdbms",
"database",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.