Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
i have got two table clinical\_study and location\_countries, they both have NCT\_ID (clinical trial) field in common, i have to pull data from both tables applying a condition on first table(Gender) and then also checking for country match in the second table, i successfully managed to run the below query, but its und...
It looks like you need to add some brackets ``` select clinical_study.NCT_ID, clinical_study.BRIEF_SUMMARY, clinical_study.STUDY_TYPE, clinical_study.GENDER, location_countries.COUNTRY from clinical_study inner join location_countries ON clinical_study.NCT_ID=location_countries.NCT_ID where (clinical_study.GENDER...
I think that AND has precedence over OR so it will be evaluated first. So you can use brackets to force precedence. ``` where (clinical_study.GENDER LIKE'Male' or clinical_study.GENDER like 'Both') and location_countries.COUNTRY ='United Kingdom' ```
SQL Server Join two tables with where condition on both tables
[ "", "sql", "sql-server", "join", "" ]
Context: The accesoirescondition exist of three fixed condition values. These conditions are representing the state of the accesoires of the product. I got a GROUP BY on product.productid and would only see the most serious accesoires condition for that specific product. Desired situation: ``` PRODUCTID PRODUCTNAME...
I would add a table, rather than a redundant field, for the conditioncode like this: ``` CREATE TABLE product ( productid int, productname varchar(20) ); CREATE TABLE cond ( conditionid int, conditionname varchar(20) ); CREATE TABLE accesoires ( accesoiresid int, productid int, accesoiresname varchar(2...
Try this query: ``` select a.productid , a.productname , b.accesoiresid , b.accesoirescondition from product a left join accesoires b on a.productid=b.productid inner join ( select d.productid, min(case when d.accesoirescondition = 'defect' then 1 when d.accesoirescondi...
Order values from join with group by
[ "", "sql", "" ]
Scenario: A company has many branches in many states. A state may have more than one branch. Whenever an employee is transferred from one branch to another, an entry is made to a table like following ``` | EID | DT | BRANCH | STATE | |-----|-------------|--------|-------| | 1 | 01-JAN-2000 | A | AA ...
Here is one of the approaches to get it done: ``` select max(z.state) as state , min(z.dt) as min_date /* main query */ , max(z.dt) as max_date , trunc((max(z.dt) - min(z.dt)) / 365) as duaration from (select q.eid , q.dt /* query # 2*/ , state ...
[SQL Fiddle](http://sqlfiddle.com/#!4/e4442d/86) ``` WITH groups AS ( SELECT t1.*, ROW_NUMBER() OVER ( ORDER BY dt ) - ROW_NUMBER() OVER ( PARTITION BY state ORDER BY dt ) AS grp FROM t1 ) SELECT state, MIN( dt ) AS first_date, MAX( dt ) AS last_date, TRUNC( ( MAX( dt ) - MIN( dt...
How to get min max date per row type
[ "", "sql", "oracle", "plsql", "" ]
i have some problem about sql , i want to select the bigger warehouse\_product\_id and with same product\_id row,i have try to use please help Table: <http://postimg.org/image/mkavxnmg9/> i want to: <http://postimg.org/image/8msomu47l/>
You seem to be looking for a greatest-n-per-group solution. For a given `product_id` and `warehouse_id` pair you need to get the max `warehouse_product_id`: ``` SELECT t1.* FROM aTable t1 JOIN ( SELECT product_id, warehouse_id, MAX(warehouse_product_id) maxVal FROM aTable GROUP BY product_id, warehouse_id ) t2 O...
``` SELECT warehouse_product_id FROM [your table] where product_id="value" ``` unless I missed what you're getting at, which is entirely possible
want to select same product_id but bigger id row
[ "", "sql", "" ]
Is there any difference between `INT PRIMARY KEY` and `INTEGER PRIMARY KEY` when defining a schema for a table? When int primary key is used, I got `sqlite_autoindex` *thing* generated; when integer primary key , I got `sqlite_sequence` table generated. what's the difference? what side effects can have the first and se...
Yes, there is a difference: `INTEGER` is a special case in SQLite, when the database does *not* create a separate primary key, but reuses the `ROWID` column instead. When you use `INT` (or any other type that "maps" to `INTEGER` internally) a separate primary key is created. That is why you see `sqlite_autoindex` crea...
UPDATE: SQLite's ROWID column is now a [64-bit integer](https://www.sqlite.org/autoinc.html): > In SQLite, a column with type INTEGER PRIMARY KEY is an alias for the ROWID (except in WITHOUT ROWID tables) which is always a 64-bit signed integer. It is all explained in [SQLite 3 documentation](https://sqlite.org/datat...
Difference between INT PRIMARY KEY and INTEGER PRIMARY KEY SQLite
[ "", "sql", "sqlite", "" ]
I'm trying to get an SQL query to select all records from last month, I have this which from looking numerous places is exactly what I should need, and should work: ``` SELECT * FROM orders WHERE DATEPART(yy,DateOrdered) = DATEPART(yy,DATEADD(m,-1,GETDATE())) AND DATEPART(m,DateOrdered) = DATEPART(m,DATEADD(m,-1,GETDA...
DATEPART is a Transact-SQL function, usable with Microsoft SQL Server. From the question tags, I assume you are using MySQL as your Database Management System. Take a look at [MySQL DATEDIFF](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff)
That would not work in mysql. To translate that to mysql you could do: ``` SELECT * FROM orders WHERE YEAR(DateOrdered) = YEAR(DATE_SUB(CURDATE(), INTERVAL -1 MONTH)) AND MONTH(DateOrdered) = MONTH(DATE_SUB(CURDATE(), INTERVAL -1 MONTH)) ``` See [here](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.ht...
Error: DATEPART does not exist, frp, SQL to select last months records
[ "", "mysql", "sql", "function", "datepart", "" ]
I have a table test5.having 10000 records.there is two column in table called es\_id and cac\_id.I want to make these column exact match.if its not macthed the update cac\_is with es\_id. for example: table **`test5`** ``` es_id cac_id xxx xxx yyy yyy zzz abc ddd null bbb ...
You can simply do: ``` UPDATE test5 SET es_id = CASE WHEN es_id IS NULL THEN cac_id ELSE es_id END, cac_id = CASE WHEN cac_id <> es_id OR cac_id IS NULL THEN es_id ELSE cac_id END WHERE cac_id <> es_id OR cac_id IS NULL OR es_id IS NULL; ``` This assumes that when es\_id is...
How about ``` UPDATE test5 SET cac_id = es_id; ``` 100K records isn't all that much, and you want them all the same anyway, so why check for the condition? Assuming this isn't a recurring process, of course.
compare two column of a tableand if not matched then update in oracle sql
[ "", "sql", "oracle", "" ]
I have a difficulty because when comparing two fields in a subquery, although the fields are identical i.e. they both have NULL values, the comparison returns a FALSE result Therfore NULL = NULL is returning FALSE Now I know that NULLs are supposed to be compared with the IS operator, however when I compare two field...
As the others have pointed out, `NULL` cannot be compared with `NULL`. In Postgres you can shorten your expressions by using the operator `IS DISTINCT FROM` which is a null-safe replacement for `<>`. In your case you'd need to use `IS NOT DISTINCT FROM` to compare for equality (looks a bit the wrong way round but unfo...
First of all, use aliases for your tables, your query will be MUCH more readable: ``` select * from fts.fts_customers_data_50360001 as d where d.record_type = 15 and d.mid = 103650360001 and not exists ( select * from fts.temp_fees_50360001 as f where f.record_type ...
SQL: field = other_field returns false even if they are identical (NULL values)
[ "", "sql", "postgresql", "null", "comparison", "" ]
I have an email dispatch table that needs to hold in excess of 4 million rows. A particular report also needs to reference this table to produce some stats, and it's taking longer than I would like to run (Currently around 30 seconds). I have checked the estimated execution plan, which shows that 94% of the cost is in...
Don't use this approach: ``` WHERE @MailCampaignId IS NULL OR MailCampaignId = @MailCampaignId ``` Instead use: ``` IF @MailCampaignId IS NULL BEGIN SELECT .. FROM ... END ELSE BEGIN SELECT .. FROM ... WHERE MailCampaignId = @MailCampaignId END ``` I...
The `IS NULL OR` part is what's messing with your performance, because if the input is NULL you're asking for every row which is the scan. I'd remove that part if possible and see if that doesn't help, and if not possible, then I'd rethink on when I'd need all of them and consider an alternate approach for example mul...
SQL Server Query Optimisation - What is the optimal index here?
[ "", "sql", "sql-server", "indexing", "" ]
I am using MySQL. In my database I have the following tables: 1. A `student` table. The primary key of this table is `sid` . 2. A `high_school` table. Primary key is `hid` . 3. A `university` table. Primary key is `uid` . Then: * There is a **joint table** for `student` & `high_school`, the table is named `joint_tab...
``` SELECT s.* FROM students s INNER JOIN joint_table_A a ON s.sid = a.sid INNER JOIN joint_table_B b ON s.sid = b.sid WHERE a.hid = 3 AND b.uid = 1 ``` To try and explain the difference between `LEFT JOIN` and `INNER JOIN` for this query: Imagine you have 1000 records in `students` but there is only 50 records in...
``` SELECT student.* FROM student JOIN joint_table_A USING (sid) JOIN joint_table_B USING (sid) WHERE joint_table_A.hid = 3 AND joint_table_B.uid = 1 ```
SQL Query for : rows linked by one joint table link to another joint table
[ "", "mysql", "sql", "" ]
I'm a SAS beginner and I'm curious if the following task can be done much more simple as it is currently in my head. I have the following (simplified) meta data in a table named user\_date\_money: User - Date - Money with various users and dates for every calendar day (for the last 4 years). The data is ordered by U...
I think the easiest way is to use PROC EXPAND: ``` PROC EXPAND data=user_date_money out=cma; ID date; BY user; CONVERT money=MEAN / transformin=(setmiss 0) transformout=(movave 5); RUN; ``` And as mentioned in John's comment, it's important to remember about missing values (and about beginning and ending observ...
If your particular need is simple enough, you can calculate it using PROC MEANS and a multilabel format. ``` data mydata; do id = 1 to 5; datevar = '01JAN2010'd-1; do month = 0 to 4; datevar=intnx('MONTH',datevar,1,'b'); sales = floor(500*rand('normal',7))+1500; output; end; end; run; proc format; v...
sas - calculate moving average for grouped data with BY statement
[ "", "sql", "sas", "datastep", "" ]
I want to select the country with the highest population. This is my query: ``` SELECT continent, name, population FROM country HAVING population = MAX(population); ``` Somehow it returns 0 rows. If i use a nested query it works: ``` SELECT continent, name, population FROM country WHERE population = (SELECT MAX(pop...
``` Select continent, name, sum(population) As sumPop From country Group By continent Order By sumPop Desc Limit 1; ``` Wow, after lots of trial and error, I see what the issue is now. First, your initial query seems wrong. With the database table you are using, you can have multiple regions within the continent. Ther...
There are a couple of things wrong with it. In fact, in some db engines it would throw an error. First, the having keyword is used with aggregate results, not fields. Here is an example. ``` select field1, count(*) records from sometable group by field1 having records > 10 ``` Note that some databases will not allow...
mysql world database: select country with max population
[ "", "mysql", "sql", "" ]
I have a table that looks like this in an Oracle DB: ``` TransactionID Customer_id Sequence Activity ---------- ------------- ---------- ----------- 1 85 1 Forms 2 51 2 Factory 3 ...
``` select t1.* from your_table t1 inner join ( select customer_id, max(Sequence) mseq from your_table group by customer_id ) t2 on t1.customer_id = t2.customer_id and t1.sequence = t2.mseq ```
Please Try it ``` with cte as ( select Customer_id,MAX(Sequence) as p from Tablename group by Customer_id ) select b.* from cte a join Tablename b on a.p = b.Sequence where a.p = b.Sequence and a.Customer_id=b.Customer_id order by b.TransactionID ```
Sorting by max value
[ "", "sql", "oracle", "" ]
This does not compile in SQL server 2012: ``` with q as ( select row_number() over (order by ActionName) as rn, * from [xxx].[dbo].[Action] a ) ``` It says 'Incorrect syntax near the keyword 'as'. Should this compile and if not how to fix this?
start your statement with `;` try this ``` ;with q as ( select row_number() over (order by ActionName) as rn, * from [xxx].[dbo].[Action] a ) SELECT * FROM q ``` and CTE should be followed by a SELECT statement.
``` ;with q as ( select row_number() over (order by a.ActionName) as rn, a.* from [xxx].[dbo].[Action] a ) ```
invalid syntax in SQL server query
[ "", "sql", "sql-server", "" ]
Is there any existing (non-proprietary) solution how to mirror current day data onto separate disk with minimum delay (under second), so that I can use smaller, non redundant but more expensive disk for high rate of reads? (specifically for SQL Server 2012) More background: * We have a transnational DB that needs to ...
You can use an indexed view to store the current days data on a separate dataspace. You'll have to build a new view each day so you may want to use a synonym to do the actual switching so as to avoid locks on insert while creating the view. Make sure you end date the filter on the column. This is how i would do it usin...
You say in the comments that the data to be queried fits in RAM on the SQL Server box. This means that SQL Server will never perform even a single physical IO to read data. It all comes from its buffer pool. Read latencies will be extremely low. Disk performance will not matter at all. If you properly structure and in...
SQL Server : mirror/cache current day data for performance reasons
[ "", "sql", "sql-server", "performance", "caching", "mirroring", "" ]
HI i want to update all records in my table when i am having an id of a specific record with the following sql: ``` Update table1 SET field2 = field2 + 1 Where id = 129; Update table1 SET field2 = field2 -1 where feild2 > (SELECT feild2 from table1 WHERE id = 129); ``` But MYSQL says You can't specify target table 't...
Try this one by giving new alias to your subquery ``` Update table1 SET field2 = field2 -1 where feild2 > (SELECT t.feild2 FROM (SELECT feild2 from table1 WHERE id = 129) t) ```
Try this: ``` SET @var =(SELECT feild2 from table1 WHERE id = 129); Update table1 SET field2 = field2 -1 where feild2 > @var; ```
Update all recored below current record given by id
[ "", "mysql", "sql", "sql-update", "" ]
I want to limit a column that it can only have a value when another column has a value. example: (this doesn't work) ``` create table testConstraint ( col1 int not null identity(1, 1) primary key, col2 int, col3 int check (col2 is not null), col4 int) ``` This is not possible because he cannot reference another colu...
You can write a trigger. Also, you can try this (1) ``` ALTER TABLE TestConstraint ADD CONSTRAINT CK_TestConstraint CHECK (NOT ( (col3 is not null) and (col2 is null) )) GO ``` or this (2) ``` ALTER TABLE TestConstraint ADD CONSTRAINT CK_TestConstraint CHECK ( ((col3 is not null) and (col2 is not null)) ...
Only simple logic is required, plus it needs (as per your second attempt) to be a table check constraint, so you can't declare it inline with the declaration of `col3`: ``` create table testConstraint ( col1 int not null identity(1, 1) primary key, col2 int, col3 int, col4 int) GO alter table testConstraint add const...
SQL Check constraint on column referencing other columns
[ "", "sql", "sql-server", "constraints", "" ]
I have a table and I want to group rows that have at most x difference at col2. For example, ``` col1 col2 abg 3 abw 4 abc 5 abd 6 abe 20 abf 21 ``` After query I want to get groups such that ``` group 1: abg 3 abw 4 abc 5 abd 6 group 2: abe 20 ...
For Oracle (or anything that supports window functions) this will work: ``` select col1, col2, sum(group_gen) over (order by col2) as grp from ( select col1, col2, case when col2 - lag(col2) over (order by col2) > 1 then 1 else 0 end as group_gen from some_table ) ``` Check it on [SQLFiddle](http://sqlfi...
This should get what you need, and changing the gap to that of 5, or any other number is a single change at the @lastVal +1 (vs whatever other difference). The prequery "PreSorted" is required to make sure the data is being processed sequentially so you don't get out-of-order entries. As each current row is processed,...
SQL - Group by numbers according to their difference
[ "", "sql", "database", "oracle", "group-by", "" ]
I have username which is manually entered by diffrent end users. There is no validation mechanism while inputting username hence there could be spelling error . For example user can enter Tina,Teena for same username . I need to return Tina when i Input Tina or vice versa. Elaborately ``` SELECT * FROM tbl where wher...
You could investigate the `SOUNDEX` function in T-SQL. It would match Teena to Tina for instance (and visa-versa). See <http://technet.microsoft.com/en-us/library/ms187384.aspx> As the function name suggests, it matches words that sound the same. So, although it would match Tina to Teena, it wouldn't match Tina to Si...
``` SELECT name FROM (SELECT 'tina' AS name UNION ALL SELECT 'teena' AS name UNION ALL SELECT 'tena' AS name)tmp WHERE Soundex(name) LIKE '%' + Soundex('tina') + '%' ```
matching similar text in sql server
[ "", "sql", "sql-server", "pattern-matching", "" ]
Hey guys I'm using this query to get the maximum value of a table that uses auto increment ``` SELECT table_schema, table_name, data_type, ( CASE data_type WHEN 'tinyint' THEN 255 WHEN 'smallint' THEN 65535 WHEN 'mediumint' THEN 16777215 WHEN 'int' THEN 4294967295 WHEN 'bigi...
The `>>` operator is a bitwise right-shift. An `INT UNSIGNED` for example has a max value of 4294967295, which is 232-1, or 11111111111111111111111111111111 in base 2. But the signed `INT` uses one of those bits for a sign bit, so the max value of a signed integer is 2147483647, which is 231-1, or 0111111111111111111...
The double angle brackets (greater than signs) are a binary shift operator. If the column type is an unsigned integer, for example, it will shift 1 position (which essentially squares the number), and if it is a regular signed integer, it will not shift at all. A signed integer uses one bit to indicate whether the numb...
Mysql Query to get max value of tables using auto increment
[ "", "mysql", "sql", "linux", "bash", "shell", "" ]
This a simple my table ``` +-----------+----------------+-----------+ | id | date | meter | ------------+----------------+-----------+ | 1 | 2103-11-01 | 5 | | 2 | 2103-11-10 | 8 | | 4 | 2103-11-14 | 10 | | 6 | 2103-11-20 | 1...
Edit: I got it: ``` select meters1.date as date1, min(meters2.date) as date2, meters1.meter as start, meters2.meter as end, (meters2.meter - meters1.meter) as amount from meters meters1, meters meters2 where meters1.date < meters2.date group by date1; ``` Outputs: ``` +------------+------------+-------+-----+...
If it's SQL server try it this way ``` WITH cte AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY date) rnum FROM table1 ) SELECT c.date date1, p.date date2, c.meter [start], p.meter [end], p.meter - c.meter amount FROM cte c JOIN cte p ON c.rnum = p.rnum - 1 ``` Here is **[SQLFiddle](http://sqlfiddle.com/#!3/ad...
get amount between range
[ "", "mysql", "sql", "sql-server", "" ]
Here's the test table for my question : ``` CREATE TABLE document ( id integer NOT NULL, name character varying(120) NOT NULL, owner_id bigint DEFAULT 0 NOT NULL, doc_type_id smallint DEFAULT 1 NOT NULL, archived boolean DEFAULT false NOT NULL, insert_date timestamp without time zone DEFAULT no...
``` with cte_ages as ( select extract(day from (modify_date - insert_date))::int as age from document ), cte_groups as ( select case when g.age = 1 then 0 else g.age end as gr_start, g.age + 4 as gr_end from generate_series(1, (select max(age) from cte_ages), 5) as g(age) ) selec...
I'm sorry i do not know postgres but if you can convert this to postgres, it will work: ``` SELECT count(*) FROM document WHERE (TO_DAYS(modify_date) - TO_DAYS(insert_date)) < 11 AND (TO_DAYS(modify_date) - TO_DAYS(insert_date)) > 5 ``` This query counts the number of documents modified between 6 and 10 days. ...
Select a count of rows, order by dynamic ranges of time intervals in PostgreSQL
[ "", "sql", "postgresql", "count", "range", "intervals", "" ]
Say I have three tables: ``` TABLE A idA variable 1 Number of hats 2 Number of scarves 3 Number of mittens TABLE B idB name 1 Andy 2 Betty 3 Cedric 4 Daphne TABLE C idA idB value 1 1 15 1 2 2 1 3 89 2 1 10 ...
The following query works: ``` SELECT B.name, A.variable FROM B CROSS JOIN A LEFT JOIN C ON C.idA = A.idA AND C.idB = B.idB WHERE C.value IS NULL ``` Its the `CROSS JOIN` that is key, it says `JOIN` every record in `B` to every record in `A`. Once you've done that you can easily check which combinations of `idA` and ...
``` select idA, variable from a where idA not in (select idA from c where idB = 1) ```
SQL Query to match unlinked data
[ "", "mysql", "sql", "" ]
In my SQL Server 2008 I've got two tables. 1. Table: All kinds of Users with unique ID's 2. Table: Blacklisted Users with ID's Now I'd like to get all Users that are not on the blacklist. Just doesn't work like I want it to ``` SELECT A.ID, B.ID FROM Users AS A INNER JOIN Blacklist AS B ON A.ID != B.ID ``` Can some...
If you expect it to not to be in Blacklist, you won't have any data to select from blacklist in select statement ``` SELECT A.* FROM Users A Where A.ID NOT IN (Select Id From Blacklist ) ``` If you wish, read more about [Subqueries with NOT IN](http://technet.microsoft.com/en-us/library/ms189062%28v=sql.10...
What you want is an anti-join, something like this: ``` SELECT A.ID, B.ID FROM Users AS A LEFT JOIN Blacklist AS B ON A.ID = B.ID WHERE B.ID IS NULL ``` That is, we perform the join, and then in the `WHERE` clause we apply a filter which eliminates rows where the join was successful. Your original query doesn't work...
Table without ID's in other Table
[ "", "sql", "sql-server", "select", "" ]
I'm currently using GUIDs as a `NONCLUSTERED PRIMARY KEY` alongside an `INT IDENTITY` column. The GUIDs are required to allow offline creation of data and synchronisation - which is how the entire database is populated. I'm aware of the implications of using a GUID as a clustered primary key, hence the integer cluste...
Generally speaking, it is preferable to use INT for Primary Key / Foreign Key fields, whether or not these fields are the leading field in Clustered indexes. The issue has to do with JOIN performance and even if you use UNIQUEINDENTIFIER as NonClustered or even if you used NEWSEQUENTIALID() to reduce fragmentation, as ...
You can also create foreign keys against unique key constraints, which then gives you the option to foreign key to the `ID` identity as an alternative to the Guid. i.e. ``` Create Table SomeTable ( UUID UNIQUEIDENTIFIER NOT NULL, ID INT IDENTITY(1,1) NOT NULL, CONSTRAINT PK PRIMARY KEY NONCLUSTERED (UUID...
SQL Guid Primary Key Join Performance
[ "", "sql", "sql-server", "database-design", "azure-sql-database", "" ]
Just trying to insert data from 5 cells via a VBA script, into a column on an SQL server 08 database. So basically I have 1 table with 4 columns, I want to insert multiple sets of data into the columns at once which would insert data into the DB with the below result.. ``` Server Name Middleware Version License ...
I believe the columns you specify in your INSERT statement are duplicated and therefore not correct. Try: ``` item4 = item4 & " [server_name],[middleware],[version],[license]" ``` Update: Your SQL statement should look like this: ``` INSERT INTO [IndustrialComp].[dbo].[Middleware]([server_name],[middleware],[versio...
I am assuming the data is in Excel. If so, just loop through the rows. Also, it's seems that your val1, val2 etc. don't match the example. Maybe you meant val3 to be D126 and val4 to be E126. I will assume that. Here is the corrected code: ``` Dim sSQL as string Dim i as long i=0 while ActiveSheet.Range("B126").offse...
Inserting multiple values into a SQL database from EXCEL through VBA script
[ "", "sql", "sql-server", "vba", "sql-server-2008", "excel", "" ]
I have a MySQL like the following: ``` Events +----+------+--------------------------------+ | id | name | sites_id | created | +----+------+--------------------------------+ | 1 | test | 1 | 2013-11-01 00:00:00 | | 2 | test | 1 | 2013-11-02 00:00:00 | | 3 | test | 2 | 2013-11-13 00...
Try something like this: ``` SELECT DISTINCT e1.* FROM events e1 INNER JOIN events e2 ON e1.sites_id = e2.sites_id AND e1.id <> e2.id WHERE ABS(datediff(e1.created, e2.created)) <= 2; ``` `sqlfiddle demo` This gives you the result: ``` ID NAME SITES_ID CREATED 2 test 1 November, 02 2013 00:0...
I've not syntax checked this (so see it as more of a guideline): ``` SELECT DISTINCT t1.id , t1.name , t1.sites_id , t1.created FROM Events t1 INNER JOIN Events t2 ON (t2.created BETWEEN DATE_ADD(t1.created, INTERVAL -2 DAY) AND DATEADD(DAY, INTERVAL 2 DAY)) AND t1.sites_id = ...
MySQL: Select rows that are in a date range of each other
[ "", "mysql", "sql", "database", "" ]
Am new to vertica. My need is to write a trigger to insert into the history table whenever table update occurs. It is simply possible in MSSQL. like vise is my need and can any body suggest some direct links or details the steps am there is less time for me to investigate into and the searches didn't resulted producti...
Vertica doesn't support triggers. This may seem strange if you're coming from another database platform, but the fact is Vertica was designed for analytical reporting applications, while triggers are more about transaction processing. It is my impression that most Vertica users (including my company) process transacti...
I think you should look into external UDF. sky's the limit !
how to write vertica trigger
[ "", "asp.net", "sql", "triggers", "vertica", "" ]
What is the fastest regarding performance way to check that integer column contains specific value? I have a table with 10 million rows in postgresql 8.4. I need to do at least 10000 checks per sec. Currently i am doing query `SELECT id FROM table WHERE id = my_value` and then checking does `DataReader` have rows. But...
You can select `COUNT` instead: ``` SELECT COUNT(*) FROM table WHERE id = my_value ``` It will return just one integer value - number of rows matching your select condition.
You need two things, As Marcin pointed out, you want to use the `COUNT(*)` if all you need is to know how many. You also need an index on that column. The index will have the answer pretty much right at hand. Without the index, Postgresql would still have to go through the entire table to count that one number. ``` C...
Does column of integers contains value
[ "", "sql", "performance", "postgresql", "" ]
I have a query: ``` select count(distinct RID) from MASTER_MOVIEVOD as M inner join RID_GENRE_MOVIEVOD as RG inner join GENRE_MOVIEVOD as G on M.RID=RG.RID and RG.GENRE_SR_NO=G.GENRE_SR_NO where M.UPDATE_PRESENT=1 and M.CLIP_TYPE=220 and M.PCAT=2 and G.GENRE_NAME!='Drama'; ``` It gives me error > Error...
This is because SQL doesn't know which `RID` to select `M.RID` or `RG.RID`, the ambiguity comes from here. You have to choose one of them instead of `RID`: ``` select count(RG.RID) from MASTER_MOVIEVOD as M .. ```
Add table identifier to `count`, because 2 of your tables has column `RID` you have to specify which one you want to use in your query ``` select count(distinct M.RID) from MASTER_MOVIEVOD as M inner join RID_GENRE_MOVIEVOD as RG inner join GENRE_MOVIEVOD as G on M.RID=RG.RID and RG.GENRE_SR_NO=G.GENRE_SR_NO where...
Sql error Error: ambiguous column name
[ "", "sql", "c", "sqlite", "" ]
so I have 2 tables Table 1: Languages ``` | language_id | language | ------------------------- | 1 | java | | 2 | c | ``` Table 2: People ``` | person_id | person_name | expert_lang | years_experience | ------------------------------------------------------------- | 1 | Neil ...
You might want to try joining the tables ``` SELECT language, SUM(years_experience) as total_years_experience FROM languages INNER JOIN people ON languages.language_id=people.expert_lang GROUP BY expert_lang ```
Try this... ``` SELECT l.languna ,SUM(p.years_experience) FROM Languages l INNER JOIN People p ON l.lagu_id=p.expert_lang GROUP BY l.languna ```
SQL wringing a JOIN
[ "", "sql", "" ]
I was given an interview question and I cannot resolve it. I'm not in the SQL field, and it was more to show problem solving ability than SQL ability. I'd still like to figure it out though! It was in MS SQL server, but a generic SQL answer is acceptable. I have 3 tables: Sales, Customers, Products and NO NULL values...
If you want the list sorted from paid the most to paid the least, add: ``` ORDER BY SUM(Sales.Number_Purchased * Products.Product_Price) DESC ``` Additionally, you have to change some of the JOIN conditions, since you are not establishing the correct connection between the tables. And since you are doing this in MS-...
I'd prefer to approach this question in the following steps. First of all, find out the total of each purchase done by all the customers. ``` SELECT Customer_ID, SUM (Sales.Number_Purchased * Products.Product_Price) FROM Sales INNER JOIN Products ON Products.Product_ID = Sales.Product_ID GROUP BY Customer_ID ``` The...
SQL Query for three tables with calculation
[ "", "sql", "sql-server", "" ]
Is there any good method to get the count of different product once. for example ``` /* the table like */ id count product 1 5 a 2 2 b 3 6 c 4 2 a ...... ``` I want to get the sum of product use one sql command. because the ...
``` Select product, sum(count) from table_name group by product ``` You might want to go through tutorial of group\_by clause <http://www.techonthenet.com/sql/group_by.php>
i dont know if you looking for pivote result as you done in your question , if yes use this ``` SELECT Sum(CASE WHEN ( product = 'a' ) THEN ` count ` ELSE 0 END)AS a, Sum(CASE WHEN ( product = 'b' ) THEN ` count ` ELSE 0 END)AS b, ...
Sql sum of count field with different product name once
[ "", "mysql", "sql", "sql-server", "" ]
i have the two tables, Payment Table and Person Table, a person por month can have more than one payment, so i want so sum all "amount" fields from a parson per month and per year, if there is no payment the result should be 0 and ID of the person should appear in the month. i am almost there, but in my curreny query ...
Since you are using the isnull function on o.date I assume this means there are nulls in this column. If so, you need to account for this within your group by clause, e.g. "group by months.monthno, c.idperson, isnull(year(o.date),2013)".
You shouldn't group by `o.Date`, but only by the month of the date, which you already have included as `months.monthno`.
SQL Query to sum by month
[ "", "sql", "" ]
EDIT: I'm using the PROC SQL functionality in SAS. I'm trying to overwrite data in a primary table with data in a secondary table if two IDs match. Basically, there is a process modifying certain values associated with various IDs, and after that process is done I want to update the values associated with those IDs in...
One answer in SAS PROC SQL is simply to do it as a left join and use COALESCE, which picks the first nonmissing value: ``` data class; set sashelp.class; run; data class_updates; input name $ height weight; datalines; Alfred 70 150 Alice 59 92 Henry 65 115 Judy 66 95 ;;;; run; proc sql; create table class as select ...
Do you really want to insert new data? Or update existing rows? If updating, join the tables: ``` UPDATE PT SET PT.PRICE = ST.PRICE, PT.IN_STOCK = ST.IN_STOCK FROM PRIMARY_TABLE PT JOIN SECONDARY_TABLE ST ON PT.PROD_ID = ST.PROD_ID ```
Overwrite data in one table with data from another if two keys match
[ "", "sql", "sas", "" ]
I've got three tables: `department`, `employee` and `telephone` **`employee`** has columns `EmpNo`, `Surname`, `Firstname` and `DeptNo`. **`telephone`** has columns `EmpNo` and `Extension`. **`department`** has columns `DeptNo` and `DeptName`. What I am trying to get is the full name, department name and telephone...
To fix your problem, move one of the `ON` clauses before the next `JOIN` ``` SELECT e.Firstname, e.Surname, d.DeptName, t.Extension FROM employee AS e INNER JOIN department AS d ON e.DeptNo = d.DeptNo INNER JOIN telephone AS t ON t.EmpNo = e.EmpNo; ```
The ON clause must follow the JOIN that it is modifying. So: `INNER JOIN department d ON e.DeptNo = d.DeptNo` and `INNER JOIN telephone t ON t.EmpNo = e.EmpNo;`
using multiple table in SQL
[ "", "sql", "" ]
I believe I have the right syntax for SQL plus command, I have tried different ways to do it but I am getting the same error message. I don't know why i am getting this "missing right parenthesis error" any help will be appreciated thank you in advance. here is my code: ``` create table PUBLISHERS ( NAME varchar2(50) ...
The `integer` data type does not use a length qualifier. `integer` is equivalent to `number(38,0)`. ``` SQL> ed Wrote file afiedt.buf 1 create table PUBLISHERS ( 2 NAME varchar2(50) primary key, 3 address varchar2(50), 4 phone integer 5* ) SQL> / Table created. ``` If you want to limit the size, use a...
`INTEGER` is not a Oracle Built-In data type. It is just a ANSI format that is supported in oracle. The oracle representation of INTEGER is NUMBER (38). Use `NUMBER` datatype instead. ``` CREATE TABLE publishers( name VARCHAR2(50) PRIMARY KEY, address VARCHAR2(50), phone NUMBER(10) ); ```
Error at line 1: ORA-00907: missing right parenthesis
[ "", "sql", "oracle", "" ]
I am new to SQL so I am fumbling here a bit. I have the following table: ``` Entered Generalist Item 12/31/2012 07:26:50 Tom Smith RTW/Updates 12/31/2012 07:30:10 Terrie Bradshaw Posters 12/31/2012 07:38:16 Jen Lopez Client Assistance/Request 12/31/2012 ...
I believe this should work (where the @ variables are the parameters passed to your procedure) ``` SELECT MIN(entered), generalist, item FROM dataTable WHERE item = @itemParm AND entered BETWEEN @enteredStart AND @enteredEnd GROUP BY generalist, item ```
I May not understand what you want, but if you want to get one person back based on the minimum date, you need to work out the minimum date, and use that to find that person: ``` select * from datatable where entered = ( select min(entered) as MinDate from DataTable where Item = 'RTW/Updates' ) and item = 'RTW/Upda...
SQL statement to find Min Date
[ "", "sql", "sql-server", "" ]
I would like to delete all duplicates in the SQL Table that have more than one ID for a single value in ColumnName (or several rows with same ColumnName value). Here is SQL for delect for one ColumnName values: ``` DELETE FROM MyDataTable WHERE ColumnName = 'UniqueComnName1' AND ID <> (SELECT TOP 1 ID FROM MyDataTabl...
You can do this with two little queries: ``` SELECT MIN(ID) AS ID INTO #tmpTable FROM MyDataTable GROUP BY ColumnName DELETE FROM MyDataTable WHERE ID NOT IN (SELECT ID FROM #tmpTable) ```
Run this and let me know your result: ``` DELETE FROM MyDataTable WHERE ID != (SELECT MAX(ID) FROM MyDataTable A WHERE A.ColumnName = MyDataTable.ColumnName) ``` This query will keep the record that having the ID equals the MAX (id) of records that having the same ColumnName.
Delete rows with identical ColumnName value in a SQL Table?
[ "", "sql", "sql-server", "duplicates", "" ]
Is it possible to express the statment below by ANSI SQL? Since the example below belongs to PL/SQL. Thanks in advance. ``` SELECT department_id, MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) "Worst", MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) "Best" FROM employees GROUP BY departme...
This returns the same result (as far as I can tell) but does not need a join and is ANSI SQL: ``` select department_id, min(case when min_comm = 1 then salary end) as worst, max(case when max_comm = 1 then salary end) as best from ( select department_id, salary, dense_rank() over (p...
You can use self-joins instead of analytics in most cases. Here's an equivalent of your `MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct)`: ``` SELECT department_id, MAX(salary) FROM employees e WHERE (department_id, commission_pct) IN (SELECT department_id, MAX(commission_pct) ...
how to express DENSE_RANK with ANSI SQL?
[ "", "sql", "oracle", "plsql", "ansi-sql", "" ]
I've inherited a SQL Server based application and it has a stored procedure that contains the following, but it hits timeout. I believe I've isolated the issue to the SELECT MAX() part, but I can't figure out how to use alternatives, such as ROW\_NUMBER() OVER( PARTITION BY... Anyone got any ideas? ## Here's the "off...
[UNSOLVED] But I've moved on! Thanks to everyone who provided answers / suggestions. Unfortunately I couldn't get any further with this, so have given-up trying for now. It looks like the best solution is to re-write the application to UPDATE the latest data into into a different table, that way it's a really quick a...
SQL performance problems are seldom addressed by rewriting the query. The compiler already know how to rewrite it anyway. The problem is always indexing. To get `MAX(StatusTime ) ... GROUP BY BID` efficiently, you need an index on `BData(BID, StatusTime)`. For efficient seek of `WHERE B.ICID = 2` you need an index on `...
SELECT MAX() too slow - any alternatives?
[ "", "sql", "sql-server", "timeout", "max", "" ]
I have a table and there's been some duplicates entered into it. I don't want to remove the duplicates but I want to set an indicator on the some of the records which are not the latest entry (the highest reviewid is the latest) My table is as follows: ``` ReviewId |ClientID | CommunicationSent 17023| 1950943...
I think this update will do it for you: ``` UPDATE T SET communicationSent = 1 FROM TABLE T INNER JOIN ( SELECT MAX(reviewId) AS 'reviewId', clientID FROM TABLE GROUP BY clientID ) T2 ON T.clientId = T2.clientId AND T.reviewId < T2.reviewId ```
I think this should do it: ``` update table1 set CommunicationSent = 1 where reviewid not in ( select max(reviewid) from table1 group by clientid ) ``` Sample [SQL Fiddle](http://www.sqlfiddle.com/#!6/48858/8)
Update table field in database depending on whether it's the latest entry
[ "", "sql", "t-sql", "" ]
I would like to delete all rows in a table that have a unique value in the `setid` column. I can select them like this: ``` select * from imagesets as a where (select count(*) from imagesets as b where a.setid = b.setid) = 1 ``` What's the best way to delete them? Is there a better way to select them?
I think the following will work in MySQL: ``` delete i from imagesets i join (select setid, count(*) as cnt from imagesets group by setid having count(*) = 1 ) set1 on i.setid = set1.setid; ```
``` CREATE TEMPORARY TABLE to_delete AS SELECT setid FROM imagesets GROUP BY setid HAVING COUNT(*) = 1; DELETE imagesets FROM imagesets NATURAL JOIN to_delete; DROP TABLE to_delete; ``` The last line is optional. Temporary tables are removed automatically by the end of the session. Aparently this works too: ```...
How should you delete rows with a unique value?
[ "", "mysql", "sql", "" ]
I would like to restrict the selection on the nested query only to what is the main query select. But while I try to do that, it returns error. Please see the query below: ``` SELECT DISTINCT A.VBELN, C.MBLNR FROM LIKP AS A INNER JOIN VBUK AS B ON B.MANDT = A.MANDT AND B.VBELN = A.VBELN LEFT JOIN ( SELECT DIS...
Try the [`LATERAL` keyword](http://pic.dhe.ibm.com/infocenter/db2luw/v10r5/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0059206.html), like so: ``` ... INNER JOIN VBUK AS B ON B.MANDT = A.MANDT AND B.VBELN = A.VBELN LEFT JOIN LATERAL ( -- <<< here SELECT DISTINCT MANDT, XBLNR, MBLNR ... ```
I've never used db2, so there's probably a better way to optimize this, but you could always just repeat the outer select inside: ``` SELECT DISTINCT A.VBELN, C.MBLNR FROM LIKP AS A INNER JOIN VBUK AS B ON B.MANDT = A.MANDT AND B.VBELN = A.VBELN LEFT JOIN ( SELECT DISTINCT MANDT, XBLNR, MBLNR FROM MKPF AS...
Nested query selection based on the main query
[ "", "sql", "performance", "db2", "" ]
I was just after some input on database design. I have two tables, Orders and Items. The items table is going to be a list of items that can be used on multiple orders, each item has an id The way i thought to do it at the moment, was in the order to put an array of comma seperated ids for each item in the order. do...
As far as I have understood from your question (it is not very clear), every Order can have multiple Items and every Item can be used in multiple orders. If this is what you want, you have a many to many relationship, that must be resolved using an intersection entity. This intersection entity has 2 foreign keys, one f...
> The way I thought to do it at the moment, was in the order to put an array of comma separated ids for each item in the order. Does that sound like the best way? Absolutely not - It will be MUCH more difficult in SQL to determine which orders contain a particular item, enumerate the items (to get a total, for example...
database design, items and orders tables
[ "", "sql", "entity-framework", "" ]
I need to delete approximately 50 million of records (and not whole table) I searched and found some ways to do it This query does what i want, i can optimize it a little bit by storing results of sub queries in a `#TempTable` What else can i do? The fastest query so far : ``` CREATE TABLE #UserIDs ( UserId UNIQUEI...
If the number of records you want to preserve is small comparing to number of records you need to delete, I would copy them to temporary table, then TRUNCATE the original table and insert preserved records back from temporary table. Table truncation works very fast, so you may save much time. However TRUNCATE TABLE not...
Run part 1 first: ``` SELECT u.UserId INTO #DeleteThis FROM Users u LEFT JOIN tableX x ON u.UserId = x.UserId LEFT JOIN tableY y ON u.UserId = y.UserId WHERE SomeCondition IS NULL --SomeCondition is indexed AND x.UserId IS NULL AND y.UserId IS NULL ``` Then run part 2: ``` DELETE TOP (1000) FROM User...
Optimizing delete operation of 50 millions of records from table
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2008-r2", "" ]
When I don't use the SET command, I get results like: ``` SQL> select * from <tablename>; NAME PLACE AGE GENDER DESTINATION -------------- -------------- --------- ------------ --------------- Joy Scotland 22 Male California ``` ...
> [**SET PAGES[IZE] {14 | n}**](http://docs.oracle.com/cd/B19306_01/server.102/b14357/ch12040.htm#i2699247) > > Sets the number of rows on each page of output in iSQL\*Plus, and the > number of lines on each page of output in command-line and Windows > GUI. **You can set PAGESIZE to zero to suppress all headings**, pag...
To export data to csv-file via sqlplus I use a script like ``` set colsep ";" -- column separator set pagesize 0 -- no column headings set feedback off -- no "xx rows selected" set trimspool on -- no line-padding set linesize 9999 -- length of output line set verify off -- no output of parameter replacement...
SELECT doesn't display column names
[ "", "sql", "oracle", "sqlplus", "" ]
This is my code having a table with diff columns ``` CREATE TABLE IF NOT EXISTS `pcategories` ( `categoryid` int(11) NOT NULL AUTO_INCREMENT, `catimage` varbinary(max) not null, PRIMARY KEY (`categoryid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ; ``` i want to insert image in "catimage'column....
Your `INSERT` tells MySQ it will insert values into two columns (`categoryid` and `catimage`): ``` NSERT INTO `pcategories` (`categoryid`, `catimage`) VALUES ``` However, you then proceed to add three values (`9`, `Laptop computers`, and an image): ``` SELECT 9, 'Laptop Computers', BulkColumn FROM Openrowset( Bulk ...
try this for insert ``` $sql = "INSERT INTO pcategories (categoryid, catimage) VALUES (9, 'p2.gif')"; ```
Image not showing up in php though inserted in sql database
[ "", "sql", "phpmyadmin", "" ]
I have an SQL table with one column (dateRec) containing dates, format: yyyy-mm-dd. Is there a way in SQL that I can define date ranges and then group all the items by these ranges ? I would need the following groups here: * group one = 0 - 7 days old * group two = 8 - 14 days old * group three = 15 - 30 days old * g...
You need to do something like this ``` select t.range as [score range], count(*) as [number of occurences] from ( select case when score between 0 and 9 then ' 0-9 ' when score between 10 and 19 then '10-19' when score between 20 and 29 then '20-29' ... else '90-99' end as range from scores)...
Yes, you can do that by adding a new column which contains all the bands you require and then group by that column: ``` SELECT subject, dateRec, category ,case when datediff(day,dateRec,Getdate())<='7' then '0 - 7 days old' when datediff(day,dateRec,Getdate()...
SQL Server: group dates by ranges
[ "", "sql", "sql-server", "stored-procedures", "group-by", "" ]
Say I have the a table with 3 columns : Id, Category, Name. I would like to query the table that way : Get me the rows for which `{ Category = "Cat1" AND Name = "ABC" }` OR `{ Category = "Cat2" AND Name = "ABC" }` OR `{ Category = "Cat2" AND Name = "DEF" }` How? Without having to resort to a huge list of `WHERE OR` I...
You can create a temp table ``` create table #temp (Category varchar(50), Name varchar(50)) insert into #temp values ('Cat1', 'abc'), ('Cat2', 'cde'), ('Cat3', 'eee') ``` And then join your main table ``` select * from table1 inner join #temp on table1.Category = #temp.Category and table1.Name = #temp.Name ``` --- ...
@Szymon's answer is the best, but if you absolutely need to do it in one query you can come up with a scheme to concatenate the two columns into one string and join candidate values using the same method. Then you can use `IN` instead of a bunch of `ANDs` and `ORs`. ``` SELECT * FROM table WHERE Category + ':' + Name ...
How to query the database with a list of key-value pairs
[ "", "sql", "sql-server", "database", "" ]
Currently I'm working on a database redesign project. A large bulk of this project is pulling data from the old database and importing it into the new one. One of the columns in a table from the old database is called 'name'. It contains a forename and a surname all in one field (*ugh*). The new table has two columns;...
A quick solution is to use [SUBSTRING\_INDEX](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index) to get everything at the left of the first space, and everything past the first space: ``` UPDATE tablename SET Forename = SUBSTRING_INDEX(Name, ' ', 1), Surname = SUBSTRING_INDEX(Na...
Try this: ``` insert into new_table (forename, lastName, ...) select substring_index(name, ' ', 1), substring(name from instr(name, ' ') + 1), ... from old_table ``` This assumes the first word is the forename, and the rest the is lastname, which correctly handles multi-word last names like "John De Lacey"
Splitting a single column (name) into two (forename, surname) in SQL
[ "", "mysql", "sql", "" ]
Assuming the following table: ``` ID Name Revision --- ----- -------- 1 blah 0 2 yada 1 3 blah 1 4 yada 0 5 blah 2 6 blah 3 ``` How do I get the two records, one for "blah" and one for "yada" with highest revision number (3 for blah and 1 for yada)? Something ...
Basically, with the **aggregate function `MAX()`**: ``` SELECT "Name", MAX("Revision") AS max_revison FROM tbl WHERE "Name" IN ('blah', 'yada'); GROUP BY "Name" ORDER BY "Name"; -- ordering by revision would be pointless; ``` If you need *more columns* from the row, there are several ways. One would be to join...
This approach will select the rows for each Name with the maximum revision number for that Name. The result will be the exact output you were looking for in your post. ``` SELECT * FROM tbl a WHERE a.revision = (select max(revision) from tbl where name = a.name) ORDER BY a.name ```
Oracle query - select top records
[ "", "sql", "oracle11g", "greatest-n-per-group", "" ]
If I have two different types of user, Parent and Child. They have identical fields, however a Child has a one to many relationship with exams, a relationship that does not exist for Parents. Would Parent and Child best be modelled as a single table, or combined? What if I have two different types of user, Parent and...
> They have identical fields, however a Child has a one to many relationship with exams Even when fields are the same, different *constraints1* means you are dealing with logically separate entities. Absent other factors, separate entities should be put into separate physical tables. There may, however, be reasons to...
Parent and Child both are Persons without a doubt. You should never put them in seperate tables. Only time separates them : what if a Child becomes a parent? A parent easily can have children for that you need a relationship table. Als a relationship table is the right way to model school membership. so tables here ...
Grounds for having a one to one relationship between tables
[ "", "mysql", "sql", "database", "database-design", "database-schema", "" ]
I have a table like this: ``` CREATE TABLE [dbo].[Question] ( [QuesID] INT IDENTITY (1, 1) NOT NULL, [Body] NVARCHAR (MAX) NULL, [O1] NVARCHAR (MAX) NULL, [O2] NVARCHAR (MAX) NULL, [O3] NVARCHAR (MAX) NULL, [O4] NVARCHAR (MAX) NULL, [UserID] ...
``` insert into Question ([Body], [O1], [O2], [O3], [O4], [UserID]) select [Body], [O1], [O2], [O3], [O4], 'newUserID' from Question where UserID = N'admin' ```
In an `insert ... select` statement, you can easily replace a column by a literal value: ``` insert YourTable (UserID, col1, col2, ...) select N'anothervalue' , col1 , col2 , ... from YourTable where UserID = N'admin' ```
inserting some rows from one table to another by changing value of one column
[ "", "sql", "sql-server", "import", "" ]
The following query creates a list of all index names in the database a long with each column that is part of that index. Can someone tell me how to determine if the column is sorted ASC or DESC? ``` SELECT ind.name as index_name , t.[name] as table_name , col.name as column_name ...
Table [`sys.index_columns`](http://technet.microsoft.com/en-us/library/ms175105%28v=sql.105%29.aspx) has a column `is_descending_key` > 1 = Index key column has a descending sort direction. > 0 = Index key column has an ascending sort direction. > Does not apply to columnstore indexes which return 0.
If you have not specified any sorting order then by default it takes it as **ASCENDING**. Also you can add the **ORDER BY** statement to check that From [Creating Ascending and Descending Indexes](http://technet.microsoft.com/en-us/library/aa933132%28v=sql.80%29.aspx): > When defining indexes, you can specify whether...
How do I Programatically Determine if an Index Column is ASC or DESC
[ "", "sql", "sql-server", "sql-server-2008", "indexing", "" ]
There is a column of birthdates. To find the current age for display, the calculation is made as the following: ``` SELECT age(birth_date) FROM people ``` This returns records in the format `1 year 10 mons 3 days`. I have modified this slightly based on this [SO post](https://stackoverflow.com/questions/16990161/pos...
### `date_trunc()` Although the function [**`date_trunc()`** is listed in the table of date/time functions](http://www.postgresql.org/docs/current/interactive/functions-datetime.html#FUNCTIONS-DATETIME-TABLE) as taking an `timestamp` as argument, the manual clarifies further down: > `source` is a value expression of ...
You won't be able to meet that requirement with the built-in functions. At the very best, they'll allow you to transform 24 months in 2 years; not the other way around. You want to create a pgsql function that generates the desired output instead (possibly as text), or (better) manage this at the application level. Do...
Colloquial age calculation for display
[ "", "sql", "postgresql", "intervals", "" ]
I have the following query: ``` select title_id, shared_task_id from tasks_task order by title_id ``` The results are like so: ``` title_id shared_task_id 1 99217 1 NULL 4 18873 4 18874 4 18875 4 NULL 4 NULL 4 NULL ``` I want to find...
Sounds like a self join is the way to go. ``` select distinct t1.title_id, t1.shared_task_id from mytable t1 join mytable t2 on t1.shared_task_id = t2.shared_task_id and t1.title_id <> t2.title_id ```
This should do it: ``` SELECT t1.* FROM tasks_task t1 JOIN ( SELECT shared_task_id FROM tasks_task WHERE shared_task_id IS NOT NULL GROUP BY shared_task_id HAVING count(DISTINCT title_id) > 1 ) t2 ON t1.shared_task_id = t2.shared_task_id ``` Output: ``` | TITLE_ID | SHARED_TASK_ID | |----------|-------------...
SQL group by subselect
[ "", "mysql", "sql", "" ]
How can I retrieve data on time range where tickets issued between the times of 6am - 9:15am for the past month. I tried this but was wrong.Its in oracle and to\_char is not function name in SQL. how can i do that in sql. ``` select * from [ICPS].[dbo].[tickets] where t_date_time_issued > sysdate - 30 and to_ch...
Assuming that you want it in SQL-Server("Its in oracle and to\_char is not function name in SQL"), you can cast the `datetme` to `time`: ``` SELECT * FROM [dbo].[tickets] WHERE t_date_time_issued > DATEADD(mm, - 30, GetDate()) AND Cast(t_date_time_issued as TIME) between '06:00' and '09:10' ``` `Demo`
You can use `to_timestamp()` in stead of `to_char`. Details about `to_timestamp()` is: <http://docs.oracle.com/cd/B28359_01/olap.111/b28126/dml_functions_2118.htm#OLADM696> Hope will help!
get data on particular timings of the day in a month in SQL
[ "", "sql", "" ]
I wanted to know that, Suppose I have a table in one database with say 1000 records and I have similar table in another database with say 500 records. Now my question is If I will try to import data from say DB1.Tbl1 to DB2.Tbl1, then what will happen? Is there any possibilities of duplicacy of the data? I wanted the...
If you have same data in both tables you can first truncate 2nd table after that you can import data from 1st table by Insert Command or "import data" task
Try this ``` INSERT INTO DB1.dbo.Tbl1 SELECT * FROM DB2.dbo.Tbl2 ``` This just moves the data. If you want to move the table definition, you have to do something else. Note that, SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the d...
Importing Data From One database to another
[ "", "sql", "" ]
since oracle does not support null=null comparisons I did this statement: ``` SELECT p.nazwa, p.nazwa_miedz, p.dawka_l_p, p.dawka_j_p, p.dawka_l_n, p.dawka_j_n FROM produkt p WHERE p.nazwa_miedz LIKE (SELECT pp.nazwa_miedz FROM produkt pp ...
``` SELECT p.nazwa, p.nazwa_miedz, p.dawka_l_p, p.dawka_j_p, p.dawka_l_n, p.dawka_j_n FROM produkt p join product p2 on p.nazwa_miedz = p2.nazwa_miedz and (p.dawka_l_p = p2.dawka_l_p or p.dawka_l_p is NULL and p2.dawka_l_p is NULL) and (p.dawka_j_p = p2.dawka_j_p or p.dawka_j_p is NULL and p2....
A self join will probably work. This will show you the general idea. ``` SELECT p.nazwa, p.nazwa_miedz, p.dawka_l_p, p.dawka_j_p, p.dawka_l_n, p.dawka_j_n FROM produkt p join product p2 on p.dawka_l_p = p2.dawka_l_p and p.dawka_j_p = p2.dawka_j_p and p.dawka_l_n = p2.dawka_l_n...
Optimizing this query in oracle
[ "", "sql", "oracle", "query-optimization", "" ]
I am using VIsual Studio 2010 with Microsoft SQL Server and I am trying to write a query that will retrun the (3) most recent records in the database by the date field. Here are the fields in the database with columns; id | first\_name | last\_name | url | date Here is the current query I am using but it only returns...
try something like this: ``` SELECT TOP 3 id, first_name, last_name, url, date FROM tbl_paystubs ORDER BY date desc ```
You could find the max, then find the next date that is less than the max, then find the next date that is less than that max. Using CTEs: ``` WITH firstDate(id, first_name, last_name, url, date) as ( SELECT id, first_name, last_name, url, MAX(DISTINCT date) AS Expr1 FROM tbl_paystubs G...
How to select the 3 most recent rows using the date field
[ "", "sql", "sql-server", "visual-studio-2010", "" ]
I have a University project and I have to create a DB for a plant shop. I have a problem with the order table. At the moment it only allows a customer to buy one product at a time but in real life a customer can buy many products at a time. For example, We have a customer John Doe, and he buys two products that are i...
You have to create Kettle Table `customer_orders`, in this table you store `customer_id` and `order_id` and connect them with foreign keys to the customer and orders tables. Like in the following query: ``` CREATE TABLE customer_orders( customer_id INT(3), order_id INT(3), PRIMARY KEY(customer_id, order_id), ...
``` CREATE TABLE sales.stores ( store_id INT IDENTITY (1, 1) PRIMARY KEY, store_name VARCHAR (255) NOT NULL, phone VARCHAR (25), email VARCHAR (255), street VARCHAR (255), city VARCHAR (255), state VARCHAR (10), zip_code VARCHAR (5) ); ```
Shop database, SQL for order table
[ "", "sql", "" ]
I have a table that looks like this: ``` id value has_other color 1 banana 0 yellow 2 apple 1 red 3 apple 1 green 4 orange 0 orange 5 grape 0 red 6 grape 0 green ``` I want to make a query that selects all entries that has 'has\_ot...
This will return the results you are looking for: ``` SELECT t.* FROM myTable t INNER JOIN ( SELECT value FROM myTable WHERE has_other = 0 GROUP BY value HAVING count(*) > 1 ) a ON a.value = t.value WHERE t.has_other = 0; ``` `sqlfiddle demo`
``` select * from myTable where value in ( select value from myTable where has_other = 0 group by value having count(*) > 1 ) and has_other = 0 ```
SQL two or more with same properties
[ "", "mysql", "sql", "" ]
I have a SQL Server Scripts 2012 Project with multiple SQL queries and stored procedures. We use Team Foundation Server 2012 to manage our source code for our Visual Studio Solutions. How can I check in a SQL Server Scripts 2012 Project into TFS? If it is not possible how can I manage source control on this and allow...
You have a few options, here are two that I have used. **1: Download the TFS 2012 MSSCCI Provider:** This plugin allows you to access TFS from Microsoft SQL Server Management Studio. So you can easily add and check in\out those ssmssln and ssmsproj files from TFS. **[64bit Download](http://visualstudiogallery.msdn....
I'm not quite sure why it would be a challenge to add the sql server scripts to TFS just as any other file in your visual studio solution. I've done this in a lot of projects with great success. What is a challenge with databases though is to find a good strategy to handle branches and database versioning. I recommend...
SQL Server Scripts 2012 Project into Team Foundation Server 2012
[ "", "sql", "sql-server", "visual-studio-2012", "tfs", "ssms", "" ]
I'm using an Oracle database and I want to know how can I find rows in a varchar type column where the values of that column has a string which contains some character. I'm trying something like this (that's a simple example of what I want), but it doesn't work: ``` select p.name from person p where p.name contain...
By *lines* I assume you mean rows in the table `person`. What you're looking for is: ``` select p.name from person p where p.name LIKE '%A%'; --contains the character 'A' ``` The above is case sensitive. For a case insensitive search, you can do: ``` select p.name from person p where UPPER(p.name) LIKE '%A%'; ...
The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different. I think ADTC's solution is better, but mine's also works. Here is the other solution I found ``` select p.name from person p where instr(p.name,chr(8211)) > 0; --contains the character chr(8211) ...
Use string contains function in oracle SQL query
[ "", "sql", "oracle", "" ]
I want to copy records from one table to another. While doing this I want to set a flag of those records I copy. This is how I would do it (simplified): ``` BEGIN TRANSACTION copyTran insert into destination_table (name) select top 100 name from source_table WITH (TABLOCKX) order by id update source_tabl...
By leveraging [`OUTPUT`](http://technet.microsoft.com/en-us/library/ms177564%28v=sql.105%29.aspx) clause you can boil it down to a single `UPDATE` statement ``` UPDATE source_table SET copy_flag = 1 OUTPUT inserted.name INTO destination_table(name) WHERE id IN ( SELECT TOP 100 id FROM source_table OR...
The problem with your query is, that you may get different records in your `UPDATE` if someone inserts some data while you are running your query. It is saver to use the `INSERTED` keyword. ``` Declare @temp TABLE (Id integer); INSERT INTO destination_table (name) OUTPUT INSERTED.Id into @temp SELECT TOP 100 nam...
Update while copy records
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a Laboratory-Test table with 120 columns all with datatype `varchar` (which supposed to be `FLOAT`) but these columns also contain characters like `^,*,A-Z,a-z`, commas, sentences with full stop "." at the end. I am using the following function to keep all the numeric values including ".". The issue is this `.`...
Since you have SQL2012, you can take advantage of the [TRY\_CONVERT()](http://technet.microsoft.com/en-us/library/hh230993.aspx) function ``` CREATE FUNCTION [dbo].[RAC] (@input varchar(max)) RETURNS TABLE AS RETURN ( WITH number_list AS (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) i FROM sys.objects a) SELECT T...
You need a somewhat basic Regular Expression that will allow you to get digits with a single decimal between two sets of digits (or perhaps digits with no decimal at all). This requires using SQLCLR for the RegEx function. You can find numerous examples of those, or you can use the freely available SQLCLR library [SQL#...
Remove alphanumeric characters from the Varchar columns and then convert to Float
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I am hoping to get an answer to this problem. I am using SQL Developer to write queries, connected to an Oracle database. What I need is, if the query result is nothing (null or 0, I guess?), I still need something to show up. As of now, when the query result is nothing, then nothing but column headers come up. The c...
I think the query that you want uses conditional aggregation, instead of filtering in the `where` clause: ``` SELECT to_char(rs.cr_date, 'MM/DD/YYYY') as "Date", sum(case when rs.s_method Like '%RTS%' then 1 else 0 end) as "RTS Returned Orders" FROM return_sku rs join order_sku os on os.ord_sku_id = r...
You could do something like this: ``` select "date", sum('MM/DD/YYYY') "Date") from (select to_char(sysdate, 'MM/DD/YYYY') "Date" , 0 "'MM/DD/YYYY') "Date" from dual union SELECT to_char(rs.cr_date, 'MM/DD/YYYY') "Date", COUNT(os.ord_id) "RTS Returned Orders" FROM return_sku rs, order_sku os WHERE rs.s_method Lik...
How to Get a Query Result even if Result is 0 or Null
[ "", "sql", "oracle", "null", "" ]
I have been working now on a project for a period of time. The project has been released and is in production mode. We have now noticed that one of the tables that stores events for products is growing rapidly, it produces around 6.5 million rows each month give/take a few 100 000. This makes of course the database to...
Data archival can be tricky. You could copy the history to another database (perhaps on another server), which would help with your HDD space concerns. But even without talking about what you decide to do with the old data, once you delete it from your table, you shouldn't have to shrink your database. That space will ...
You also have option to do table partitioning. You could have several filegroups assign to different disks and allocate these resources to the table. SQL will do horizontal table partitioning based on values you specified. This is good overview for SQL table partitioning: <http://databases.about.com/od/sqlserver/a/par...
History tables in SQL Server
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
``` SELECT Id FROM Container_A JOIN Container_B ON Container_A.Container_B_FK = Container_B.Id ORDER BY Container_A.Id ``` This query return all elements of all Container\_A items related to Container\_B. The question is - How to get only first (with min Id) item related to each Container\_B item.
The problem with queries like this is that "first" has no meaning at all unless you specify what the order of the items are within the group. If you want the lowest item id, then you can group on the container b and use the `min` aggreagate to get the lowest item id from each group: ``` select b.Id, min(a.Id) as A...
``` SELECT top 1 *,min(Id) as minimum FROM Container_A JOIN Container_B ON Container_A.Container_B_FK = Container_B.Id group by Container_A.id,Container_B.id ORDER BY minimum ```
Return not all, but only first item of each joined table item
[ "", "sql", "sql-server", "join", "" ]
I have found some SQL queries in an application I am examining like this: ``` SELECT DISTINCT Company, Warehouse, Item, SUM(quantity) OVER (PARTITION BY Company, Warehouse, Item) AS stock ``` I'm quite sure this gives the same result as: ``` SELECT Company, Warehouse, Item, SUM(quantity) AS stock GROUP BY Company, W...
## Performance: **Winner: `GROUP BY`** Some very rudimentary testing on a large table with unindexed columns showed that at least in my case the two queries generated a completely different query plan. The one for `PARTITION BY` was significantly slower. The `GROUP BY` query plan included only a table scan and aggre...
Using `sum()` as an analytic function with `over partition by` is not necessary. I don't think there is a big difference between them in any sense. In oracle there are lot more analytic function than aggregation function. I think ms-sql is the same case. And for example `lag()`, `lead()`, `rank()`, `dense rank()`, etc ...
DISTINCT with PARTITION BY vs. GROUPBY
[ "", "sql", "sql-server", "group-by", "distinct", "query-performance", "" ]
I want to be able to list the 2nd lowest priced product sold for the day after i do queries on microsoft server sql studio 2008. (I know how to list the lowest thx to the guys who answered that question Here, but what if i just want to list the 2nd lowest, 3rd, or 4th lowest, but let just focus on how to list the 2nd l...
Give this a try: ``` SELECT date, product_sold, price FROM ( SELECT date, product_sold, price, DENSE_RANK() OVER (PARTITION BY date ORDER BY price) rank FROM sales ) t WHERE rank = 2 ``` Fiddle [here](http://sqlfiddle.com/#!6/6d46e/1). Note that if you have values `1`, `1` and `2` this will return `2`. If yo...
You are unclear about what to do about ties. Here is a solution using `dense_rank()`: ``` select date, product, price from (select s.*, dense_rank() over (partition by date order by price ) as seqnum from sales ) s where seqnum = 2; ```
Now I want to be able to list the 2nd lowest priced product sold for the day
[ "", "sql", "sql-server", "database", "" ]
I am using db2 9.5 i have created a column in table which is created successfully but i am not able to update table column and getting following error > [Error] Script lines: 1-1 -------------------------- > DB2 SQL error: SQLCODE: -668, SQLSTATE: 57016, SQLERRMC: 7;DB2ADMIN.XCATENTRYEXT > Message: Operation not allow...
It follows from the error message, that you somehow submit the entire string `Database["DB2"].ExecuteNonQuery("call SYSPROC.ADMIN_CMD ('REORG TABLE DB2ADMIN.XCATENTRYEXT index CATENTRY_ID INPLACE')")` as a SQL statement, which obviously is incorrect. Simply issue these on the shell command line: ``` db2 connect to <y...
It is possible to do REORG through an SQL statement: ``` CALL SYSPROC.ADMIN_CMD('REORG TABLE SCHEMA.TABLENAME'); ```
Failing update table in db2 with SQLCODE: -668, SQLSTATE: 57016, SQLERRMC: 7;
[ "", "sql", "database", "db2", "db2-luw", "" ]
Im working on a small school project where im creating a movie database in SQL. I've created the tables and was wondering if I will encounter any problems with the model i created. Thanks in advance. Current diagram ![enter image description here](https://i.stack.imgur.com/r4moC.png) Edit: Here is the new diagram ...
MovieDetails is bad design. You need one row in MovieDetails per actor, while the director will be the same, which is data duplication. Instead, the Movie table should have a foreign key referencing director, then a MovieActor table should represent the many to many relationship between movies and actors. Technically,...
How about (I am only showing the relevant columns) ``` movie table ----------- id title person ------ id name cast table ---------- movie_id person_id movie_role_id (actor, director, ...) role_type table ---------------- id name (actor, director, ...) genres table ------------ id name movie_genres table --...
SQL movie database diagram
[ "", "sql", "sql-server", "database", "diagram", "" ]
Consider the following Postgresql database table: ``` id | book_id | author_id --------------------------- 1 | 1 | 1 2 | 2 | 1 3 | 3 | 2 4 | 4 | 2 5 | 5 | 2 6 | 6 | 3 7 | 7 | 2 ``` In this example, Author 1 has written 2 books, Author 2 has...
``` select avg(totalbooks) from (select count(1) totalbooks from books group by author_id) bookcount ``` I think your example data actually only has 3 books for author id 2, so this would not return 2.3 <http://sqlfiddle.com/#!15/3e36e/1> With the 4th book: <http://sqlfiddle.com/#!15/67eac/1>
You'll need a subquery. The inner query will `count` the books with `GROUP BY author`; the outer query will scan the results of the inner query and `avg` them. You can use a subquery in the `FROM` clause for this, or you can use a CTE (`WITH` expression).
How do you determine the average total of a column in Postgresql?
[ "", "sql", "postgresql", "count", "average", "" ]
I am a bit lost here. I would like to join these two queries into one to avoid two connections and simplify the code. ``` "SELECT uname FROM Projects WHERE id IN (SELECT MAX(id) FROM Projects)" "SELECT name FROM Users WHERE username like"+"'"+ uname +"'" ``` Right now I am using two queries and taking the result o...
You can simply use `=` rather than `LIKE` since I you are not using pattern symbol such as `%`. ``` SELECT a.name FROM Users a INNER JOIN Projects b ON a.username = b.uname WHERE b.ID = (SELECT MAX(id) FROM Projects) ```
You may try like this using the `INNER JOIN` considering that both of your tables are linked through `User_ID` ``` SELECT u.name FROM Users u INNER JOIN Projects p ON u.username = p.uname WHERE p.ID = (SELECT MAX(id) FROM Projects) ```
SQL join two queries
[ "", "sql", "sql-server", "" ]
So i have 2 tables **Places** ``` PlaceID varchar PK PlaceName varchar ``` **Trips** ``` TripID int PK Depart TIME DepartPlc varchar ArrivalPlc varchar ArrivalTime TIME ``` `DepartPlc` and `ArrivalPlc` both have `PlaceID`'s stored. I want to select the data from trips, but show de `PlaceName` da...
Just JOIN Twice using two different table aliases ``` SELECT DPlaces.placeid D_PlaceID, Aplaces.placeid A_PlaceID FROM trips t INNER JOIN places DPlaces ON t.departplc = DPlaces.placename INNER JOIN places APlaces ON t.arrivalplc = aplaces.placename WHERE t.T...
You need to use the `places` table twice in your `from` clause: ``` select tripId, depart, departPlc as departPlaceId, dp.placeName as departPlaceName, arrivalPlc as arravalPlaceId, ap.placeName as arrivalPlaceName from trips as t inner join places as dp on t.departPlc = dp.placeId inner join...
SQL is this possible...it probably is
[ "", "sql", "sql-server", "" ]
I want to fill the calendar object which requires start and end date information. I have one column which contains a sequence of dates. Some of the dates are consecutive (have one day difference) and some are not. ``` InfoDate 2013-12-04 consecutive date [StartDate] 2013-12-05 consecutive date 2013-12-06 consecu...
No joins or recursive CTEs needed. The standard gaps-and-island solution is to group by (value minus row\_number), since that is invariant within a consecutive sequence. The start and end dates are just the MIN() and MAX() of the group. ``` WITH t AS ( SELECT InfoDate d,ROW_NUMBER() OVER(ORDER BY InfoDate) i FROM ...
Here you go.. ``` ;WITH CTEDATES AS ( SELECT ROW_NUMBER() OVER (ORDER BY Infodate asc ) AS ROWNUMBER,infodate FROM YourTableName ), CTEDATES1 AS ( SELECT ROWNUMBER, infodate, 1 as groupid FROM CTEDATES WHERE ROWNUMBER=1 UNION ALL SELECT a.ROWNUMBER, a.infodate,case datediff(d, b.infodate,a.infodate) w...
Detect consecutive dates ranges using SQL
[ "", "sql", "sql-server", "sql-server-2008", "gaps-and-islands", "" ]
I found something that I cannot resolve by my self. Lack of problem solving techniques... :( I need to get result to select each user with his id, and show their last login info, for example from this table: ``` id name loginTime logoutTime 3 test 2013-11-25 22:50:00...
``` select max(loginTime), id, name from your_table group by id, name ```
``` SELECT id, name, logintime, logouttime a from table where logintime=(select max(logintime) from table b where a.id = b.id) ```
distinct users, get last login info
[ "", "sql", "t-sql", "" ]
I'm trying to create a search function that uses a TextBox and two DropDownLists to return entries from my MSSQL DB. The way I have it set up is by passing the search queries via QueryStrings to a GridView on a separate page. Here's what I have for the search function: ``` Partial Class Includes_LeftCol Inherits Sys...
The problem is here: ``` Product_Rental BETWEEN @Product_Rental AND @Product_Rental + 50 ``` Because you are using `+ 50` [data type precedence](http://technet.microsoft.com/en-us/library/ms190309.aspx) kicks in. The docs state: > When an operator combines two expressions of different data types, the rules for data ...
The SQL Type INT is for whole numbers (1,2,3). FLOAT could support decimals. And text characters like [ and ] definitely won't work with an INT column. Edit from Comments: Since the Product\_Rental field is VarChar try changing to this (if you don't want to change the type on the table, which I recommend): ``` --Mak...
Conversion failed when converting the varchar value '[]' to data type int
[ "", "asp.net", "sql", "sql-server", "vb.net", "search", "" ]
I have searched far and wide for an answer to this problem. I'm using a Microsoft SQL Server, suppose I have a table that looks like this: ``` +--------+---------+-------------+-------------+ | ID | NUMBER | COUNTRY | LANG | +--------+---------+-------------+-------------+ | 1 | 3968 | UK ...
Since you don't care, I chose the max ID for each number. ``` select tbl.* from tbl inner join ( select max(id) as maxID, number from tbl group by number) maxID on maxID.maxID = tbl.id ``` --- **Query Explanation** ``` select tbl.* -- give me all the data from the base table (tbl) from tbl inn...
A very typical approach to this type of problem is to use `row_number()`: ``` select t.* from (select t.*, row_number() over (partition by number order by id) as seqnum from t ) t where seqnum = 1; ``` This is more generalizable than using a comparison to the minimum id. For instance, you can ...
SQL - select distinct only on one column
[ "", "sql", "sql-server", "unique", "distinct", "" ]
``` SELECT Count(*) FROM stu_empl_pers WHERE site_id = 'DEXLER'; ``` returns 22 records. but ``` SELECT Count(*) FROM stu_empl_pers a WHERE a.status = 'A' OR a.faculty = 1 OR a.staff = 1 AND a.site_id = 'DEXLER'; ``` returns 691 records.It considers different site\_id also.Ca...
> I need status=A and site\_id='dexler'as mandatory then, could you try this? ``` Select count(*) from stu_empl_pers a WHERE (a.faculty=1 OR a.staff=1) AND a.status='A' AND a.site_Id = 'DEXLER'; ```
``` WHERE a.status='A' or a.faculty=1 OR a.staff=1 AND a.site_Id = 'DEXLER'; (true/false or true/false or (true/false and true/false)) ``` maybe this will be more easier to see what your `WHERE` statement mean if one of `OR`s (except the one with `AND`) become true the record will be added to the result ...
Select statement gives different set of records
[ "", "mysql", "sql", "" ]
I need to filter some results from a query where the field must have more than a given length. I know that doesn't work, but it would be something like this: ``` SELECT * FROM MyTable WHERE COUNT(description) > 50 ``` Is that doable or will I have to filter that on PHP(in my case) later?
Given you're using MySQL, you're probably looking for `LENGTH()`. For standard SQL, the function is called `LEN()`. If you are dealing with UTF-8, you will have to use `CHAR_LENGTH()` as `LENGTH()` measures the length in bytes while `CHAR_LENGTH()` will correctly measure the length in characters.
``` SELECT * FROM MyTable WHERE LENGTH(description) < 50 ```
Filter results by the column length
[ "", "mysql", "sql", "" ]
this is my table 1: ``` NAME AGE SEX CITY ID Clara 22 f New York 1 Bob 33 m Washington 2 Sam 25 m Boston 3 ``` this is my table 2: ``` NUMBER ID 555-1111 1 555-2222 2 555-3333 ...
You only need one INSERT: ``` INSERT INTO destinationTable( name, age, sex, city, id, number, nationality) SELECT name, age, sex, city, s1.id, number, s3.nationality FROM sourceTable1 s1 INNER JOIN sourceTable2 s2 ON s2.Id = s1.Id INNER JOIN sourceTable3 s3 ON s3.Id = s1.Id ```
I would suggest instead of creating a new table, you just use a view that combines the two tables, this way if any of the data in table 1 or table 2 changes, you don't need to update the third table: ``` CREATE VIEW dbo.YourView AS SELECT t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number FROM Table1 t1 ...
SQL INSERT INTO from multiple tables
[ "", "sql", "sql-server", "" ]
I was reading in 2600, but this article is also here <https://viaforensics.com/mobile-security/static-code-analysis-watchtower.html> Anyways there is a code block: ``` $result = mysql_query("SELECT * FROM users WHERE username = '{$_GET['username']}' AND `password` = SHA1('{$_GET['password']}')") ``` The author says "...
If `username` was something like `'' OR ''=''#` and `password` was `'anything'` it would short circuit the query to become: ``` SELECT * FROM users WHERE username ='' OR ''=''#AND password ='anything' ``` You can short circuit the logic by injecting SQL into parameters.
Let us expand on Namphibian's answer a bit, the $\_GET['parameter'] is a parameter that is part of the URL, so it will look something like. ``` http://link/foo.php?username=thatguy&password=whoa ``` Where $\_GET['username'] is "thatguy" and $\_GET['password'] is "whoa" So let's put that in the code. ``` $result = m...
Can you spot the SQL injection?
[ "", "mysql", "sql", "code-injection", "" ]
So i'm writing a function for oracle db but I get errors saying that the sql statements were ignored and so expressions are missing. The function: ``` CREATE OR REPLACE FUNCTION getQueueNumber (student IN VARCHAR,course IN CHAR) RETURN INT IS queuePosition INT; date TIMESTAMP; BEGIN SELECT waitingDat...
What you're probably looking for, is error handling instead of just an if. ``` CREATE OR REPLACE FUNCTION getQueueNumber (p_student IN VARCHAR, p_course IN CHAR) RETURN INT IS queuePosition INT; v_date TIMESTAMP; BEGIN BEGIN SELECT waitingDate INTO v_date FROM WaitingCourseStudent wcs WHER...
``` SELECT waitingDate INTO date <--- (date is reserved keyword for denoting oracle datatype of date) FROM WaitingCourseStudent wcs WHERE wcs.student=student AND wcs.course=course; IF SQL%NOTFOUND THEN queuePosition := NULL; ``` Alternate suggestion : Prefix your variables with **v\_** or something like that t...
SQL statements ignored in PL/SQL
[ "", "sql", "oracle", "plsql", "" ]
I have a table: ``` Visit (FromId, ToId, VisitTime) ``` where FromId and ToId are FKs to table ``` UserProfile (uid, name, age ...) ``` As a user with my UID I want to select all profiles I have visited or who visited me in one result set ordered by VisitTime and with the indication of the "direction of the visit"....
``` SELECT CASE WHEN a.FromID = 'yourIDHere' THEN c.Name ELSE b.Name END Name, CASE WHEN a.FromID = 'yourIDHere' THEN c.Age ELSE b.Age END Age, a.VisitTime, CASE WHEN a.FromID = 'yourIDHere' THEN ...
You need two different sets of information (From's user profile, and To's user profile) depending on the direction of the visit. So you can: **do a double-JOIN combined with a lot of IF's** ``` SELECT IF ( FromId = f.uid, f.name, t.name ) AS name, IF ( FromId = f.uid, f.age, t.age ) AS age, ... F...
Are two selects needed?
[ "", "mysql", "sql", "" ]
I have inherited a SQL Server table in the (abbreviated) form of (includes sample data set): ``` | SID | name | Invite_Date | |-----|-------|-------------| | 101 | foo | 2013-01-06 | | 102 | bar | 2013-04-04 | | 101 | fubar | 2013-03-06 | ``` I need to select all `SID`'s and the `Invite_date`, ...
``` select t1.* from your_table t1 inner join ( select sid, max(CONVERT(DATE, Invite_date)) mdate from your_table group by sid ) t2 on t1.sid = t2.sid and CONVERT(DATE, t1.Invite_date) = t2.mdate ```
You can use a [ranking function](http://technet.microsoft.com/en-us/library/ms189798.aspx) like `ROW_NUMBER` or `DENSE_RANK` in a `CTE`: ``` WITH CTE AS ( SELECT SID, name, Invite_Date, rn = Row_Number() OVER (PARTITION By SID Order By Invite_Date DESC) FROM dbo.Tab...
SQL Server : select from duplicate columns where date newest
[ "", "sql", "sql-server", "" ]
I would like to pass a set of values as a parameter to an Sql Statement (in vb.net). **In my case:** Users are allowed to upload a set of IDs, to check availability of an item. I would like to execute a statement that will return the items that match any of the IDs by doing something like the following: ``` SELECT *...
you could pass the values in as XML and parse them using the XMLDOM. See: [here](http://psoug.org/reference/xml_functions.html) ``` DECLARE vXML VARCHAR2 (10000 CHAR) := '<ids><id>1</id><id>2</id><id>3</id></ids>'; BEGIN OPEN :refc FOR SELECT c."id" FROM XMLTABLE ('/ids/i...
From VB.net you can pass an "Associative array" to a SQL call. In PL/SQL create types and procedures like this: ``` CREATE OR REPLACE TYPE NUMBER_TABLE_TYPE AS TABLE OF NUMBER; CREATE OR REPLACE PACKAGE My_Package AS TYPE NUMBER_ARRAY_TYPE IS TABLE OF NUMBER INDEX BY BINARY_INTEGER; PROCEDURE My_Procedure(ar...
Is there a way to pass a set of values as a parameter in an Oracle SQL Statement
[ "", "sql", "oracle", "parameters", "set", "" ]
I want to know difference between these two key. When the Unique key with `not null` constrain in terms of how they are stored in database and what difference are there when we making `Select,Insert,Update, Delete` operation for these keys.
A primary key must be unique and non-null, so they're the same from that standpoint. However, a table can only have one primary key, while you can have multiple unique non-null keys. Most systems also use metadata to tag primary keys separately so that they can be identified by designers, etc. > What are the differen...
Yes! In general there is one huge difference in how unique keys and primary keys are stored in SQL Server 2008. A unique key **by default** (you can change that) will be created as a non-clustered index and a PK will be created as a clustered index **by default** (you can change that also). Non-clustered means it wil...
What is difference between unique key with 'not null' constraint and primary key?
[ "", "sql", "sql-server-2008", "" ]
I am trying to create a query for a report. I have a table of `licenses` and a table of `users`, and I have `license_assignments` as a many to many table to assign license seats to users: ``` mysql> CREATE TABLE license_assignments ( `uid` int(10) unsigned DEFAULT NULL, `lid` int(1) unsigned NOT NULL, `delta` int(10) ...
You are getting a cartesian product because one set is six rows with lid=2, and the other set has three rows with lid=2. Each row in a set is being matched with EVERY row in the other set. The problem with the JOIN here is that you need to guarantee that a row from set one will match at most one row from set two... yo...
The query is much simpler than you think :) ``` SELECT COUNT(*) all_licenses_count, COUNT(*) - COUNT(uid) unassigned_count FROM license_assignments WHERE lid = 2 ``` The `COUNT(*)` counts rows while `COUNT(uid)` counts rows that have `uid` not null. Output: ``` | ALL_LICENSES_COUNT | UNASSIGNED_COUNT | |-------...
Why am I getting a cartesian project with this join?
[ "", "mysql", "sql", "join", "" ]
I'm working on a query that doesn't seem to be doing what it's supposed to since being transferred from one SSRS server to another, and the following line in part of the where statement *appears* to be where the difference is, or at least from what I can find. ``` where COALESCE(field, -1) = CASE field WHEN 1 THEN 0 E...
Without context it's difficult to give a truly helpful answer. At first glance it looks as though it could be rewritten much more simply from this: ``` WHERE COALESCE(@field, -1) = CASE @field WHEN 1 THEN 0 ELSE -1 END ``` to this: ``` WHERE COALESCE(@field, -1) = -1 ``` If that is true then basically you are sayin...
> the first non-null value from the specified list of fields This means the list of fields between the parenthesis. For instance: ``` COALESCE(col1,col2,col3,-1) ``` means that if `col1` is not null then use this, else check `col2`. If `col2` is null then check `col3`. If that is null too then use -1 as the value. ...
coalesce and a case statement - explanation?
[ "", "sql", "t-sql", "sql-server-2008-r2", "" ]
i've a table in a database i would like to use as a contacts table to import into outlook. what i would like the import to do is this: name | email andy | ds@ds.com <--name and email entered at the moment i have this code: ``` (SELECT 'Name', 'Email') union all (select E_Name, Email INTO OUTFILE '/xampp/tmp/Sampl...
I found a solution to my problem. would slap myself. ``` SELECT * INTO OUTFILE '/xampp/tmp/Sample.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' FROM ( SELECT 'Name' AS `E_Name`, 'Email' AS `Email` UNION ALL SELECT `E_Name`, `Email` FROM `email` ) `sub_query` ``` before the new line i wasnt doing a re...
I find this situation often. The easiest way I know is by using `sed`, that is a command-line utility for Unix. Since you are working on Excel, I am assuming that you don't have a \*nix system (Linux, BSD, etc). So I recommend you install Cygwin (you can get it [here](http://www.cygwin.com/)). Then, open a Cygwin bas...
Column names from MySQL to CSV file
[ "", "mysql", "sql", "excel", "csv", "" ]
How do I check whether insertion will result in UNIQUE INDEX collision error without actually inserting something?
Run a SELECT query with unique column condition and if result data set isn't empty, it means will occur unique index error: ``` SELECT 1 FROM table WHERE unique_column = 'new_insert_value' LIMIT 1 ```
`INSERT` and catch the error. Is cheapest way, because it performs the lookup and actually does the insert on success. The problem with a separate check before the actual INSERT is, of course, concurrency. Multiple processes can do the check, all conclude that there will be no collision, and all decide to `INSERT`, onl...
Dry insert to check for index collisions
[ "", "mysql", "sql", "" ]
Is there a way to Select records between dates and specific time range. For example all the records from 2013-11-01 to 2013-11-30 between hours 05:00 to 15:00. Here what i made until now. ``` select count(*) as total from tradingaccounts accounts inner join tradingaccounts_audit audit on audit.parent_id = accounts...
You can use the `HOUR` function to add an additional condition on the hours: ``` select count(*) as total from tradingaccounts accounts inner join tradingaccounts_audit audit on audit.parent_id = accounts.id where date(audit.date_created) between date('2013-11-01 00:00:00') AND date('2013-11-01 23:59:59') AND HOUR (a...
As others answered, `HOUR()` could help you. But HOUR() or DATE() cannot use `INDEX`. To make query faster, I suggest that add `time_created TIME` column and save only TIME part. after that `ADD INDEX(date_created, time_created)`. finally with below query, you can retrieve rows with high speed. ``` where audit.date_c...
Select between date range and specific time range
[ "", "mysql", "sql", "select", "time", "" ]
``` Class| Value ------------- A | 1 A | 2 A | 3 A | 10 B | 1 ``` I am not sure whether it is practical to achieve this using SQL. If the difference of values are less than 5 (or x), then group the rows (of course with the same Class) Expected result ``` Class| ValueMin | ValueMax --------------------...
These give the correct result, using the fact that you must have the same number of group starts as ends and that they will both be in ascending order. ``` if object_id('tempdb..#temp') is not null drop table #temp create table #temp (class char(1),Value int); insert into #temp values ('A',1); insert into #temp valu...
You are trying to group things by gaps between values. The easiest way to do this is to use the `lag()` function to find the gaps: ``` select class, min(value) as minvalue, max(value) as maxvalue from (select class, value, sum(IsNewGroup) over (partition by class order by value) as GroupId from (sel...
SQL group by if values are close
[ "", "sql", "sql-server", "group-by", "subquery", "gaps-and-islands", "" ]
I have a simple select query - ``` SELECT ID, NAME FROM PERSONS WHERE NAME IN ('BBB', 'AAA', 'ZZZ') -- ORDER BY ??? ``` I want this result to be ordered by the sequence in which NAMES are provided, that is, 1st row in result set should be the one with NAME = BBB, 2nd is AAA, 3rd it ZZZ. Is this possible in SQL serv...
You could create an ordered split function: ``` CREATE FUNCTION [dbo].[SplitStrings_Ordered] ( @List NVARCHAR(MAX), @Delimiter NVARCHAR(255) ) RETURNS TABLE AS RETURN (SELECT [Index] = ROW_NUMBER() OVER (ORDER BY Number), Item FROM (SELECT Number, Item = SUBSTRING(@List, Number, CHARINDE...
You could store the names in a temp table with an order. Example: ``` DECLARE @Names TABLE ( Name VARCHAR(MAX), SortOrder INT ) INSERT INTO @Names (Name, SortOrder) VALUES ('BBB', 1) INSERT INTO @Names (Name, SortOrder) VALUES ('AAA', 2) INSERT INTO @Names (Name, SortOrder) VALUES ('ZZZ', 3) SELECT P.ID, P.N...
order by using terms in where clause
[ "", "sql", "sql-server", "" ]
Im trying to create a plugin for wordpress and I encounter a table with a structure like this ![enter image description here](https://i.stack.imgur.com/EFEVB.png) Sample data ![enter image description here](https://i.stack.imgur.com/0I0FL.png) How should my MySQL `Select` query look like if I want to get ``` user_...
In order to match the `field_id` with a particular value you'll have to match them in pairs `(field_id AND value)`. Then you will have to count the amount of matches. ``` SELECT user_id FROM wp_bp_xprofile_data t WHERE (field_id = 270 AND value = 'Gender') OR (field_id = 354 AND value = 'City') GROUP BY user_id ...
Assuming wp\_bp\_xprofile\_data is for table above, and `value` has real value rather than "Name", "Gender" etc. could you try this? ``` SELECT t1.user_id, t1.value, t2.value FROM wp_bp_xprofile_data t1 INNER JOIN wp_bp_xprofile_data t2 ON t1.user_id = t2.user_id WHERE t1.field_id = 270 AND t1.value = 'Mail' AND ...
Mysql Select on row values
[ "", "mysql", "sql", "" ]
I am using Oracle 10g and I have the following table: ``` create table DE_TRANSFORM_MAP ( DE_TRANSFORM_MAP_ID NUMBER(10) not null, CLIENT NUMBER(5) not null, USE_CASE NUMBER(38) not null, DE_TRANSFORM_NAME VARCHAR2(100) not null, IS_ACTIVE NUMBER(1) not null ) ``` That ma...
The error you get means that you cannot query the table the trigger is on from within a row level trigger itself. One way to work around this problem is to use a combination of 3 triggers. * a) A before statement level trigger * b) A row level trigger * c) An after statement level trigger Trigger A initializes a coll...
You should perhaps consider doing a "before insert" sort of thing! I've only got an MSSQL engine to play with right now, but hopefully something below might help you on your way... I'm not sure what you mean with your example of an error that works, however, as it appears to be in contradiction to the first use case yo...
Oracle 10g and data validation in a trigger before row update
[ "", "sql", "oracle", "triggers", "oracle10g", "" ]
I have a table named myvals with the following fields: ``` ID number -- ------- 1 7 2 3 3 4 4 0 5 9 ``` Starting on 2nd row, I would like to add the number with the previous row number. So, my end result would look like this ``` ID number -- ------ 1 7 2 10 3 7 4 4 5 ...
You could use the [LAG](http://technet.microsoft.com/en-us/library/hh231256.aspx) analytic function ``` SELECT Id, number + LAG(number,1,0) OVER (ORDER BY Id) FROM table ```
First thing's first. You can't add to null to ID 1 must have a value.
SQL - Add value with previous row only
[ "", "sql", "sql-server-2012", "" ]